edit-server.el 16 KB

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