edit-server.el 13 KB

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