edit-server.el 27 KB

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