edit-server.el 14 KB

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