edit-server.el 15 KB

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