edit-server.el 16 KB

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