edit-server.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. ;; Edit Server socket code
  90. ;
  91. (defun edit-server-start (&optional verbose)
  92. "Start the edit server.
  93. If argument VERBOSE is non-nil, logs all server activity to buffer `*edit-server-log*'.
  94. When called interactivity, a prefix argument will cause it to be verbose.
  95. "
  96. (interactive "P")
  97. (if (process-status "edit-server")
  98. (message "An edit-server process is already running")
  99. (make-network-process
  100. :name "edit-server"
  101. :buffer edit-server-process-buffer-name
  102. :family 'ipv4
  103. :host 'local ; only listen to local connections
  104. :service edit-server-port
  105. :log 'edit-server-accept
  106. :server 't)
  107. (setq edit-server-clients '())
  108. (if verbose (get-buffer-create edit-server-log-buffer-name))
  109. (edit-server-log nil "Created a new edit-server process")))
  110. (defun edit-server-stop nil
  111. "Stop the edit server"
  112. (interactive)
  113. (while edit-server-clients
  114. (edit-server-kill-client (car edit-server-clients))
  115. (setq edit-server-clients (cdr edit-server-clients)))
  116. (if (process-status "edit-server")
  117. (delete-process "edit-server")
  118. (message "No edit server running"))
  119. (if (get-buffer edit-server-process-buffer-name)
  120. (kill-buffer edit-server-process-buffer-name)))
  121. (defun edit-server-log (proc fmt &rest args)
  122. "If a `*edit-server-log*' buffer exists, write STRING to it for logging purposes.
  123. If `edit-server-verbose' is non-nil, then STRING is also echoed to the message line."
  124. (let ((string (apply 'format fmt args)))
  125. (if edit-server-verbose
  126. (message string))
  127. (if (get-buffer edit-server-log-buffer-name)
  128. (with-current-buffer edit-server-log-buffer-name
  129. (goto-char (point-max))
  130. (insert (current-time-string)
  131. " "
  132. (if (processp proc)
  133. (concat
  134. (buffer-name (process-buffer proc))
  135. ": ")
  136. "") ; nil is not acceptable to 'insert
  137. string)
  138. (or (bolp) (newline))))))
  139. (defun edit-server-accept (server client msg)
  140. "Accept a new client connection."
  141. (let ((buffer (generate-new-buffer edit-server-process-buffer-name)))
  142. (buffer-disable-undo buffer)
  143. (set-process-buffer client buffer)
  144. (set-process-filter client 'edit-server-filter)
  145. (set-process-query-on-exit-flag client nil) ; kill-buffer kills the associated process
  146. (with-current-buffer buffer
  147. (set (make-local-variable 'edit-server-phase) 'wait)
  148. (set (make-local-variable 'edit-server-received) 0)
  149. (set (make-local-variable 'edit-server-request) nil))
  150. (set (make-local-variable 'edit-server-content-length) nil))
  151. (add-to-list 'edit-server-clients client)
  152. (edit-server-log client msg))
  153. (defun edit-server-filter (proc string)
  154. "Process data received from the client."
  155. ;; there is no guarantee that data belonging to the same client
  156. ;; request will arrive all in one go; therefore, we must accumulate
  157. ;; data in the buffer and process it in different phases, which
  158. ;; requires us to keep track of the processing state.
  159. (with-current-buffer (process-buffer proc)
  160. (insert string)
  161. (setq edit-server-received
  162. (+ edit-server-received (string-bytes string)))
  163. (when (eq edit-server-phase 'wait)
  164. ;; look for a complete HTTP request string
  165. (save-excursion
  166. (goto-char (point-min))
  167. (when (re-search-forward "^\\([A-Z]+\\)\\s-+\\(\\S-+\\)\\s-+\\(HTTP/[0-9\.]+\\)\r?\n" nil t)
  168. (edit-server-log proc
  169. "Got HTTP `%s' request, processing in buffer `%s'..."
  170. (match-string 1) (current-buffer))
  171. (setq edit-server-request (match-string 1))
  172. (setq edit-server-content-length nil)
  173. (setq edit-server-phase 'head))))
  174. (when (eq edit-server-phase 'head)
  175. ;; look for "Content-length" header
  176. (save-excursion
  177. (goto-char (point-min))
  178. (when (re-search-forward "^Content-Length:\\s-+\\([0-9]+\\)" nil t)
  179. (setq edit-server-content-length (string-to-number (match-string 1)))))
  180. ;; look for head/body separator
  181. (save-excursion
  182. (goto-char (point-min))
  183. (when (re-search-forward "\\(\r?\n\\)\\{2\\}" nil t)
  184. ;; HTTP headers are pure ASCII (1 char = 1 byte), so we can subtract
  185. ;; the buffer position from the count of received bytes
  186. (setq edit-server-received
  187. (- edit-server-received (- (match-end 0) (point-min))))
  188. ;; discard headers - keep only HTTP content in buffer
  189. (delete-region (point-min) (match-end 0))
  190. (setq edit-server-phase 'body))))
  191. (when (eq edit-server-phase 'body)
  192. (if (and edit-server-content-length
  193. (> edit-server-content-length edit-server-received))
  194. (edit-server-log proc
  195. "Received %d bytes of %d ..."
  196. edit-server-received edit-server-content-length)
  197. ;; all content trasnferred - process request now
  198. (cond
  199. ((string= edit-server-request "POST")
  200. ;; create editing buffer, and move content to it
  201. (edit-server-create-edit-buffer proc))
  202. (t
  203. ;; send 200 OK response to any other request
  204. (edit-server-send-response proc "edit-server is running.\n" t)))
  205. ;; wait for another connection to arrive
  206. (setq edit-server-received 0)
  207. (setq edit-server-phase 'wait)))))
  208. (defun edit-server-create-edit-buffer(proc)
  209. "Create an edit buffer, place content in it and save the network
  210. process for the final call back"
  211. (let ((buffer (generate-new-buffer edit-server-edit-buffer-name)))
  212. (copy-to-buffer buffer (point-min) (point-max))
  213. (with-current-buffer buffer
  214. (edit-server-text-mode)
  215. (add-hook 'kill-buffer-hook 'edit-server-abort* nil t)
  216. (buffer-enable-undo)
  217. (set (make-local-variable 'edit-server-proc) proc)
  218. (set (make-local-variable 'edit-server-frame)
  219. (if edit-server-new-frame
  220. (make-frame-on-display (getenv "DISPLAY")) nil))
  221. (if edit-server-new-frame
  222. (raise-frame edit-server-frame)
  223. (pop-to-buffer buffer)))))
  224. (defun edit-server-send-response (proc &optional body close)
  225. "Send an HTTP 200 OK response back to process PROC.
  226. Optional second argument BODY specifies the response content:
  227. - If nil, the HTTP response will have null content.
  228. - If a string, the string is sent as response content.
  229. - Any other value will cause the contents of the current
  230. buffer to be sent.
  231. If optional third argument CLOSE is non-nil, then process PROC
  232. and its buffer are killed with `edit-server-kill-client'."
  233. (interactive)
  234. (if (processp proc)
  235. (let ((response-header (concat
  236. "HTTP/1.0 200 OK\n"
  237. "Server: Emacs\n"
  238. "Date: "
  239. (format-time-string
  240. "%a, %d %b %Y %H:%M:%S GMT\n"
  241. (current-time)))))
  242. (process-send-string proc response-header)
  243. (process-send-string proc "\n")
  244. (cond
  245. ((stringp body) (process-send-string proc body))
  246. ((not body) nil)
  247. (t (process-send-region proc (point-min) (point-max))))
  248. (process-send-eof proc)
  249. (if close
  250. (edit-server-kill-client proc))
  251. (edit-server-log proc "Editing done, sent HTTP OK response."))
  252. (message "edit-server-send-response: invalid proc (bug?)")))
  253. (defun edit-server-kill-client (proc)
  254. "Kill client process PROC and remove it from the list."
  255. (let ((procbuf (process-buffer proc)))
  256. (delete-process proc)
  257. (kill-buffer procbuf)
  258. (setq edit-server-clients (delq procbuf edit-server-clients))))
  259. (defun edit-server-done (&optional abort nokill)
  260. "Finish editing: send HTTP response back, close client and editing buffers.
  261. The current contents of the buffer are sent back to the HTTP
  262. client, unless argument ABORT is non-nil, in which case then the
  263. original text is sent back.
  264. If optional second argument NOKILL is non-nil, then the editing
  265. buffer is not killed.
  266. When called interactively, use prefix arg to abort editing."
  267. (interactive "P")
  268. (let ((buffer (current-buffer))
  269. (proc edit-server-proc)
  270. (procbuf (process-buffer edit-server-proc)))
  271. ;; edit-server-* vars are buffer-local, so they must be used before issuing kill-buffer
  272. (if abort
  273. ;; send back original content
  274. (with-current-buffer procbuf
  275. (run-hooks 'edit-server-done-hook)
  276. (edit-server-send-response proc t))
  277. ;; send back edited content
  278. (save-restriction
  279. (widen)
  280. (buffer-disable-undo)
  281. ;; ensure any format encoding is done (like longlines)
  282. (dolist (format buffer-file-format)
  283. (format-encode-region (point-min) (point-max) format))
  284. ;; send back
  285. (run-hooks 'edit-server-done-hook)
  286. (edit-server-send-response edit-server-proc t)
  287. ;; restore formats (only useful if we keep the buffer)
  288. (dolist (format buffer-file-format)
  289. (format-decode-region (point-min) (point-max) format))
  290. (buffer-enable-undo)))
  291. (if edit-server-frame (delete-frame edit-server-frame))
  292. ;; delete-frame may change the current buffer
  293. (unless nokill (kill-buffer buffer))
  294. (edit-server-kill-client proc)))
  295. (defun edit-server-abort ()
  296. "Discard editing and send the original text back to the browser."
  297. (interactive)
  298. (edit-server-done t))
  299. (defun edit-server-abort* ()
  300. "Discard editing and send the original text back to the browser,
  301. but don't kill the editing buffer."
  302. (interactive)
  303. (edit-server-done t t))
  304. (provide 'edit-server)
  305. ;;; edit-server.el ends here