edit-server.el 19 KB

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