edit_server.el 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 (make-frame) nil))
  212. (if edit-server-new-frame
  213. (raise-frame edit-server-frame)
  214. (pop-to-buffer buffer)))))
  215. (defun edit-server-send-response (proc &optional body close)
  216. "Send an HTTP 200 OK response back to process PROC.
  217. Optional second argument BODY specifies the response content:
  218. - If nil, the HTTP response will have null content.
  219. - If a string, the string is sent as response content.
  220. - Any other value will cause the contents of the current
  221. buffer to be sent.
  222. If optional third argument CLOSE is non-nil, then process PROC
  223. and its buffer are killed with `edit-server-kill-client'."
  224. (interactive)
  225. (if (processp proc)
  226. (let ((response-header (concat
  227. "HTTP/1.0 200 OK\n"
  228. "Server: Emacs\n"
  229. "Date: "
  230. (format-time-string
  231. "%a, %d %b %Y %H:%M:%S GMT\n"
  232. (current-time)))))
  233. (process-send-string proc response-header)
  234. (process-send-string proc "\n")
  235. (cond
  236. ((stringp body) (process-send-string proc body))
  237. ((not body) nil)
  238. (t (process-send-region proc (point-min) (point-max))))
  239. (process-send-eof proc)
  240. (if close
  241. (edit-server-kill-client proc))
  242. (edit-server-log proc "Editing done, sent HTTP OK response."))
  243. (message "edit-server-send-response: invalid proc (bug?)")))
  244. (defun edit-server-kill-client (proc)
  245. "Kill client process PROC and remove it from the list."
  246. (let ((procbuf (process-buffer proc)))
  247. (delete-process proc)
  248. (kill-buffer procbuf)
  249. (setq edit-server-clients (delq procbuf edit-server-clients))))
  250. (defun edit-server-done (&optional abort nokill)
  251. "Finish editing: send HTTP response back, close client and editing buffers.
  252. The current contents of the buffer are sent back to the HTTP
  253. client, unless argument ABORT is non-nil, in which case then the
  254. original text is sent back.
  255. If optional second argument NOKILL is non-nil, then the editing
  256. buffer is not killed.
  257. When called interactively, use prefix arg to abort editing."
  258. (interactive "P")
  259. (let ((buffer (current-buffer))
  260. (proc edit-server-proc)
  261. (procbuf (process-buffer edit-server-proc)))
  262. ;; edit-server-* vars are buffer-local, so they must be used before issuing kill-buffer
  263. (if abort
  264. ;; send back original content
  265. (with-current-buffer procbuf
  266. (run-hooks 'edit-server-done-hook)
  267. (edit-server-send-response proc t))
  268. ;; send back edited content
  269. (run-hooks 'edit-server-done-hook)
  270. (edit-server-send-response edit-server-proc t))
  271. (if edit-server-frame (delete-frame edit-server-frame))
  272. ;; delete-frame may change the current buffer
  273. (unless nokill (kill-buffer buffer))
  274. (edit-server-kill-client proc)))
  275. (defun edit-server-abort ()
  276. "Discard editing and send the original text back to the browser."
  277. (interactive)
  278. (edit-server-done t))
  279. (defun edit-server-abort* ()
  280. "Discard editing and send the original text back to the browser,
  281. but don't kill the editing buffer."
  282. (interactive)
  283. (edit-server-done t t))
  284. (provide 'edit-server)
  285. ;;; edit-server.el ends here