edit-server.el 16 KB

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