edit_server.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. ;;
  2. ;; Emacs edit-server
  3. ;;
  4. ;; This provides an edit server to respond to requests from the Chrome
  5. ;; Emacs Chrome plugin. This is my first attempt at doing something
  6. ;; with sockets in Emacs. I based it on the following examples:
  7. ;;
  8. ;; http://www.emacswiki.org/emacs/EmacsEchoServer
  9. ;; http://nullprogram.com/blog/2009/05/17/
  10. ;;
  11. ;; (C) 2009 Alex Bennee (alex@bennee.com)
  12. ;; (C) 2010 Riccardo Murri (riccardo.murri@gmail.com)
  13. ;;
  14. ;; Licensed under GPLv3
  15. ;;
  16. ;; uncomment to debug
  17. ;(setq debug-on-error 't)
  18. ;(setq edebug-all-defs 't)
  19. ;; Customization
  20. (defcustom edit-server-port 9292
  21. "Local port the edit server listens to."
  22. :group 'edit-server
  23. :type 'integer)
  24. (defcustom edit-server-new-frame t
  25. "If not nil, edit each buffer in a new frame (and raise it)."
  26. :group 'edit-server
  27. :type 'boolean)
  28. (defcustom edit-server-verbose nil
  29. "If not nil, log connections and progress also to the echo area."
  30. :group 'edit-server
  31. :type 'boolean)
  32. (defcustom edit-server-done-hook nil
  33. "Hook run when done editing a buffer for the Emacs HTTP edit-server.
  34. Current buffer holds the text that is about to be sent back to the client."
  35. :group 'edit-server
  36. :type 'hook)
  37. ;; Vars
  38. (defconst edit-server-process-buffer-name " *edit-server*"
  39. "Template name of the edit-server process buffers.")
  40. (defconst edit-server-log-buffer-name "*edit-server-log*"
  41. "Template name of the edit-server process buffers.")
  42. (defconst edit-server-edit-buffer-name "TEXTAREA"
  43. "Template name of the edit-server text editing buffers.")
  44. (defvar edit-server-proc 'nil
  45. "Network process associated with the current edit, made local when
  46. the edit buffer is created")
  47. (defvar edit-server-frame 'nil
  48. "The frame created for a new edit-server process, made local when
  49. then edit buffer is created")
  50. (defvar edit-server-clients '()
  51. "List of all client processes associated with the server process.")
  52. (defvar edit-server-phase nil
  53. "Symbol indicating the state of the HTTP request parsing.")
  54. (defvar edit-server-received nil
  55. "Number of bytes received so far in the client buffer.
  56. Depending on the character encoding, may be different from the buffer length.")
  57. (defvar edit-server-request nil
  58. "The HTTP request (GET, HEAD, POST) received.")
  59. (defvar edit-server-content-length nil
  60. "The value gotten from the HTTP `Content-Length' header.")
  61. ;; Mode magic
  62. ;
  63. ; We want to re-map some of the keys to trigger edit-server-done
  64. ; instead of the usual emacs like behaviour. However using
  65. ; local-set-key will affect all buffers of the same mode, hence we
  66. ; define a special (derived) mode for handling editing of text areas.
  67. ;
  68. (define-derived-mode edit-server-text-mode text-mode "Edit Server Text Mode"
  69. "A derived version of text-mode with a few common Emacs keystrokes
  70. rebound to more functions that can deal with the response to the
  71. edit-server request.
  72. Any of the following keys will close the buffer and send the text
  73. to the HTTP client: C-x #, C-x C-s, C-c C-c.
  74. If any of the above isused with a prefix argument, the
  75. unmodified text is sent back instead.
  76. "
  77. :group 'edit-server)
  78. (define-key edit-server-text-mode-map (kbd "C-x #") 'edit-server-done)
  79. (define-key edit-server-text-mode-map (kbd "C-x C-s") 'edit-server-done)
  80. (define-key edit-server-text-mode-map (kbd "C-c C-c") 'edit-server-done)
  81. ;; Edit Server socket code
  82. ;
  83. (defun edit-server-start (&optional verbose)
  84. "Start the edit server.
  85. If argument VERBOSE is non-nil, logs all server activity to buffer `*edit-server-log*'.
  86. When called interactivity, a prefix argument will cause it to be verbose.
  87. "
  88. (interactive "P")
  89. (if (process-status "edit-server")
  90. (message "An edit-server process is already running")
  91. (make-network-process
  92. :name "edit-server"
  93. :buffer edit-server-process-buffer-name
  94. :family 'ipv4
  95. :host 'local ; only listen to local connections
  96. :service edit-server-port
  97. :log 'edit-server-accept
  98. :server 't)
  99. (setq edit-server-clients '())
  100. (if verbose (get-buffer-create edit-server-log-buffer-name))
  101. (edit-server-log nil "Created a new edit-server process")))
  102. (defun edit-server-stop nil
  103. "Stop the edit server"
  104. (interactive)
  105. (while edit-server-clients
  106. (edit-server-kill-client (car edit-server-clients))
  107. (setq edit-server-clients (cdr edit-server-clients)))
  108. (if (process-status "edit-server")
  109. (delete-process "edit-server")
  110. (message "No edit server running"))
  111. (if (get-buffer edit-server-process-buffer-name)
  112. (kill-buffer edit-server-process-buffer-name)))
  113. (defun edit-server-log (proc fmt &rest args)
  114. "If a `*edit-server-log*' buffer exists, write STRING to it for logging purposes.
  115. If `edit-server-verbose' is non-nil, then STRING is also echoed to the message line."
  116. (let ((string (apply 'format fmt args)))
  117. (if edit-server-verbose
  118. (message string))
  119. (if (get-buffer edit-server-log-buffer-name)
  120. (with-current-buffer edit-server-log-buffer-name
  121. (goto-char (point-max))
  122. (insert (current-time-string)
  123. " "
  124. (if (processp proc)
  125. (concat
  126. (buffer-name (process-buffer proc))
  127. ": ")
  128. "") ; nil is not acceptable to 'insert
  129. string)
  130. (or (bolp) (newline))))))
  131. (defun edit-server-accept (server client msg)
  132. "Accept a new client connection."
  133. (let ((buffer (generate-new-buffer edit-server-process-buffer-name)))
  134. (buffer-disable-undo buffer)
  135. (set-process-buffer client buffer)
  136. (set-process-filter client 'edit-server-filter)
  137. (set-process-query-on-exit-flag client nil) ; kill-buffer kills the associated process
  138. (with-current-buffer buffer
  139. (set (make-local-variable 'edit-server-phase) 'wait)
  140. (set (make-local-variable 'edit-server-received) 0)
  141. (set (make-local-variable 'edit-server-request) nil))
  142. (set (make-local-variable 'edit-server-content-length) nil))
  143. (add-to-list 'edit-server-clients client)
  144. (edit-server-log client msg))
  145. (defun edit-server-filter (proc string)
  146. "Process data received from the client."
  147. ;; there is no guarantee that data belonging to the same client
  148. ;; request will arrive all in one go; therefore, we must accumulate
  149. ;; data in the buffer and process it in different phases, which
  150. ;; requires us to keep track of the processing state.
  151. (with-current-buffer (process-buffer proc)
  152. (insert string)
  153. (setq edit-server-received
  154. (+ edit-server-received (string-bytes string)))
  155. (when (eq edit-server-phase 'wait)
  156. ;; look for a complete HTTP request string
  157. (save-excursion
  158. (goto-char (point-min))
  159. (when (re-search-forward "^\\([A-Z]+\\)\\s-+\\(\\S-+\\)\\s-+\\(HTTP/[0-9\.]+\\)\r?\n" nil t)
  160. (edit-server-log proc
  161. "Got HTTP `%s' request, processing in buffer `%s'..."
  162. (match-string 1) (current-buffer))
  163. (setq edit-server-request (match-string 1))
  164. (setq edit-server-content-length nil)
  165. (setq edit-server-phase 'head))))
  166. (when (eq edit-server-phase 'head)
  167. ;; look for "Content-length" header
  168. (save-excursion
  169. (goto-char (point-min))
  170. (when (re-search-forward "^Content-Length:\\s-+\\([0-9]+\\)" nil t)
  171. (setq edit-server-content-length (string-to-number (match-string 1)))))
  172. ;; look for head/body separator
  173. (save-excursion
  174. (goto-char (point-min))
  175. (when (re-search-forward "\\(\r?\n\\)\\{2\\}" nil t)
  176. ;; HTTP headers are pure ASCII (1 char = 1 byte), so we can subtract
  177. ;; the buffer position from the count of received bytes
  178. (setq edit-server-received
  179. (- edit-server-received (- (match-end 0) (point-min))))
  180. ;; discard headers - keep only HTTP content in buffer
  181. (delete-region (point-min) (match-end 0))
  182. (setq edit-server-phase 'body))))
  183. (when (eq edit-server-phase 'body)
  184. (if (and edit-server-content-length
  185. (> edit-server-content-length edit-server-received))
  186. (edit-server-log proc
  187. "Received %d bytes of %d ..."
  188. edit-server-received edit-server-content-length)
  189. ;; all content trasnferred - process request now
  190. (cond
  191. ((string= edit-server-request "POST")
  192. ;; create editing buffer, and move content to it
  193. (edit-server-create-edit-buffer proc))
  194. (t
  195. ;; send 200 OK response to any other request
  196. (edit-server-send-response proc "edit-server is running.\n" t)))
  197. ;; wait for another connection to arrive
  198. (setq edit-server-received 0)
  199. (setq edit-server-phase 'wait)))))
  200. (defun edit-server-create-edit-buffer(proc)
  201. "Create an edit buffer, place content in it and save the network
  202. process for the final call back"
  203. (let ((buffer (generate-new-buffer edit-server-edit-buffer-name)))
  204. (copy-to-buffer buffer (point-min) (point-max))
  205. (with-current-buffer buffer
  206. (edit-server-text-mode)
  207. (add-hook 'kill-buffer-hook 'edit-server-abort* nil t)
  208. (buffer-enable-undo)
  209. (set (make-local-variable 'edit-server-proc) proc)
  210. (set (make-local-variable 'edit-server-frame)
  211. (if edit-server-new-frame
  212. (make-frame-on-display (getenv "DISPLAY")) nil))
  213. (if edit-server-new-frame
  214. (raise-frame edit-server-frame)
  215. (pop-to-buffer buffer)))))
  216. (defun edit-server-send-response (proc &optional body close)
  217. "Send an HTTP 200 OK response back to process PROC.
  218. Optional second argument BODY specifies the response content:
  219. - If nil, the HTTP response will have null content.
  220. - If a string, the string is sent as response content.
  221. - Any other value will cause the contents of the current
  222. buffer to be sent.
  223. If optional third argument CLOSE is non-nil, then process PROC
  224. and its buffer are killed with `edit-server-kill-client'."
  225. (interactive)
  226. (if (processp proc)
  227. (let ((response-header (concat
  228. "HTTP/1.0 200 OK\n"
  229. "Server: Emacs\n"
  230. "Date: "
  231. (format-time-string
  232. "%a, %d %b %Y %H:%M:%S GMT\n"
  233. (current-time)))))
  234. (process-send-string proc response-header)
  235. (process-send-string proc "\n")
  236. (cond
  237. ((stringp body) (process-send-string proc body))
  238. ((not body) nil)
  239. (t (process-send-region proc (point-min) (point-max))))
  240. (process-send-eof proc)
  241. (if close
  242. (edit-server-kill-client proc))
  243. (edit-server-log proc "Editing done, sent HTTP OK response."))
  244. (message "edit-server-send-response: invalid proc (bug?)")))
  245. (defun edit-server-kill-client (proc)
  246. "Kill client process PROC and remove it from the list."
  247. (let ((procbuf (process-buffer proc)))
  248. (delete-process proc)
  249. (kill-buffer procbuf)
  250. (setq edit-server-clients (delq procbuf edit-server-clients))))
  251. (defun edit-server-done (&optional abort nokill)
  252. "Finish editing: send HTTP response back, close client and editing buffers.
  253. The current contents of the buffer are sent back to the HTTP
  254. client, unless argument ABORT is non-nil, in which case then the
  255. original text is sent back.
  256. If optional second argument NOKILL is non-nil, then the editing
  257. buffer is not killed.
  258. When called interactively, use prefix arg to abort editing."
  259. (interactive "P")
  260. (let ((buffer (current-buffer))
  261. (proc edit-server-proc)
  262. (procbuf (process-buffer edit-server-proc)))
  263. ;; edit-server-* vars are buffer-local, so they must be used before issuing kill-buffer
  264. (if abort
  265. ;; send back original content
  266. (with-current-buffer procbuf
  267. (run-hooks 'edit-server-done-hook)
  268. (edit-server-send-response proc t))
  269. ;; send back edited content
  270. (save-restriction
  271. (widen)
  272. (buffer-disable-undo)
  273. ;; ensure any format encoding is done (like longlines)
  274. (dolist (format buffer-file-format)
  275. (format-encode-region (point-min) (point-max) format))
  276. ;; send back
  277. (run-hooks 'edit-server-done-hook)
  278. (edit-server-send-response edit-server-proc t)
  279. ;; restore formats (only useful if we keep the buffer)
  280. (dolist (format buffer-file-format)
  281. (format-decode-region (point-min) (point-max) format))
  282. (buffer-enable-undo)))
  283. (if edit-server-frame (delete-frame edit-server-frame))
  284. ;; delete-frame may change the current buffer
  285. (unless nokill (kill-buffer buffer))
  286. (edit-server-kill-client proc)))
  287. (defun edit-server-abort ()
  288. "Discard editing and send the original text back to the browser."
  289. (interactive)
  290. (edit-server-done t))
  291. (defun edit-server-abort* ()
  292. "Discard editing and send the original text back to the browser,
  293. but don't kill the editing buffer."
  294. (interactive)
  295. (edit-server-done t t))
  296. (provide 'edit-server)
  297. ;;; edit-server.el ends here