edit-server.el 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. ;;; edit-server.el --- server that responds to edit requests from Chrome
  2. ;; Copyright (C) 2009-2013 Alex Bennée
  3. ;; Copyright (C) 2010-2011 Riccardo Murri
  4. ;; Author: Alex Bennée <alex@bennee.com>
  5. ;; Maintainer: Alex Bennée <alex@bennee.com>
  6. ;; Version: 1.14
  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. (unless (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. (defcustom edit-server-edit-mode-hook nil
  90. "Hook run when we enter edit-server-edit-mode. This is the final step of
  91. an edit session and is called when all frames and displays have been
  92. set-up. You should not set any additional major modes here though as they
  93. may conflict with the edit-server-edit-mode, use the
  94. edit-server-start-hook instead."
  95. :group 'edit-server
  96. :type 'hook)
  97. ;; frame options
  98. (defcustom edit-server-new-frame t
  99. "If not nil, edit each buffer in a new frame (and raise it)."
  100. :group 'edit-server
  101. :type 'boolean)
  102. (defcustom edit-server-new-frame-alist
  103. '((name . "Edit with Emacs FRAME")
  104. (width . 80)
  105. (height . 25)
  106. (minibuffer . t)
  107. (menu-bar-lines . t))
  108. "Frame parameters for new frames. See `default-frame-alist' for examples.
  109. If nil, the new frame will use the existing `default-frame-alist' values."
  110. :group 'edit-server
  111. :type '(repeat (cons :format "%v"
  112. (symbol :tag "Parameter")
  113. (sexp :tag "Value"))))
  114. (defcustom edit-server-default-major-mode
  115. 'text-mode
  116. "The default major mode to use in editing buffers, if no other
  117. mode is selected by `edit-server-url-major-mode-alist'."
  118. :group 'edit-server
  119. :type 'function)
  120. (defcustom edit-server-url-major-mode-alist
  121. nil
  122. "A-list of patterns and corresponding functions; when the first
  123. pattern is encountered which matches `edit-server-url', the
  124. corresponding function will be called in order to set the desired
  125. major mode. If no pattern matches,
  126. `edit-server-default-major-mode' will be used."
  127. :group 'edit-server
  128. :type '(alist :key-type (string :tag "Regexp")
  129. :value-type (function :tag "Major mode function")))
  130. (defcustom edit-server-new-frame-mode-line t
  131. "Show the emacs frame's mode-line if set to t; hide if nil."
  132. :group 'edit-server
  133. :type 'boolean)
  134. ;;; Variables
  135. (defconst edit-server-process-buffer-name " *edit-server*"
  136. "Template name of the edit-server process buffers.")
  137. (defconst edit-server-log-buffer-name "*edit-server-log*"
  138. "Name of the edit-server process buffers.")
  139. (defconst edit-server-edit-buffer-name "TEXTAREA"
  140. "Template name of the edit-server text editing buffers.")
  141. (defvar edit-server-clients ()
  142. "List of all client processes associated with the server process.")
  143. ;; Buffer local variables
  144. ;;
  145. ;; These are all required to associate the edit buffer with the
  146. ;; correct connection to the client and allow for the buffer to be sent
  147. ;; back when ready. They are `permanent-local` to avoid being reset if
  148. ;; the buffer changes major modes.
  149. (defvar edit-server-proc nil
  150. "Network process associated with the current edit.")
  151. (make-variable-buffer-local 'edit-server-proc)
  152. (put 'edit-server-proc 'permanent-local t)
  153. (defvar edit-server-frame nil
  154. "The frame created for a new edit-server process.")
  155. (make-variable-buffer-local 'edit-server-frame)
  156. (put 'edit-server-frame 'permanent-local t)
  157. (defvar edit-server-phase nil
  158. "Symbol indicating the state of the HTTP request parsing.")
  159. (make-variable-buffer-local 'edit-server-phase)
  160. (put 'edit-server-phase 'permanent-local t)
  161. (defvar edit-server-received nil
  162. "Number of bytes received so far in the client buffer.
  163. Depending on the character encoding, may be different from the buffer length.")
  164. (make-variable-buffer-local 'edit-server-received)
  165. (put 'edit-server-received 'permanent-local t)
  166. (defvar edit-server-request nil
  167. "The HTTP request (GET, HEAD, POST) received.")
  168. (make-variable-buffer-local 'edit-server-request)
  169. (put 'edit-server-request 'permanent-local t)
  170. (defvar edit-server-request-url nil
  171. "The HTTP request URL received.")
  172. (make-variable-buffer-local 'edit-server-request-url)
  173. (put 'edit-server-request-url 'permanent-local t)
  174. (defvar edit-server-content-length nil
  175. "The value gotten from the HTTP `Content-Length' header.")
  176. (make-variable-buffer-local 'edit-server-content-length)
  177. (put 'edit-server-content-length 'permanent-local t)
  178. (defvar edit-server-url nil
  179. "The value gotten from the HTTP `x-url' header.")
  180. (make-variable-buffer-local 'edit-server-url)
  181. (put 'edit-server-url 'permanent-local t)
  182. (defvar edit-server-file nil
  183. "The value gotten from the HTTP `x-file' header.")
  184. (make-variable-buffer-local 'edit-server-file)
  185. (put 'edit-server-file 'permanent-local t)
  186. ;;; Mode magic
  187. ;;
  188. ;; We want to re-map some of the keys to trigger edit-server-done
  189. ;; instead of the usual emacs like behaviour. However using
  190. ;; local-set-key will affect all buffers of the same mode, hence we
  191. ;; define a special (derived) mode for handling editing of text areas.
  192. (defvar edit-server-edit-mode-map
  193. (let ((map (make-sparse-keymap)))
  194. (define-key map (kbd "C-x C-s") 'edit-server-save)
  195. (define-key map (kbd "C-x #") 'edit-server-done)
  196. (define-key map (kbd "C-c C-c") 'edit-server-done)
  197. (define-key map (kbd "C-x C-c") 'edit-server-abort)
  198. map)
  199. "Keymap for minor mode `edit-server-edit-mode'.
  200. Redefine a few common Emacs keystrokes to functions that can
  201. deal with the response to the edit-server request.
  202. Any of the following keys will close the buffer and send the text
  203. to the HTTP client: C-x #, C-c C-c.
  204. Pressing C-x C-s will save the current state to the kill-ring.
  205. If any of the above isused with a prefix argument, the
  206. unmodified text is sent back instead.")
  207. (define-minor-mode edit-server-edit-mode
  208. "Minor mode enabled on buffers opened by `edit-server-accept'.
  209. Its sole purpose is currently to enable
  210. `edit-server-edit-mode-map', which overrides common keystrokes to
  211. send a response back to the client."
  212. :group 'edit-server
  213. :lighter " EditSrv"
  214. :init-value nil
  215. :keymap edit-server-edit-mode-map
  216. (when (and
  217. (numberp arg)
  218. (> arg 0))
  219. (run-hooks 'edit-server-edit-mode-hook)))
  220. (defun turn-on-edit-server-edit-mode-if-server ()
  221. "Turn on `edit-server-edit-mode' if in an edit-server buffer."
  222. (when edit-server-proc
  223. (edit-server-edit-mode t)))
  224. (define-globalized-minor-mode global-edit-server-edit-mode
  225. edit-server-edit-mode turn-on-edit-server-edit-mode-if-server)
  226. (global-edit-server-edit-mode t)
  227. ;; Edit Server socket code
  228. ;; Avoid an unnecessary prompt about active processes when exiting
  229. ;; emacs with no active edit-server clients
  230. ;; https://github.com/stsquad/emacs_chrome/issues/67
  231. ;;
  232. ;; According to http://emacswiki.org/emacs/AdviceVsHooks advice is a
  233. ;; sledgehammer which should be avoided if possible. However, the
  234. ;; only hooks run by save-buffers-kill-emacs are defined by
  235. ;; kill-emacs-query-functions and run *after* the check for active
  236. ;; processes which results in precisely the interactive prompt we want
  237. ;; to avoid when edit-server has no active clients. So it seems that
  238. ;; advice is the only solution until save-buffers-kill-emacs offers an
  239. ;; earlier hook.
  240. (defadvice save-buffers-kill-emacs
  241. (before edit-server-stop-before-kill-emacs)
  242. "Call `edit-server-stop' if there are no active clients, to
  243. avoid the user being prompted to kill the edit-server process."
  244. (or edit-server-clients (edit-server-stop)))
  245. ;;;###autoload
  246. (defun edit-server-start (&optional verbose)
  247. "Start the edit server.
  248. If argument VERBOSE is non-nil, logs all server activity to buffer
  249. `*edit-server-log*'. When called interactivity, a prefix argument
  250. will cause it to be verbose."
  251. (interactive "P")
  252. (if (or (process-status "edit-server")
  253. (null (condition-case err
  254. (let ((proc (make-network-process
  255. :name "edit-server"
  256. :buffer edit-server-process-buffer-name
  257. :family 'ipv4
  258. :host (or edit-server-host 'local)
  259. :service edit-server-port
  260. :log 'edit-server-accept
  261. :server t
  262. :noquery t)))
  263. (set-process-coding-system proc 'utf-8 'utf-8)
  264. proc)
  265. (file-error nil))))
  266. (message "An edit-server process is already running")
  267. (ad-activate 'save-buffers-kill-emacs)
  268. (setq edit-server-clients '())
  269. (when verbose (get-buffer-create edit-server-log-buffer-name))
  270. (edit-server-log nil "Created a new edit-server process")))
  271. (defun edit-server-stop nil
  272. "Stop the edit server"
  273. (interactive)
  274. (while edit-server-clients
  275. (edit-server-kill-client (car edit-server-clients))
  276. (setq edit-server-clients (cdr edit-server-clients)))
  277. (if (process-status "edit-server")
  278. (delete-process "edit-server")
  279. (message "No edit server running"))
  280. (when (get-buffer edit-server-process-buffer-name)
  281. (kill-buffer edit-server-process-buffer-name))
  282. (ad-disable-advice 'save-buffers-kill-emacs
  283. 'before 'edit-server-stop-before-kill-emacs)
  284. ;; Disabling advice doesn't take effect until you (re-)activate
  285. ;; all advice for the function.
  286. (ad-activate 'save-buffers-kill-emacs))
  287. (defun edit-server-log (proc fmt &rest args)
  288. "If a `*edit-server-log*' buffer exists, write STRING to it.
  289. This is done for logging purposes. If `edit-server-verbose' is
  290. non-nil, then STRING is also echoed to the message line."
  291. (let ((string (apply 'format fmt args)))
  292. (when edit-server-verbose
  293. (message string))
  294. (when (get-buffer edit-server-log-buffer-name)
  295. (with-current-buffer edit-server-log-buffer-name
  296. (goto-char (point-max))
  297. (insert (current-time-string)
  298. " "
  299. (if (processp proc)
  300. (concat
  301. (buffer-name (process-buffer proc))
  302. ": ")
  303. "") ; nil is not acceptable to 'insert
  304. string)
  305. (or (bolp) (newline))))))
  306. (defun edit-server-accept (server client msg)
  307. "Accept a new client connection."
  308. (let ((buffer (generate-new-buffer edit-server-process-buffer-name)))
  309. (buffer-disable-undo buffer)
  310. (set-process-buffer client buffer)
  311. (set-process-filter client 'edit-server-filter)
  312. ;; kill-buffer kills the associated process
  313. (set-process-query-on-exit-flag client nil)
  314. (with-current-buffer buffer
  315. (setq edit-server-phase 'wait
  316. edit-server-received 0
  317. edit-server-request nil
  318. edit-server-request-url nil))
  319. (setq edit-server-content-length nil
  320. edit-server-url nil
  321. edit-server-file nil))
  322. (add-to-list 'edit-server-clients client)
  323. (edit-server-log client msg))
  324. (defun edit-server-filter (proc string)
  325. "Process data received from the client."
  326. ;; there is no guarantee that data belonging to the same client
  327. ;; request will arrive all in one go; therefore, we must accumulate
  328. ;; data in the buffer and process it in different phases, which
  329. ;; requires us to keep track of the processing state.
  330. (with-current-buffer (process-buffer proc)
  331. (insert string)
  332. (setq edit-server-received
  333. (+ edit-server-received (string-bytes string)))
  334. (when (eq edit-server-phase 'wait)
  335. ;; look for a complete HTTP request string
  336. (save-excursion
  337. (goto-char (point-min))
  338. (when (re-search-forward
  339. "^\\([A-Z]+\\)\\s-+\\(\\S-+\\)\\s-+\\(HTTP/[0-9\.]+\\)\r?\n"
  340. nil t)
  341. (setq edit-server-request (match-string 1)
  342. edit-server-request-url (match-string 2)
  343. edit-server-content-length nil
  344. edit-server-phase 'head)
  345. (edit-server-log
  346. proc "Got HTTP `%s' request of url `%s', processing in buffer `%s'..."
  347. edit-server-request edit-server-request-url (current-buffer)))))
  348. (when (eq edit-server-phase 'head)
  349. ;; look for "Content-length" header
  350. (save-excursion
  351. (goto-char (point-min))
  352. (when (re-search-forward "^Content-Length:\\s-+\\([0-9]+\\)" nil t)
  353. (setq edit-server-content-length
  354. (string-to-number (match-string 1)))))
  355. ;; look for "x-url" header
  356. (save-excursion
  357. (goto-char (point-min))
  358. (when (re-search-forward "^x-url: .*/\\{2,3\\}\\([^\r\n]+\\)" nil t)
  359. (setq edit-server-url (match-string 1))))
  360. ;; look for "x-file" header
  361. (save-excursion
  362. (goto-char (point-min))
  363. (when (re-search-forward "^x-file: \\([^\r\n]+\\)" nil t)
  364. (edit-server-log proc "Found x-file: %s" (match-string 1))
  365. (setq edit-server-file (match-string 1))))
  366. ;; look for head/body separator
  367. (save-excursion
  368. (goto-char (point-min))
  369. (when (re-search-forward "\\(\r?\n\\)\\{2\\}" nil t)
  370. ;; HTTP headers are pure ASCII (1 char = 1 byte), so we can subtract
  371. ;; the buffer position from the count of received bytes
  372. (setq edit-server-received
  373. (- edit-server-received (- (match-end 0) (point-min))))
  374. ;; discard headers - keep only HTTP content in buffer
  375. (delete-region (point-min) (match-end 0))
  376. (edit-server-log proc
  377. "Processed headers, length: %s, url: %s, file: %s"
  378. edit-server-content-length edit-server-url edit-server-file)
  379. (setq edit-server-phase 'body))))
  380. (when (eq edit-server-phase 'body)
  381. (if (and edit-server-content-length
  382. (> edit-server-content-length edit-server-received))
  383. (edit-server-log proc
  384. "Received %d bytes of %d ..."
  385. edit-server-received edit-server-content-length)
  386. ;; all content transferred - process request now
  387. (cond
  388. ((string-match "foreground" edit-server-request-url)
  389. (edit-server-foreground-request (current-buffer))
  390. (edit-server-send-response proc "edit-server received foreground request.\n")
  391. (edit-server-kill-client proc))
  392. ((string= edit-server-request "POST")
  393. ;; create editing buffer, and move content to it
  394. (edit-server-find-or-create-edit-buffer proc edit-server-file))
  395. (t
  396. ;; send 200 OK response to any other request
  397. (edit-server-send-response proc "edit-server is running.\n")
  398. (edit-server-kill-client proc)))
  399. ;; wait for another connection to arrive
  400. (setq edit-server-received 0)
  401. (setq edit-server-phase 'wait)))))
  402. (defun edit-server-foreground-request (buffer)
  403. "Bring Emacs into the foreground after a request from Chrome.
  404. `buffer' is the process buffer which contains any potential contents
  405. to be passed into the kill ring.
  406. The new frame will have a specific frame parameter of
  407. `edit-server-forground-frame' set to 't"
  408. (when (bufferp buffer)
  409. (with-current-buffer buffer
  410. (kill-ring-save (point-min) (point-max))))
  411. (when edit-server-new-frame
  412. (set-frame-parameter
  413. (make-frame-on-display (getenv "DISPLAY")
  414. edit-server-new-frame-alist)
  415. 'edit-server-forground-frame 't)))
  416. (defun edit-server-show-edit-buffer (buffer)
  417. "Show edit `BUFFER' by creating a frame or raising the selected
  418. frame. If a frame was created it returns `FRAME'."
  419. (let ((edit-frame nil))
  420. (when edit-server-new-frame
  421. (setq edit-frame
  422. (if (memq window-system '(ns mac nil))
  423. ;; Aquamacs, Emacs NS, Emacs (experimental) Mac port, termcap.
  424. ;; matching (nil) avoids use of DISPLAY from TTY environments.
  425. (make-frame edit-server-new-frame-alist)
  426. (make-frame-on-display (getenv "DISPLAY")
  427. edit-server-new-frame-alist)))
  428. (unless edit-server-new-frame-mode-line
  429. (setq mode-line-format nil))
  430. (select-frame edit-frame)
  431. (when (and (eq window-system 'x)
  432. (fboundp 'x-send-client-message))
  433. (x-send-client-message nil 0 nil
  434. "_NET_ACTIVE_WINDOW" 32
  435. '(1 0 0))))
  436. (pop-to-buffer buffer)
  437. (raise-frame edit-frame)
  438. (select-frame-set-input-focus (window-frame (selected-window)))
  439. edit-frame))
  440. (defun edit-server-choose-major-mode ()
  441. "Use `edit-server-url-major-mode-alist' to choose a major mode
  442. initialization function based on `edit-server-url', or fall back
  443. to `edit-server-default-major-mode'"
  444. (funcall (or (assoc-default edit-server-url
  445. edit-server-url-major-mode-alist 'string-match)
  446. edit-server-default-major-mode)))
  447. (defun edit-server-find-or-create-edit-buffer (proc &optional existing)
  448. "Find and existing or create an new edit buffer, place content in it
  449. and save the network process for the final call back"
  450. ;; FIXME: `existing' is useless: see issue #104.
  451. (let* ((existing-buffer (and (stringp existing) (get-buffer existing)))
  452. (buffer (or existing-buffer (generate-new-buffer
  453. (or edit-server-url
  454. edit-server-edit-buffer-name)))))
  455. (edit-server-log proc
  456. "using buffer %s for edit (existing-buffer is %s)"
  457. buffer existing-buffer)
  458. ;; set multi-byte for proper UTF-8 handling (djb)
  459. (when (fboundp 'set-buffer-multibyte)
  460. (with-current-buffer buffer
  461. (set-buffer-multibyte t)))
  462. ;; I seem to be working around a bug here :-/
  463. ;;
  464. ;; For some reason the copy-to-buffer doesn't blat the existing contents.
  465. ;; This screws up formatting as the contents were decoded before being
  466. ;; sent back to the browser. As a kludge I save the returned contents
  467. ;; in the kill-ring.
  468. (when existing-buffer
  469. (kill-ring-save (point-min) (point-max)))
  470. (edit-server-log proc "copying new data into buffer")
  471. (copy-to-buffer buffer (point-min) (point-max))
  472. (with-current-buffer buffer
  473. (setq edit-server-url (with-current-buffer (process-buffer proc) edit-server-url))
  474. (edit-server-choose-major-mode)
  475. ;; Allow `edit-server-start-hook' to override the major mode.
  476. ;; (re)setting the minor mode seems to clear the buffer-local
  477. ;; variables that we depend upon for the response, so call the
  478. ;; hooks early on
  479. (run-hooks 'edit-server-start-hook)
  480. (set-buffer-modified-p 'nil)
  481. (add-hook 'kill-buffer-hook 'edit-server-abort* nil t)
  482. (buffer-enable-undo)
  483. (setq edit-server-proc proc
  484. edit-server-frame (edit-server-show-edit-buffer buffer))
  485. (edit-server-edit-mode))))
  486. (defun edit-server-send-response (proc &optional body progress)
  487. "Send an HTTP 200 OK response back to process PROC.
  488. Optional second argument BODY specifies the response content:
  489. - If nil, the HTTP response will have null content.
  490. - If a string, the string is sent as response content.
  491. - Any other value will cause the contents of the current
  492. buffer to be sent.
  493. If optional third argument progress is non-nil, then the response
  494. will include x-file and x-open headers to allow continuation of editing."
  495. (interactive)
  496. (edit-server-log proc "sending edit-server response")
  497. (if (processp proc)
  498. (let ((response-header (concat
  499. "HTTP/1.0 200 OK\n"
  500. (format "Server: Emacs/%s\n" emacs-version)
  501. "Date: "
  502. (format-time-string
  503. "%a, %d %b %Y %H:%M:%S GMT\n"
  504. (current-time))
  505. (when progress
  506. (format "x-file: %s\nx-open: true\n" (buffer-name))))))
  507. (process-send-string proc response-header)
  508. (process-send-string proc "\n")
  509. (cond
  510. ((stringp body)
  511. (process-send-string proc (encode-coding-string body 'utf-8)))
  512. ((not body) nil)
  513. (t
  514. (encode-coding-region (point-min) (point-max) 'utf-8)
  515. (process-send-region proc (point-min) (point-max))))
  516. (process-send-eof proc)
  517. (edit-server-log proc "Editing done, sent HTTP OK response."))
  518. (message "edit-server-send-response: invalid proc (bug?)")))
  519. (defun edit-server-kill-client (proc)
  520. "Kill client process PROC and remove it from the list."
  521. (let ((procbuf (process-buffer proc)))
  522. (delete-process proc)
  523. (when (buffer-live-p procbuf)
  524. (kill-buffer procbuf))
  525. (setq edit-server-clients (delq proc edit-server-clients))))
  526. (defun edit-server-done (&optional abort nokill)
  527. "Finish editing: send HTTP response back, close client and editing buffers.
  528. The current contents of the buffer are sent back to the HTTP
  529. client, unless argument ABORT is non-nil, in which case then the
  530. original text is sent back.
  531. If optional second argument NOKILL is non-nil, then the editing
  532. buffer is not killed and the buffer name is passed to calling process.
  533. When called interactively, use prefix arg to abort editing."
  534. (interactive "P")
  535. ;; Do nothing if the connection is closed by the browser (tab killed, etc.)
  536. (unless (eq (process-status edit-server-proc) 'closed)
  537. (let ((buffer (current-buffer))
  538. (proc edit-server-proc)
  539. (procbuf (process-buffer edit-server-proc)))
  540. ;; edit-server-* vars are buffer-local,
  541. ;; so they must be used before issuing kill-buffer
  542. (if abort
  543. ;; send back original content
  544. (with-current-buffer procbuf
  545. (run-hooks 'edit-server-done-hook)
  546. (edit-server-send-response proc t))
  547. ;; send back edited content
  548. (save-restriction
  549. (widen)
  550. (buffer-disable-undo)
  551. ;; ensure any format encoding is done (like longlines)
  552. (dolist (format buffer-file-format)
  553. (format-encode-region (point-min) (point-max) format))
  554. ;; send back
  555. (run-hooks 'edit-server-done-hook)
  556. (edit-server-send-response proc t nokill)
  557. (edit-server-log proc "sent response to browser")))
  558. (when edit-server-frame
  559. (delete-frame edit-server-frame))
  560. ;; delete-frame may change the current buffer
  561. (unless nokill
  562. ;; don't run abort twice in a row.
  563. (remove-hook 'kill-buffer-hook 'edit-server-abort*)
  564. (kill-buffer buffer))
  565. (edit-server-kill-client proc))))
  566. ;; edit-server-save uses the iterative edit-server option (send a
  567. ;; buffer back to the client which then returns new request to
  568. ;; continue the session). The edit-server then switches back to the
  569. ;; buffer referenced by the x-file header.
  570. ;;
  571. (defun edit-server-save ()
  572. "Save the current state of the edit buffer but don't close it."
  573. (interactive)
  574. (edit-server-done nil t))
  575. (defun edit-server-abort ()
  576. "Discard editing and send the original text back to the browser."
  577. (interactive)
  578. (edit-server-done t))
  579. (defun edit-server-abort* ()
  580. "Discard editing and send the original text back to the browser,
  581. but don't kill the editing buffer."
  582. (interactive)
  583. (edit-server-done t t))
  584. (provide 'edit-server)
  585. ;;; edit-server.el ends here