edit-server.el 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. ;;; edit-server.el --- server that responds to edit requests from Chrome
  2. ;; Copyright (C) 2009-2011 Alex Bennee
  3. ;; Copyright (C) 2010-2011 Riccardo Murri
  4. ;; Author: Alex Bennee <alex@bennee.com>
  5. ;; Maintainer: Alex Bennee <alex@bennee.com>
  6. ;; Version: 1.10
  7. ;; Homepage: https://github.com/stsquad/emacs_chrome
  8. ;; This file is not part of GNU Emacs.
  9. ;; This file is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 3, or (at your option)
  12. ;; any later version.
  13. ;; This file is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; This provides an edit server to respond to requests from the Chrome
  21. ;; Emacs Chrome plugin. This is my first attempt at doing something
  22. ;; with sockets in Emacs. I based it on the following examples:
  23. ;;
  24. ;; http://www.emacswiki.org/emacs/EmacsEchoServer
  25. ;; http://nullprogram.com/blog/2009/05/17/
  26. ;;
  27. ;; To use it ensure the file is in your load-path and add something
  28. ;; like the following examples to your .emacs:
  29. ;;
  30. ;; To open pages for editing in new buffers in your existing Emacs
  31. ;; instance:
  32. ;;
  33. ;; (when (require 'edit-server nil t)
  34. ;; (setq edit-server-new-frame nil)
  35. ;; (edit-server-start))
  36. ;;
  37. ;; To open pages for editing in new frames using a running emacs
  38. ;; started in --daemon mode:
  39. ;;
  40. ;; (when (and (require 'edit-server nil t) (daemonp))
  41. ;; (edit-server-start))
  42. ;;
  43. ;; Buffers are edited in `text-mode' by default; to use a different
  44. ;; major mode, change `edit-server-default-major-mode' or customize
  45. ;; `edit-server-url-major-mode-alist' to specify major modes based
  46. ;; on the remote URL:
  47. ;;
  48. ;; (setq edit-server-url-major-mode-alist
  49. ;; '(("github\\.com" . markdown-mode)))
  50. ;;
  51. ;; Alternatively, set the mode in `edit-server-start-hook'. For
  52. ;; example:
  53. ;;
  54. ;; (add-hook 'edit-server-start-hook
  55. ;; (lambda ()
  56. ;; (when (string-match "github.com" (buffer-name))
  57. ;; (markdown-mode))))
  58. ;;; Code:
  59. ;; uncomment to debug
  60. ;; (setq debug-on-error t)
  61. ;; (setq edebug-all-defs t)
  62. (if (not (featurep 'make-network-process))
  63. (error "Incompatible version of [X]Emacs - lacks make-network-process"))
  64. ;;; Customization
  65. (defcustom edit-server-port 9292
  66. "Local port the edit server listens to."
  67. :group 'edit-server
  68. :type 'integer)
  69. (defcustom edit-server-host nil
  70. "If not nil, accept connections from HOST address rather than just
  71. localhost. This may present a security issue."
  72. :group 'edit-server
  73. :type 'boolean)
  74. (defcustom edit-server-verbose nil
  75. "If not nil, log connections and progress also to the echo area."
  76. :group 'edit-server
  77. :type 'boolean)
  78. (defcustom edit-server-done-hook nil
  79. "Hook run when done editing a buffer for the Emacs HTTP edit-server.
  80. Current buffer holds the text that is about to be sent back to the client."
  81. :group 'edit-server
  82. :type 'hook)
  83. (defcustom edit-server-start-hook nil
  84. "Hook run when starting a editing buffer. Current buffer is
  85. the fully prepared editing buffer. Use this hook to enable
  86. buffer-specific modes or add key bindings."
  87. :group 'edit-server
  88. :type 'hook)
  89. ;; frame options
  90. (defcustom edit-server-new-frame t
  91. "If not nil, edit each buffer in a new frame (and raise it)."
  92. :group 'edit-server
  93. :type 'boolean)
  94. (defcustom edit-server-new-frame-alist
  95. '((name . "Emacs TEXTAREA")
  96. (width . 80)
  97. (height . 25)
  98. (minibuffer . t)
  99. (menu-bar-lines . t))
  100. "Frame parameters for new frames. See `default-frame-alist' for examples.
  101. If nil, the new frame will use the existing `default-frame-alist' values."
  102. :group 'edit-server
  103. :type '(repeat (cons :format "%v"
  104. (symbol :tag "Parameter")
  105. (sexp :tag "Value"))))
  106. (defcustom edit-server-default-major-mode
  107. 'text-mode
  108. "The default major mode to use in editing buffers, if no other
  109. mode is selected by `edit-server-url-major-mode-alist'."
  110. :group 'edit-server
  111. :type 'function)
  112. (defcustom edit-server-url-major-mode-alist
  113. nil
  114. "A-list of patterns and corresponding functions; when the first
  115. pattern is encountered which matches `edit-server-url', the
  116. corresponding function will be called in order to set the desired
  117. major mode. If no pattern matches,
  118. `edit-server-default-major-mode' will be used."
  119. :group 'edit-server
  120. :type '(alist :key-type (string :tag "Regexp")
  121. :value-type (function :tag "Major mode function")))
  122. (defcustom edit-server-new-frame-mode-line t
  123. "Show the emacs frame's mode-line if set to t; hide if nil."
  124. :group 'edit-server
  125. :type 'boolean)
  126. ;;; Variables
  127. (defconst edit-server-process-buffer-name " *edit-server*"
  128. "Template name of the edit-server process buffers.")
  129. (defconst edit-server-log-buffer-name "*edit-server-log*"
  130. "Template name of the edit-server process buffers.")
  131. (defconst edit-server-edit-buffer-name "TEXTAREA"
  132. "Template name of the edit-server text editing buffers.")
  133. ;; Buffer local variables
  134. ;;
  135. ;; These are all required to associate the edit buffer with the
  136. ;; correct connection to the client and allow for the buffer to be sent
  137. ;; back when ready. They are `permanent-local` to avoid being reset if
  138. ;; the buffer changes major modes.
  139. (defvar edit-server-proc 'nil
  140. "Network process associated with the current edit, made local when
  141. the edit buffer is created")
  142. (put 'edit-server-proc 'permanent-local t)
  143. (defvar edit-server-frame nil
  144. "The frame created for a new edit-server process, made local when
  145. then edit buffer is created")
  146. (put 'edit-server-frame 'permanent-local t)
  147. (defvar edit-server-clients ()
  148. "List of all client processes associated with the server process.")
  149. (put 'edit-server-clients 'permanent-local t)
  150. (defvar edit-server-phase nil
  151. "Symbol indicating the state of the HTTP request parsing.")
  152. (put 'edit-server-phase 'permanent-local t)
  153. (defvar edit-server-received nil
  154. "Number of bytes received so far in the client buffer.
  155. Depending on the character encoding, may be different from the buffer length.")
  156. (put 'edit-server-received 'permanent-local t)
  157. (defvar edit-server-request nil
  158. "The HTTP request (GET, HEAD, POST) received.")
  159. (put 'edit-server-request 'permanent-local t)
  160. (defvar edit-server-content-length nil
  161. "The value gotten from the HTTP `Content-Length' header.")
  162. (put 'edit-server-content-length 'permanent-local t)
  163. (defvar edit-server-url nil
  164. "The value gotten from the HTTP `x-url' header.")
  165. (put 'edit-server-url 'permanent-local t)
  166. ;;; Mode magic
  167. ;;
  168. ;; We want to re-map some of the keys to trigger edit-server-done
  169. ;; instead of the usual emacs like behaviour. However using
  170. ;; local-set-key will affect all buffers of the same mode, hence we
  171. ;; define a special (derived) mode for handling editing of text areas.
  172. (defvar edit-server-edit-mode-map
  173. (let ((map (make-sparse-keymap)))
  174. (define-key map (kbd "C-x C-s") 'edit-server-save)
  175. (define-key map (kbd "C-x #") 'edit-server-done)
  176. (define-key map (kbd "C-c C-c") 'edit-server-done)
  177. (define-key map (kbd "C-x C-c") 'edit-server-abort)
  178. map)
  179. "Keymap for minor mode `edit-server-edit-mode'.
  180. Redefine a few common Emacs keystrokes to functions that can
  181. deal with the response to the edit-server request.
  182. Any of the following keys will close the buffer and send the text
  183. to the HTTP client: C-x #, C-c C-c.
  184. Pressing C-x C-s will save the current state to the kill-ring.
  185. If any of the above isused with a prefix argument, the
  186. unmodified text is sent back instead.")
  187. (define-minor-mode edit-server-edit-mode
  188. "Minor mode enabled on buffers opened by `edit-server-accept'.
  189. Its sole purpose is currently to enable
  190. `edit-server-edit-mode-map', which overrides common keystrokes to
  191. send a response back to the client."
  192. :group 'edit-server
  193. :lighter " EditSrv"
  194. :init-value nil
  195. :keymap edit-server-edit-mode-map)
  196. ;; Edit Server socket code
  197. (defun edit-server-start (&optional verbose)
  198. "Start the edit server.
  199. If argument VERBOSE is non-nil, logs all server activity to buffer
  200. `*edit-server-log*'. When called interactivity, a prefix argument
  201. will cause it to be verbose."
  202. (interactive "P")
  203. (if (or (process-status "edit-server")
  204. (null (condition-case err
  205. (make-network-process
  206. :name "edit-server"
  207. :buffer edit-server-process-buffer-name
  208. :family 'ipv4
  209. :host (if edit-server-host
  210. edit-server-host
  211. 'local)
  212. :service edit-server-port
  213. :log 'edit-server-accept
  214. :server t
  215. :noquery t)
  216. (file-error nil))))
  217. (message "An edit-server process is already running")
  218. (setq edit-server-clients '())
  219. (if verbose (get-buffer-create edit-server-log-buffer-name))
  220. (edit-server-log nil "Created a new edit-server process")))
  221. (defun edit-server-stop nil
  222. "Stop the edit server"
  223. (interactive)
  224. (while edit-server-clients
  225. (edit-server-kill-client (car edit-server-clients))
  226. (setq edit-server-clients (cdr edit-server-clients)))
  227. (if (process-status "edit-server")
  228. (delete-process "edit-server")
  229. (message "No edit server running"))
  230. (if (get-buffer edit-server-process-buffer-name)
  231. (kill-buffer edit-server-process-buffer-name)))
  232. (defun edit-server-log (proc fmt &rest args)
  233. "If a `*edit-server-log*' buffer exists, write STRING to it.
  234. This is done for logging purposes. If `edit-server-verbose' is
  235. non-nil, then STRING is also echoed to the message line."
  236. (let ((string (apply 'format fmt args)))
  237. (if edit-server-verbose
  238. (message string))
  239. (if (get-buffer edit-server-log-buffer-name)
  240. (with-current-buffer edit-server-log-buffer-name
  241. (goto-char (point-max))
  242. (insert (current-time-string)
  243. " "
  244. (if (processp proc)
  245. (concat
  246. (buffer-name (process-buffer proc))
  247. ": ")
  248. "") ; nil is not acceptable to 'insert
  249. string)
  250. (or (bolp) (newline))))))
  251. (defun edit-server-accept (server client msg)
  252. "Accept a new client connection."
  253. (let ((buffer (generate-new-buffer edit-server-process-buffer-name)))
  254. (and (fboundp 'set-buffer-multibyte)
  255. (set-buffer-multibyte t)) ; djb
  256. (buffer-disable-undo buffer)
  257. (set-process-buffer client buffer)
  258. (set-process-filter client 'edit-server-filter)
  259. ;; kill-buffer kills the associated process
  260. (set-process-query-on-exit-flag client nil)
  261. (with-current-buffer buffer
  262. (set (make-local-variable 'edit-server-phase) 'wait)
  263. (set (make-local-variable 'edit-server-received) 0)
  264. (set (make-local-variable 'edit-server-request) nil))
  265. (set (make-local-variable 'edit-server-content-length) nil)
  266. (set (make-local-variable 'edit-server-url) nil))
  267. (add-to-list 'edit-server-clients client)
  268. (edit-server-log client msg))
  269. (defun edit-server-filter (proc string)
  270. "Process data received from the client."
  271. ;; there is no guarantee that data belonging to the same client
  272. ;; request will arrive all in one go; therefore, we must accumulate
  273. ;; data in the buffer and process it in different phases, which
  274. ;; requires us to keep track of the processing state.
  275. (with-current-buffer (process-buffer proc)
  276. (insert string)
  277. (setq edit-server-received
  278. (+ edit-server-received (string-bytes string)))
  279. (when (eq edit-server-phase 'wait)
  280. ;; look for a complete HTTP request string
  281. (save-excursion
  282. (goto-char (point-min))
  283. (when (re-search-forward
  284. "^\\([A-Z]+\\)\\s-+\\(\\S-+\\)\\s-+\\(HTTP/[0-9\.]+\\)\r?\n"
  285. nil t)
  286. (edit-server-log
  287. proc "Got HTTP `%s' request, processing in buffer `%s'..."
  288. (match-string 1) (current-buffer))
  289. (setq edit-server-request (match-string 1))
  290. (setq edit-server-content-length nil)
  291. (setq edit-server-phase 'head))))
  292. (when (eq edit-server-phase 'head)
  293. ;; look for "Content-length" header
  294. (save-excursion
  295. (goto-char (point-min))
  296. (when (re-search-forward "^Content-Length:\\s-+\\([0-9]+\\)" nil t)
  297. (setq edit-server-content-length
  298. (string-to-number (match-string 1)))))
  299. ;; look for "x-url" header
  300. (save-excursion
  301. (goto-char (point-min))
  302. (when (re-search-forward "^x-url: .*//\\(.*\\)/" nil t)
  303. (setq edit-server-url (match-string 1))))
  304. ;; look for head/body separator
  305. (save-excursion
  306. (goto-char (point-min))
  307. (when (re-search-forward "\\(\r?\n\\)\\{2\\}" nil t)
  308. ;; HTTP headers are pure ASCII (1 char = 1 byte), so we can subtract
  309. ;; the buffer position from the count of received bytes
  310. (setq edit-server-received
  311. (- edit-server-received (- (match-end 0) (point-min))))
  312. ;; discard headers - keep only HTTP content in buffer
  313. (delete-region (point-min) (match-end 0))
  314. (setq edit-server-phase 'body))))
  315. (when (eq edit-server-phase 'body)
  316. (if (and edit-server-content-length
  317. (> edit-server-content-length edit-server-received))
  318. (edit-server-log proc
  319. "Received %d bytes of %d ..."
  320. edit-server-received edit-server-content-length)
  321. ;; all content transferred - process request now
  322. (cond
  323. ((string= edit-server-request "POST")
  324. ;; create editing buffer, and move content to it
  325. (edit-server-create-edit-buffer proc))
  326. (t
  327. ;; send 200 OK response to any other request
  328. (edit-server-send-response proc "edit-server is running.\n" t)))
  329. ;; wait for another connection to arrive
  330. (setq edit-server-received 0)
  331. (setq edit-server-phase 'wait)))))
  332. (defun edit-server-create-frame(buffer)
  333. "Create a frame for the edit server"
  334. (if edit-server-new-frame
  335. (let ((new-frame
  336. (if (memq window-system '(ns mac))
  337. ;; Aquamacs, Emacs NS, Emacs (experimental) Mac port
  338. (make-frame edit-server-new-frame-alist)
  339. (make-frame-on-display (getenv "DISPLAY")
  340. edit-server-new-frame-alist))))
  341. (if (not edit-server-new-frame-mode-line)
  342. (setq mode-line-format nil))
  343. (select-frame new-frame)
  344. (if (and (eq window-system 'x)
  345. (fboundp 'x-send-client-message))
  346. (x-send-client-message nil 0 nil
  347. "_NET_ACTIVE_WINDOW" 32
  348. '(1 0 0)))
  349. (raise-frame new-frame)
  350. (set-window-buffer (frame-selected-window new-frame) buffer)
  351. new-frame)
  352. (pop-to-buffer buffer)
  353. (raise-frame)
  354. nil))
  355. (defun edit-server-choose-major-mode ()
  356. "Use `edit-server-url-major-mode-alist' to choose a major mode
  357. initialization function based on `edit-server-url', or fall back
  358. to `edit-server-default-major-mode'"
  359. (let ((pairs edit-server-url-major-mode-alist)
  360. (mode edit-server-default-major-mode))
  361. (while pairs
  362. (let ((entry (car pairs)))
  363. (if (string-match (car entry) edit-server-url)
  364. (setq mode (cdr entry)
  365. pairs nil)
  366. (setq pairs (cdr pairs)))))
  367. (funcall mode)))
  368. (defun edit-server-create-edit-buffer(proc)
  369. "Create an edit buffer, place content in it and save the network
  370. process for the final call back"
  371. (let ((buffer (generate-new-buffer
  372. (if edit-server-url
  373. edit-server-url
  374. edit-server-edit-buffer-name))))
  375. (with-current-buffer buffer
  376. (and (fboundp 'set-buffer-multibyte)
  377. (set-buffer-multibyte t))) ; djb
  378. (copy-to-buffer buffer (point-min) (point-max))
  379. (with-current-buffer buffer
  380. (edit-server-choose-major-mode)
  381. ;; Allow `edit-server-start-hook' to override the major mode.
  382. ;; (re)setting the minor mode seems to clear the buffer-local
  383. ;; variables that we depend upon for the response, so call the
  384. ;; hooks early on
  385. (run-hooks 'edit-server-start-hook)
  386. (not-modified)
  387. (add-hook 'kill-buffer-hook 'edit-server-abort* nil t)
  388. (buffer-enable-undo)
  389. (set (make-local-variable 'edit-server-proc) proc)
  390. (set (make-local-variable 'edit-server-frame)
  391. (edit-server-create-frame buffer))
  392. (edit-server-edit-mode))))
  393. (defun edit-server-send-response (proc &optional body close)
  394. "Send an HTTP 200 OK response back to process PROC.
  395. Optional second argument BODY specifies the response content:
  396. - If nil, the HTTP response will have null content.
  397. - If a string, the string is sent as response content.
  398. - Any other value will cause the contents of the current
  399. buffer to be sent.
  400. If optional third argument CLOSE is non-nil, then process PROC
  401. and its buffer are killed with `edit-server-kill-client'."
  402. (interactive)
  403. (if (processp proc)
  404. (let ((response-header (concat
  405. "HTTP/1.0 200 OK\n"
  406. (format "Server: Emacs/%s\n" emacs-version)
  407. "Date: "
  408. (format-time-string
  409. "%a, %d %b %Y %H:%M:%S GMT\n"
  410. (current-time)))))
  411. (process-send-string proc response-header)
  412. (process-send-string proc "\n")
  413. (cond
  414. ((stringp body)
  415. (process-send-string proc (encode-coding-string body 'utf-8)))
  416. ((not body) nil)
  417. (t
  418. (encode-coding-region (point-min) (point-max) 'utf-8)
  419. (process-send-region proc (point-min) (point-max))))
  420. (process-send-eof proc)
  421. (if close
  422. (edit-server-kill-client proc))
  423. (edit-server-log proc "Editing done, sent HTTP OK response."))
  424. (message "edit-server-send-response: invalid proc (bug?)")))
  425. (defun edit-server-kill-client (proc)
  426. "Kill client process PROC and remove it from the list."
  427. (let ((procbuf (process-buffer proc)))
  428. (delete-process proc)
  429. (kill-buffer procbuf)
  430. (setq edit-server-clients (delq proc edit-server-clients))))
  431. (defun edit-server-done (&optional abort nokill)
  432. "Finish editing: send HTTP response back, close client and editing buffers.
  433. The current contents of the buffer are sent back to the HTTP
  434. client, unless argument ABORT is non-nil, in which case then the
  435. original text is sent back.
  436. If optional second argument NOKILL is non-nil, then the editing
  437. buffer is not killed.
  438. When called interactively, use prefix arg to abort editing."
  439. (interactive "P")
  440. ;; Do nothing if the connection is closed by the browser (tab killed, etc.)
  441. (unless (eq (process-status edit-server-proc) 'closed)
  442. (let ((buffer (current-buffer))
  443. (proc edit-server-proc)
  444. (procbuf (process-buffer edit-server-proc)))
  445. ;; edit-server-* vars are buffer-local,
  446. ;; so they must be used before issuing kill-buffer
  447. (if abort
  448. ;; send back original content
  449. (with-current-buffer procbuf
  450. (run-hooks 'edit-server-done-hook)
  451. (edit-server-send-response proc t))
  452. ;; send back edited content
  453. (save-restriction
  454. (widen)
  455. (buffer-disable-undo)
  456. ;; ensure any format encoding is done (like longlines)
  457. (dolist (format buffer-file-format)
  458. (format-encode-region (point-min) (point-max) format))
  459. ;; send back
  460. (run-hooks 'edit-server-done-hook)
  461. (edit-server-send-response edit-server-proc t)
  462. ;; restore formats (only useful if we keep the buffer)
  463. (dolist (format buffer-file-format)
  464. (format-decode-region (point-min) (point-max) format))
  465. (buffer-enable-undo)))
  466. (if edit-server-frame (delete-frame edit-server-frame))
  467. ;; delete-frame may change the current buffer
  468. (unless nokill (kill-buffer buffer))
  469. (edit-server-kill-client proc))))
  470. ;;
  471. ;; There are a couple of options for handling the save
  472. ;; action. The intent is to preserve data but not finish
  473. ;; editing. There are a couple of approaches that could
  474. ;; be taken:
  475. ;; a) Use the iterative edit-server option (send a buffer
  476. ;; back to the client which then returns new request
  477. ;; to continue the session).
  478. ;; b) Back-up the edit session to a file
  479. ;; c) Save the current buffer to the kill-ring
  480. ;;
  481. ;; I've attempted to do a) a couple of times but I keep running
  482. ;; into problems which I think are emacs bugs. So for now I'll
  483. ;; just push the current buffer to the kill-ring.
  484. (defun edit-server-save ()
  485. "Save the current state of the edit buffer."
  486. (interactive)
  487. (save-restriction
  488. (widen)
  489. (buffer-disable-undo)
  490. (copy-region-as-kill (point-min) (point-max))
  491. (buffer-enable-undo)))
  492. (defun edit-server-abort ()
  493. "Discard editing and send the original text back to the browser."
  494. (interactive)
  495. (edit-server-done t))
  496. (defun edit-server-abort* ()
  497. "Discard editing and send the original text back to the browser,
  498. but don't kill the editing buffer."
  499. (interactive)
  500. (edit-server-done t t))
  501. (provide 'edit-server)
  502. ;;; edit-server.el ends here