edit-server.el 16 KB

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