edit-server.el 13 KB

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