edit-server.el 20 KB

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