edit-server.el 14 KB

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