server.el 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  1. ;;; server.el --- Lisp code for GNU Emacs running as server process -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1986-1987, 1992, 1994-2017 Free Software Foundation,
  3. ;; Inc.
  4. ;; Author: William Sommerfeld <wesommer@athena.mit.edu>
  5. ;; Maintainer: emacs-devel@gnu.org
  6. ;; Keywords: processes
  7. ;; Changes by peck@sun.com and by rms.
  8. ;; Overhaul by Karoly Lorentey <lorentey@elte.hu> for multi-tty support.
  9. ;; This file is part of GNU Emacs.
  10. ;; GNU Emacs 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 of the License, or
  13. ;; (at your option) any later version.
  14. ;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  20. ;;; Commentary:
  21. ;; This Lisp code is run in Emacs when it is to operate as
  22. ;; a server for other processes.
  23. ;; Load this library and do M-x server-edit to enable Emacs as a server.
  24. ;; Emacs opens up a socket for communication with clients. If there are no
  25. ;; client buffers to edit, server-edit acts like (switch-to-buffer
  26. ;; (other-buffer))
  27. ;; When some other program runs "the editor" to edit a file,
  28. ;; "the editor" can be the Emacs client program ../lib-src/emacsclient.
  29. ;; This program transmits the file names to Emacs through
  30. ;; the server subprocess, and Emacs visits them and lets you edit them.
  31. ;; Note that any number of clients may dispatch files to Emacs to be edited.
  32. ;; When you finish editing a Server buffer, again call server-edit
  33. ;; to mark that buffer as done for the client and switch to the next
  34. ;; Server buffer. When all the buffers for a client have been edited
  35. ;; and exited with server-edit, the client "editor" will return
  36. ;; to the program that invoked it.
  37. ;; Your editing commands and Emacs's display output go to and from
  38. ;; the terminal in the usual way. Thus, server operation is possible
  39. ;; only when Emacs can talk to the terminal at the time you invoke
  40. ;; the client. This is possible in four cases:
  41. ;; 1. On a window system, where Emacs runs in one window and the
  42. ;; program that wants to use "the editor" runs in another.
  43. ;; 2. On a multi-terminal system, where Emacs runs on one terminal and the
  44. ;; program that wants to use "the editor" runs on another.
  45. ;; 3. When the program that wants to use "the editor" is running
  46. ;; as a subprocess of Emacs.
  47. ;; 4. On a system with job control, when Emacs is suspended, the program
  48. ;; that wants to use "the editor" will stop and display
  49. ;; "Waiting for Emacs...". It can then be suspended, and Emacs can be
  50. ;; brought into the foreground for editing. When done editing, Emacs is
  51. ;; suspended again, and the client program is brought into the foreground.
  52. ;; The buffer local variable "server-buffer-clients" lists
  53. ;; the clients who are waiting for this buffer to be edited.
  54. ;; The global variable "server-clients" lists all the waiting clients,
  55. ;; and which files are yet to be edited for each.
  56. ;; Todo:
  57. ;; - handle command-line-args-left.
  58. ;; - move most of the args processing and decision making from emacsclient.c
  59. ;; to here.
  60. ;; - fix up handling of the client's environment (place it in the terminal?).
  61. ;;; Code:
  62. (eval-when-compile (require 'cl-lib))
  63. (defgroup server nil
  64. "Emacs running as a server process."
  65. :group 'external)
  66. (defcustom server-use-tcp nil
  67. "If non-nil, use TCP sockets instead of local sockets."
  68. :set #'(lambda (sym val)
  69. (unless (featurep 'make-network-process '(:family local))
  70. (setq val t)
  71. (unless load-in-progress
  72. (message "Local sockets unsupported, using TCP sockets")))
  73. (set-default sym val))
  74. :group 'server
  75. :type 'boolean
  76. :version "22.1")
  77. (defcustom server-host nil
  78. "The name or IP address to use as host address of the server process.
  79. If set, the server accepts remote connections; otherwise it is local.
  80. DO NOT give this a non-nil value unless you know what you are doing!
  81. On unsecured networks, accepting remote connections is very dangerous,
  82. because server-client communication (including session authentication)
  83. is not encrypted."
  84. :group 'server
  85. :type '(choice
  86. (string :tag "Name or IP address")
  87. (const :tag "Local" nil))
  88. :version "22.1")
  89. ;;;###autoload
  90. (put 'server-host 'risky-local-variable t)
  91. (defcustom server-port nil
  92. "The port number that the server process should listen on.
  93. This variable only takes effect when the Emacs server is using
  94. TCP instead of local sockets. A nil value means to use a random
  95. port number."
  96. :group 'server
  97. :type '(choice
  98. (string :tag "Port number")
  99. (const :tag "Random" nil))
  100. :version "24.1")
  101. ;;;###autoload
  102. (put 'server-port 'risky-local-variable t)
  103. (defcustom server-auth-dir (locate-user-emacs-file "server/")
  104. "Directory for server authentication files.
  105. We only use this if `server-use-tcp' is non-nil.
  106. Otherwise we use `server-socket-dir'.
  107. NOTE: On FAT32 filesystems, directories are not secure;
  108. files can be read and modified by any user or process.
  109. It is strongly suggested to set `server-auth-dir' to a
  110. directory residing in a NTFS partition instead."
  111. :group 'server
  112. :type 'directory
  113. :version "22.1")
  114. ;;;###autoload
  115. (put 'server-auth-dir 'risky-local-variable t)
  116. (defcustom server-auth-key nil
  117. "Server authentication key.
  118. This is only used if `server-use-tcp' is non-nil.
  119. Normally, the authentication key is randomly generated when the
  120. server starts. It is recommended to leave it that way. Using a
  121. long-lived shared key will decrease security (especially since
  122. the key is transmitted as plain-text).
  123. In some situations however, it can be difficult to share randomly
  124. generated passwords with remote hosts (e.g., no shared directory),
  125. so you can set the key with this variable and then copy the
  126. server file to the remote host (with possible changes to IP
  127. address and/or port if that applies).
  128. Note that the usual security risks of using the server over
  129. remote TCP, arising from the fact that client-server
  130. communications are unencrypted, still apply.
  131. The key must consist of 64 ASCII printable characters except for
  132. space (this means characters from ! to ~; or from code 33 to
  133. 126). You can use \\[server-generate-key] to get a random key."
  134. :group 'server
  135. :type '(choice
  136. (const :tag "Random" nil)
  137. (string :tag "Password"))
  138. :version "24.3")
  139. (defcustom server-raise-frame t
  140. "If non-nil, raise frame when switching to a buffer."
  141. :group 'server
  142. :type 'boolean
  143. :version "22.1")
  144. (defcustom server-visit-hook nil
  145. "Hook run when visiting a file for the Emacs server."
  146. :group 'server
  147. :type 'hook)
  148. (defcustom server-switch-hook nil
  149. "Hook run when switching to a buffer for the Emacs server."
  150. :group 'server
  151. :type 'hook)
  152. (defcustom server-done-hook nil
  153. "Hook run when done editing a buffer for the Emacs server."
  154. :group 'server
  155. :type 'hook)
  156. (defvar server-process nil
  157. "The current server process.")
  158. (defvar server-clients nil
  159. "List of current server clients.
  160. Each element is a process.")
  161. (defvar server-buffer-clients nil
  162. "List of client processes requesting editing of current buffer.")
  163. (make-variable-buffer-local 'server-buffer-clients)
  164. ;; Changing major modes should not erase this local.
  165. (put 'server-buffer-clients 'permanent-local t)
  166. (defcustom server-window nil
  167. "Specification of the window to use for selecting Emacs server buffers.
  168. If nil, use the selected window.
  169. If it is a function, it should take one argument (a buffer) and
  170. display and select it. A common value is `pop-to-buffer'.
  171. If it is a window, use that.
  172. If it is a frame, use the frame's selected window.
  173. It is not meaningful to set this to a specific frame or window with Custom.
  174. Only programs can do so."
  175. :group 'server
  176. :version "22.1"
  177. :type '(choice (const :tag "Use selected window"
  178. :match (lambda (widget value)
  179. (not (functionp value)))
  180. nil)
  181. (function-item :tag "Display in new frame" switch-to-buffer-other-frame)
  182. (function-item :tag "Use pop-to-buffer" pop-to-buffer)
  183. (function :tag "Other function")))
  184. (defcustom server-temp-file-regexp "^/tmp/Re\\|/draft$"
  185. "Regexp matching names of temporary files.
  186. These are deleted and reused after each edit by the programs that
  187. invoke the Emacs server."
  188. :group 'server
  189. :type 'regexp)
  190. (defcustom server-kill-new-buffers t
  191. "Whether to kill buffers when done with them.
  192. If non-nil, kill a buffer unless it already existed before editing
  193. it with the Emacs server. If nil, kill only buffers as specified by
  194. `server-temp-file-regexp'.
  195. Please note that only buffers that still have a client are killed,
  196. i.e. buffers visited with \"emacsclient --no-wait\" are never killed
  197. in this way."
  198. :group 'server
  199. :type 'boolean
  200. :version "21.1")
  201. (defvar server-existing-buffer nil
  202. "Non-nil means the buffer existed before the server was asked to visit it.
  203. This means that the server should not kill the buffer when you say you
  204. are done with it in the server.")
  205. (make-variable-buffer-local 'server-existing-buffer)
  206. ;;;###autoload
  207. (defcustom server-name "server"
  208. "The name of the Emacs server, if this Emacs process creates one.
  209. The command `server-start' makes use of this. It should not be
  210. changed while a server is running."
  211. :group 'server
  212. :type 'string
  213. :version "23.1")
  214. ;; We do not use `temporary-file-directory' here, because emacsclient
  215. ;; does not read the init file.
  216. (defvar server-socket-dir
  217. (and (featurep 'make-network-process '(:family local))
  218. (format "%s/emacs%d" (or (getenv "TMPDIR") "/tmp") (user-uid)))
  219. "The directory in which to place the server socket.
  220. If local sockets are not supported, this is nil.")
  221. (defun server-clients-with (property value)
  222. "Return a list of clients with PROPERTY set to VALUE."
  223. (let (result)
  224. (dolist (proc server-clients)
  225. (when (equal value (process-get proc property))
  226. (push proc result)))
  227. result))
  228. (defun server-add-client (proc)
  229. "Create a client for process PROC, if it doesn't already have one.
  230. New clients have no properties."
  231. (add-to-list 'server-clients proc))
  232. (defmacro server-with-environment (env vars &rest body)
  233. "Evaluate BODY with environment variables VARS set to those in ENV.
  234. The environment variables are then restored to their previous values.
  235. VARS should be a list of strings.
  236. ENV should be in the same format as `process-environment'."
  237. (declare (indent 2))
  238. (let ((var (make-symbol "var"))
  239. (value (make-symbol "value")))
  240. `(let ((process-environment process-environment))
  241. (dolist (,var ,vars)
  242. (let ((,value (getenv-internal ,var ,env)))
  243. (push (if (stringp ,value)
  244. (concat ,var "=" ,value)
  245. ,var)
  246. process-environment)))
  247. (progn ,@body))))
  248. (defun server-delete-client (proc &optional noframe)
  249. "Delete PROC, including its buffers, terminals and frames.
  250. If NOFRAME is non-nil, let the frames live.
  251. Updates `server-clients'."
  252. (server-log (concat "server-delete-client" (if noframe " noframe")) proc)
  253. ;; Force a new lookup of client (prevents infinite recursion).
  254. (when (memq proc server-clients)
  255. (let ((buffers (process-get proc 'buffers)))
  256. ;; Kill the client's buffers.
  257. (dolist (buf buffers)
  258. (when (buffer-live-p buf)
  259. (with-current-buffer buf
  260. ;; Kill the buffer if necessary.
  261. (when (and (equal server-buffer-clients
  262. (list proc))
  263. (or (and server-kill-new-buffers
  264. (not server-existing-buffer))
  265. (server-temp-file-p))
  266. (not (buffer-modified-p)))
  267. (let (flag)
  268. (unwind-protect
  269. (progn (setq server-buffer-clients nil)
  270. (kill-buffer (current-buffer))
  271. (setq flag t))
  272. (unless flag
  273. ;; Restore clients if user pressed C-g in `kill-buffer'.
  274. (setq server-buffer-clients (list proc)))))))))
  275. ;; Delete the client's frames.
  276. (unless noframe
  277. (dolist (frame (frame-list))
  278. (when (and (frame-live-p frame)
  279. (equal proc (frame-parameter frame 'client)))
  280. ;; Prevent `server-handle-delete-frame' from calling us
  281. ;; recursively.
  282. (set-frame-parameter frame 'client nil)
  283. (delete-frame frame))))
  284. (setq server-clients (delq proc server-clients))
  285. ;; Delete the client's tty, except on Windows (both GUI and console),
  286. ;; where there's only one terminal and does not make sense to delete it.
  287. (unless (eq system-type 'windows-nt)
  288. (let ((terminal (process-get proc 'terminal)))
  289. ;; Only delete the terminal if it is non-nil.
  290. (when (and terminal (eq (terminal-live-p terminal) t))
  291. (delete-terminal terminal))))
  292. ;; Delete the client's process.
  293. (if (eq (process-status proc) 'open)
  294. (delete-process proc))
  295. (server-log "Deleted" proc))))
  296. (defvar server-log-time-function 'current-time-string
  297. "Function to generate timestamps for `server-buffer'.")
  298. (defconst server-buffer " *server*"
  299. "Buffer used internally by Emacs's server.
  300. One use is to log the I/O for debugging purposes (see option `server-log'),
  301. the other is to provide a current buffer in which the process filter can
  302. safely let-bind buffer-local variables like `default-directory'.")
  303. (defvar server-log nil
  304. "If non-nil, log the server's inputs and outputs in the `server-buffer'.")
  305. (defun server-log (string &optional client)
  306. "If option `server-log' is non-nil, log STRING to `server-buffer'.
  307. If CLIENT is non-nil, add a description of it to the logged message."
  308. (when server-log
  309. (with-current-buffer (get-buffer-create server-buffer)
  310. (goto-char (point-max))
  311. (insert (funcall server-log-time-function)
  312. (cond
  313. ((null client) " ")
  314. ((listp client) (format " %s: " (car client)))
  315. (t (format " %s: " client)))
  316. string)
  317. (or (bolp) (newline)))))
  318. (defun server-sentinel (proc msg)
  319. "The process sentinel for Emacs server connections."
  320. ;; If this is a new client process, set the query-on-exit flag to nil
  321. ;; for this process (it isn't inherited from the server process).
  322. (when (and (eq (process-status proc) 'open)
  323. (process-query-on-exit-flag proc))
  324. (set-process-query-on-exit-flag proc nil))
  325. ;; Delete the associated connection file, if applicable.
  326. ;; Although there's no 100% guarantee that the file is owned by the
  327. ;; running Emacs instance, server-start uses server-running-p to check
  328. ;; for possible servers before doing anything, so it *should* be ours.
  329. (and (process-contact proc :server)
  330. (eq (process-status proc) 'closed)
  331. (ignore-errors
  332. (delete-file (process-get proc :server-file))))
  333. (server-log (format "Status changed to %s: %s" (process-status proc) msg) proc)
  334. (server-delete-client proc))
  335. (defun server--on-display-p (frame display)
  336. (and (equal (frame-parameter frame 'display) display)
  337. ;; Note: TTY frames still get a `display' parameter set to the value of
  338. ;; $DISPLAY. This is useful when running from that tty frame
  339. ;; sub-processes that want to connect to the X server, but that means we
  340. ;; have to be careful here not to be tricked into thinking those frames
  341. ;; are on `display'.
  342. (not (eq (framep frame) t))))
  343. (defun server-select-display (display)
  344. ;; If the current frame is on `display' we're all set.
  345. ;; Similarly if we are unable to open frames on other displays, there's
  346. ;; nothing more we can do.
  347. (unless (or (not (fboundp 'make-frame-on-display))
  348. (server--on-display-p (selected-frame) display))
  349. ;; Otherwise, look for an existing frame there and select it.
  350. (dolist (frame (frame-list))
  351. (when (server--on-display-p frame display)
  352. (select-frame frame)))
  353. ;; If there's no frame on that display yet, create and select one.
  354. (unless (server--on-display-p (selected-frame) display)
  355. (let* ((buffer (generate-new-buffer " *server-dummy*"))
  356. (frame (make-frame-on-display
  357. display
  358. ;; Make it display (and remember) some dummy buffer, so
  359. ;; we can detect later if the frame is in use or not.
  360. `((server-dummy-buffer . ,buffer)
  361. ;; This frame may be deleted later (see
  362. ;; server-unselect-display) so we want it to be as
  363. ;; unobtrusive as possible.
  364. (visibility . nil)))))
  365. (select-frame frame)
  366. (set-window-buffer (selected-window) buffer)
  367. frame))))
  368. (defun server-unselect-display (frame)
  369. (when (frame-live-p frame)
  370. ;; If the temporary frame is in use (displays something real), make it
  371. ;; visible. If not (which can happen if the user's customizations call
  372. ;; pop-to-buffer etc.), delete it to avoid preserving the connection after
  373. ;; the last real frame is deleted.
  374. ;; Rewritten to avoid inadvertently killing the current buffer after
  375. ;; `delete-frame' removed FRAME (Bug#10729).
  376. (let ((buffer (frame-parameter frame 'server-dummy-buffer)))
  377. (if (and (one-window-p 'nomini frame)
  378. (eq (window-buffer (frame-first-window frame)) buffer))
  379. ;; The temp frame still only shows one buffer, and that is the
  380. ;; internal temp buffer.
  381. (delete-frame frame)
  382. (set-frame-parameter frame 'visibility t)
  383. (set-frame-parameter frame 'server-dummy-buffer nil))
  384. (when (buffer-live-p buffer)
  385. (kill-buffer buffer)))))
  386. (defun server-handle-delete-frame (frame)
  387. "Delete the client connection when the emacsclient frame is deleted.
  388. \(To be used from `delete-frame-functions'.)"
  389. (let ((proc (frame-parameter frame 'client)))
  390. (when (and (frame-live-p frame)
  391. proc
  392. ;; See if this is the last frame for this client.
  393. (>= 1 (let ((frame-num 0))
  394. (dolist (f (frame-list))
  395. (when (eq proc (frame-parameter f 'client))
  396. (setq frame-num (1+ frame-num))))
  397. frame-num)))
  398. (server-log (format "server-handle-delete-frame, frame %s" frame) proc)
  399. (server-delete-client proc 'noframe)))) ; Let delete-frame delete the frame later.
  400. (defun server-handle-suspend-tty (terminal)
  401. "Notify the client process that its tty device is suspended."
  402. (dolist (proc (server-clients-with 'terminal terminal))
  403. (server-log (format "server-handle-suspend-tty, terminal %s" terminal)
  404. proc)
  405. (condition-case nil
  406. (server-send-string proc "-suspend \n")
  407. (file-error ;The pipe/socket was closed.
  408. (ignore-errors (server-delete-client proc))))))
  409. (defun server-unquote-arg (arg)
  410. "Remove &-quotation from ARG.
  411. See `server-quote-arg' and `server-process-filter'."
  412. (replace-regexp-in-string
  413. "&." (lambda (s)
  414. (pcase (aref s 1)
  415. (?& "&")
  416. (?- "-")
  417. (?n "\n")
  418. (_ " ")))
  419. arg t t))
  420. (defun server-quote-arg (arg)
  421. "In ARG, insert a & before each &, each space, each newline, and -.
  422. Change spaces to underscores, too, so that the return value never
  423. contains a space.
  424. See `server-unquote-arg' and `server-process-filter'."
  425. (replace-regexp-in-string
  426. "[-&\n ]" (lambda (s)
  427. (pcase (aref s 0)
  428. (?& "&&")
  429. (?- "&-")
  430. (?\n "&n")
  431. (?\s "&_")))
  432. arg t t))
  433. (defun server-send-string (proc string)
  434. "A wrapper around `process-send-string' for logging."
  435. (server-log (concat "Sent " string) proc)
  436. (process-send-string proc string))
  437. (defun server-ensure-safe-dir (dir)
  438. "Make sure DIR is a directory with no race-condition issues.
  439. Creates the directory if necessary and makes sure:
  440. - there's no symlink involved
  441. - it's owned by us
  442. - it's not readable/writable by anybody else."
  443. (setq dir (directory-file-name dir))
  444. (let ((attrs (file-attributes dir 'integer)))
  445. (unless attrs
  446. (cl-letf (((default-file-modes) ?\700)) (make-directory dir t))
  447. (setq attrs (file-attributes dir 'integer)))
  448. ;; Check that it's safe for use.
  449. (let* ((uid (nth 2 attrs))
  450. (w32 (eq system-type 'windows-nt))
  451. (safe (cond
  452. ((not (eq t (car attrs))) nil) ; is a dir?
  453. ((and w32 (zerop uid)) ; on FAT32?
  454. (display-warning
  455. 'server
  456. (format-message "\
  457. Using `%s' to store Emacs-server authentication files.
  458. Directories on FAT32 filesystems are NOT secure against tampering.
  459. See variable `server-auth-dir' for details."
  460. (file-name-as-directory dir))
  461. :warning)
  462. t)
  463. ((and (/= uid (user-uid)) ; is the dir ours?
  464. (or (not w32)
  465. ;; Files created on Windows by Administrator
  466. ;; (RID=500) have the Administrators (RID=544)
  467. ;; group recorded as the owner.
  468. (/= uid 544) (/= (user-uid) 500)))
  469. nil)
  470. (w32 t) ; on NTFS?
  471. (t ; else, check permissions
  472. (zerop (logand ?\077 (file-modes dir)))))))
  473. (unless safe
  474. (error "The directory `%s' is unsafe" dir)))))
  475. (defun server-generate-key ()
  476. "Generate and return a random authentication key.
  477. The key is a 64-byte string of random chars in the range `!'..`~'.
  478. If called interactively, also inserts it into current buffer."
  479. (interactive)
  480. (let ((auth-key
  481. (cl-loop repeat 64
  482. collect (+ 33 (random 94)) into auth
  483. finally return (concat auth))))
  484. (if (called-interactively-p 'interactive)
  485. (insert auth-key))
  486. auth-key))
  487. (defun server-get-auth-key ()
  488. "Return server's authentication key.
  489. If `server-auth-key' is nil, just call `server-generate-key'.
  490. Otherwise, if `server-auth-key' is a valid key, return it.
  491. If the key is not valid, signal an error."
  492. (if server-auth-key
  493. (if (string-match-p "^[!-~]\\{64\\}$" server-auth-key)
  494. server-auth-key
  495. (error "The key `%s' is invalid" server-auth-key))
  496. (server-generate-key)))
  497. ;;;###autoload
  498. (defun server-start (&optional leave-dead inhibit-prompt)
  499. "Allow this Emacs process to be a server for client processes.
  500. This starts a server communications subprocess through which client
  501. \"editors\" can send your editing commands to this Emacs job.
  502. To use the server, set up the program `emacsclient' in the Emacs
  503. distribution as your standard \"editor\".
  504. Optional argument LEAVE-DEAD (interactively, a prefix arg) means just
  505. kill any existing server communications subprocess.
  506. If a server is already running, restart it. If clients are
  507. running, ask the user for confirmation first, unless optional
  508. argument INHIBIT-PROMPT is non-nil.
  509. To force-start a server, do \\[server-force-delete] and then
  510. \\[server-start]."
  511. (interactive "P")
  512. (when (or (not server-clients)
  513. ;; Ask the user before deleting existing clients---except
  514. ;; when we can't get user input, which may happen when
  515. ;; doing emacsclient --eval "(kill-emacs)" in daemon mode.
  516. (cond
  517. ((and (daemonp)
  518. (null (cdr (frame-list)))
  519. (eq (selected-frame) terminal-frame))
  520. leave-dead)
  521. (inhibit-prompt t)
  522. (t (yes-or-no-p
  523. "The current server still has clients; delete them? "))))
  524. (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
  525. (server-file (expand-file-name server-name server-dir)))
  526. (when server-process
  527. ;; kill it dead!
  528. (ignore-errors (delete-process server-process)))
  529. ;; Delete the socket files made by previous server invocations.
  530. (if (not (eq t (server-running-p server-name)))
  531. ;; Remove any leftover socket or authentication file
  532. (ignore-errors
  533. (let (delete-by-moving-to-trash)
  534. (delete-file server-file)))
  535. (setq server-mode nil) ;; already set by the minor mode code
  536. (display-warning
  537. 'server
  538. (concat "Unable to start the Emacs server.\n"
  539. (format "There is an existing Emacs server, named %S.\n"
  540. server-name)
  541. (substitute-command-keys
  542. "To start the server in this Emacs process, stop the existing
  543. server or call `\\[server-force-delete]' to forcibly disconnect it."))
  544. :warning)
  545. (setq leave-dead t))
  546. ;; If this Emacs already had a server, clear out associated status.
  547. (while server-clients
  548. (server-delete-client (car server-clients)))
  549. ;; Now any previous server is properly stopped.
  550. (if leave-dead
  551. (progn
  552. (unless (eq t leave-dead) (server-log (message "Server stopped")))
  553. (setq server-process nil))
  554. ;; Make sure there is a safe directory in which to place the socket.
  555. (server-ensure-safe-dir server-dir)
  556. (when server-process
  557. (server-log (message "Restarting server")))
  558. (cl-letf (((default-file-modes) ?\700))
  559. (add-hook 'suspend-tty-functions 'server-handle-suspend-tty)
  560. (add-hook 'delete-frame-functions 'server-handle-delete-frame)
  561. (add-hook 'kill-emacs-query-functions
  562. 'server-kill-emacs-query-function)
  563. ;; We put server's kill-emacs-hook after the others, so that
  564. ;; frames are not deleted too early, because doing that
  565. ;; would severely degrade our abilities to communicate with
  566. ;; the user, while some hooks may wish to ask the user
  567. ;; questions (e.g., desktop-kill).
  568. (add-hook 'kill-emacs-hook 'server-force-stop t) ;Cleanup upon exit.
  569. (setq server-process
  570. (apply #'make-network-process
  571. :name server-name
  572. :server t
  573. :noquery t
  574. :sentinel #'server-sentinel
  575. :filter #'server-process-filter
  576. :use-external-socket t
  577. ;; We must receive file names without being decoded.
  578. ;; Those are decoded by server-process-filter according
  579. ;; to file-name-coding-system. Also don't get
  580. ;; confused by CRs since we don't quote them.
  581. :coding 'raw-text-unix
  582. ;; The other args depend on the kind of socket used.
  583. (if server-use-tcp
  584. (list :family 'ipv4 ;; We're not ready for IPv6 yet
  585. :service (or server-port t)
  586. :host (or server-host 'local)
  587. :plist '(:authenticated nil))
  588. (list :family 'local
  589. :service server-file
  590. :plist '(:authenticated t)))))
  591. (unless server-process (error "Could not start server process"))
  592. (process-put server-process :server-file server-file)
  593. (when server-use-tcp
  594. (let ((auth-key (server-get-auth-key)))
  595. (process-put server-process :auth-key auth-key)
  596. (with-temp-file server-file
  597. (set-buffer-multibyte nil)
  598. (setq buffer-file-coding-system 'no-conversion)
  599. (insert (format-network-address
  600. (process-contact server-process :local))
  601. " " (number-to-string (emacs-pid)) ; Kept for compatibility
  602. "\n" auth-key)))))))))
  603. (defun server-force-stop ()
  604. "Kill all connections to the current server.
  605. This function is meant to be called from `kill-emacs-hook'."
  606. (server-start t t))
  607. ;;;###autoload
  608. (defun server-force-delete (&optional name)
  609. "Unconditionally delete connection file for server NAME.
  610. If server is running, it is first stopped.
  611. NAME defaults to `server-name'. With argument, ask for NAME."
  612. (interactive
  613. (list (if current-prefix-arg
  614. (read-string "Server name: " nil nil server-name))))
  615. (when server-mode (with-temp-message nil (server-mode -1)))
  616. (let ((file (expand-file-name (or name server-name)
  617. (if server-use-tcp
  618. server-auth-dir
  619. server-socket-dir))))
  620. (condition-case nil
  621. (let (delete-by-moving-to-trash)
  622. (delete-file file)
  623. (message "Connection file %S deleted" file))
  624. (file-error
  625. (message "No connection file %S" file)))))
  626. (defun server-running-p (&optional name)
  627. "Test whether server NAME is running.
  628. Return values:
  629. nil the server is definitely not running.
  630. t the server seems to be running.
  631. something else we cannot determine whether it's running without using
  632. commands which may have to wait for a long time."
  633. (unless name (setq name server-name))
  634. (condition-case nil
  635. (if server-use-tcp
  636. (with-temp-buffer
  637. (insert-file-contents-literally (expand-file-name name server-auth-dir))
  638. (or (and (looking-at "127\\.0\\.0\\.1:[0-9]+ \\([0-9]+\\)")
  639. (assq 'comm
  640. (process-attributes
  641. (string-to-number (match-string 1))))
  642. t)
  643. :other))
  644. (delete-process
  645. (make-network-process
  646. :name "server-client-test" :family 'local :server nil :noquery t
  647. :service (expand-file-name name server-socket-dir)))
  648. t)
  649. (file-error nil)))
  650. ;;;###autoload
  651. (define-minor-mode server-mode
  652. "Toggle Server mode.
  653. With a prefix argument ARG, enable Server mode if ARG is
  654. positive, and disable it otherwise. If called from Lisp, enable
  655. Server mode if ARG is omitted or nil.
  656. Server mode runs a process that accepts commands from the
  657. `emacsclient' program. See Info node `Emacs server' and
  658. `server-start' for details."
  659. :global t
  660. :group 'server
  661. :version "22.1"
  662. ;; Fixme: Should this check for an existing server socket and do
  663. ;; nothing if there is one (for multiple Emacs sessions)?
  664. (server-start (not server-mode)))
  665. (defun server-eval-and-print (expr proc)
  666. "Eval EXPR and send the result back to client PROC."
  667. ;; While we're running asynchronously (from a process filter), it is likely
  668. ;; that the emacsclient command was run in response to a user
  669. ;; action, so the user probably knows that Emacs is processing this
  670. ;; emacsclient request, so if we get a C-g it's likely that the user
  671. ;; intended it to interrupt us rather than interrupt whatever Emacs
  672. ;; was doing before it started handling the process filter.
  673. ;; Hence `with-local-quit' (bug#6585).
  674. (let ((v (with-local-quit (eval (car (read-from-string expr))))))
  675. (when proc
  676. (with-temp-buffer
  677. (let ((standard-output (current-buffer)))
  678. (pp v)
  679. (let ((text (buffer-substring-no-properties
  680. (point-min) (point-max))))
  681. (server-reply-print (server-quote-arg text) proc)))))))
  682. (defconst server-msg-size 1024
  683. "Maximum size of a message sent to a client.")
  684. (defun server-reply-print (qtext proc)
  685. "Send a `-print QTEXT' command to client PROC.
  686. QTEXT must be already quoted.
  687. This handles splitting the command if it would be bigger than
  688. `server-msg-size'."
  689. (let ((prefix "-print ")
  690. part)
  691. (while (> (+ (length qtext) (length prefix) 1) server-msg-size)
  692. ;; We have to split the string
  693. (setq part (substring qtext 0 (- server-msg-size (length prefix) 1)))
  694. ;; Don't split in the middle of a quote sequence
  695. (if (string-match "\\(^\\|[^&]\\)&\\(&&\\)*$" part)
  696. ;; There is an uneven number of & at the end
  697. (setq part (substring part 0 -1)))
  698. (setq qtext (substring qtext (length part)))
  699. (server-send-string proc (concat prefix part "\n"))
  700. (setq prefix "-print-nonl "))
  701. (server-send-string proc (concat prefix qtext "\n"))))
  702. (defun server-create-tty-frame (tty type proc)
  703. (unless tty
  704. (error "Invalid terminal device"))
  705. (unless type
  706. (error "Invalid terminal type"))
  707. (add-to-list 'frame-inherited-parameters 'client)
  708. (let ((frame
  709. (server-with-environment
  710. (process-get proc 'env)
  711. '("LANG" "LC_CTYPE" "LC_ALL"
  712. ;; For tgetent(3); list according to ncurses(3).
  713. "BAUDRATE" "COLUMNS" "ESCDELAY" "HOME" "LINES"
  714. "NCURSES_ASSUMED_COLORS" "NCURSES_NO_PADDING"
  715. "NCURSES_NO_SETBUF" "TERM" "TERMCAP" "TERMINFO"
  716. "TERMINFO_DIRS" "TERMPATH"
  717. ;; rxvt wants these
  718. "COLORFGBG" "COLORTERM")
  719. (make-frame `((window-system . nil)
  720. (tty . ,tty)
  721. (tty-type . ,type)
  722. ;; Ignore nowait here; we always need to
  723. ;; clean up opened ttys when the client dies.
  724. (client . ,proc)
  725. ;; This is a leftover from an earlier
  726. ;; attempt at making it possible for process
  727. ;; run in the server process to use the
  728. ;; environment of the client process.
  729. ;; It has no effect now and to make it work
  730. ;; we'd need to decide how to make
  731. ;; process-environment interact with client
  732. ;; envvars, and then to change the
  733. ;; C functions `child_setup' and
  734. ;; `getenv_internal' accordingly.
  735. (environment . ,(process-get proc 'env)))))))
  736. ;; ttys don't use the `display' parameter, but callproc.c does to set
  737. ;; the DISPLAY environment on subprocesses.
  738. (set-frame-parameter frame 'display
  739. (getenv-internal "DISPLAY" (process-get proc 'env)))
  740. (select-frame frame)
  741. (process-put proc 'frame frame)
  742. (process-put proc 'terminal (frame-terminal frame))
  743. frame))
  744. (defun server-create-window-system-frame (display nowait proc parent-id
  745. &optional parameters)
  746. (let* ((display (or display
  747. (frame-parameter nil 'display)
  748. (error "Please specify display.")))
  749. (w (or (cdr (assq 'window-system parameters))
  750. (window-system-for-display display))))
  751. ;; Special case for ns. This is because DISPLAY may not be set at all
  752. ;; which in the ns case isn't an error. The variable display then becomes
  753. ;; the fully qualified hostname, which make-frame-on-display below
  754. ;; does not understand and throws an error.
  755. ;; It may also be a valid X display, but if Emacs is compiled for ns, it
  756. ;; can not make X frames.
  757. (if (featurep 'ns-win)
  758. (setq w 'ns display "ns")
  759. ;; FIXME! Not sure what this was for, and not sure how it should work
  760. ;; in the cl-defmethod new world!
  761. ;;(unless (assq w window-system-initialization-alist)
  762. ;; (setq w nil))
  763. )
  764. (cond (w
  765. ;; Flag frame as client-created, but use a dummy client.
  766. ;; This will prevent the frame from being deleted when
  767. ;; emacsclient quits while also preventing
  768. ;; `server-save-buffers-kill-terminal' from unexpectedly
  769. ;; killing emacs on that frame.
  770. (let* ((params `((client . ,(if nowait 'nowait proc))
  771. ;; This is a leftover, see above.
  772. (environment . ,(process-get proc 'env))
  773. ,@parameters))
  774. frame)
  775. (if parent-id
  776. (push (cons 'parent-id (string-to-number parent-id)) params))
  777. (add-to-list 'frame-inherited-parameters 'client)
  778. (setq frame (make-frame-on-display display params))
  779. (server-log (format "%s created" frame) proc)
  780. (select-frame frame)
  781. (process-put proc 'frame frame)
  782. (process-put proc 'terminal (frame-terminal frame))
  783. frame))
  784. (t
  785. (server-log "Window system unsupported" proc)
  786. (server-send-string proc "-window-system-unsupported \n")
  787. nil))))
  788. (defun server-goto-toplevel (proc)
  789. (condition-case nil
  790. ;; If we're running isearch, we must abort it to allow Emacs to
  791. ;; display the buffer and switch to it.
  792. (dolist (buffer (buffer-list))
  793. (with-current-buffer buffer
  794. (when (bound-and-true-p isearch-mode)
  795. (isearch-cancel))))
  796. ;; Signaled by isearch-cancel.
  797. (quit (message nil)))
  798. (when (> (recursion-depth) 0)
  799. ;; We're inside a minibuffer already, so if the emacs-client is trying
  800. ;; to open a frame on a new display, we might end up with an unusable
  801. ;; frame because input from that display will be blocked (until exiting
  802. ;; the minibuffer). Better exit this minibuffer right away.
  803. ;; Similarly with recursive-edits such as the splash screen.
  804. (run-with-timer 0 nil (lambda () (server-execute-continuation proc)))
  805. (top-level)))
  806. ;; We use various special properties on process objects:
  807. ;; - `env' stores the info about the environment of the emacsclient process.
  808. ;; - `continuation' is a no-arg function that we need to execute. It contains
  809. ;; commands we wanted to execute in some earlier invocation of the process
  810. ;; filter but that we somehow were unable to process at that time
  811. ;; (e.g. because we first need to throw to the toplevel).
  812. (defun server-execute-continuation (proc)
  813. (let ((continuation (process-get proc 'continuation)))
  814. (process-put proc 'continuation nil)
  815. (if continuation (ignore-errors (funcall continuation)))))
  816. (cl-defun server-process-filter (proc string)
  817. "Process a request from the server to edit some files.
  818. PROC is the server process. STRING consists of a sequence of
  819. commands prefixed by a dash. Some commands have arguments;
  820. these are &-quoted and need to be decoded by `server-unquote-arg'.
  821. The filter parses and executes these commands.
  822. To illustrate the protocol, here is an example command that
  823. emacsclient sends to create a new X frame (note that the whole
  824. sequence is sent on a single line):
  825. -env HOME=/home/lorentey
  826. -env DISPLAY=:0.0
  827. ... lots of other -env commands
  828. -display :0.0
  829. -window-system
  830. The following commands are accepted by the server:
  831. `-auth AUTH-STRING'
  832. Authenticate the client using the secret authentication string
  833. AUTH-STRING.
  834. `-env NAME=VALUE'
  835. An environment variable on the client side.
  836. `-dir DIRNAME'
  837. The current working directory of the client process.
  838. `-current-frame'
  839. Forbid the creation of new frames.
  840. `-frame-parameters ALIST'
  841. Set the parameters of the created frame.
  842. `-nowait'
  843. Request that the next frame created should not be
  844. associated with this client.
  845. `-display DISPLAY'
  846. Set the display name to open X frames on.
  847. `-position LINE[:COLUMN]'
  848. Go to the given line and column number
  849. in the next file opened.
  850. `-file FILENAME'
  851. Load the given file in the current frame.
  852. `-eval EXPR'
  853. Evaluate EXPR as a Lisp expression and return the
  854. result in -print commands.
  855. `-window-system'
  856. Open a new X frame.
  857. `-tty DEVICENAME TYPE'
  858. Open a new tty frame at the client.
  859. `-suspend'
  860. Suspend this tty frame. The client sends this string in
  861. response to SIGTSTP and SIGTTOU. The server must cease all I/O
  862. on this tty until it gets a -resume command.
  863. `-resume'
  864. Resume this tty frame. The client sends this string when it
  865. gets the SIGCONT signal and it is the foreground process on its
  866. controlling tty.
  867. `-ignore COMMENT'
  868. Do nothing, but put the comment in the server log.
  869. Useful for debugging.
  870. The following commands are accepted by the client:
  871. `-emacs-pid PID'
  872. Describes the process id of the Emacs process;
  873. used to forward window change signals to it.
  874. `-window-system-unsupported'
  875. Signals that the server does not support creating X frames;
  876. the client must try again with a tty frame.
  877. `-print STRING'
  878. Print STRING on stdout. Used to send values
  879. returned by -eval.
  880. `-print-nonl STRING'
  881. Print STRING on stdout. Used to continue a
  882. preceding -print command that would be too big to send
  883. in a single message.
  884. `-error DESCRIPTION'
  885. Signal an error and delete process PROC.
  886. `-suspend'
  887. Suspend this terminal, i.e., stop the client process.
  888. Sent when the user presses C-z."
  889. (server-log (concat "Received " string) proc)
  890. ;; First things first: let's check the authentication
  891. (unless (process-get proc :authenticated)
  892. (if (and (string-match "-auth \\([!-~]+\\)\n?" string)
  893. (equal (match-string 1 string) (process-get proc :auth-key)))
  894. (progn
  895. (setq string (substring string (match-end 0)))
  896. (process-put proc :authenticated t)
  897. (server-log "Authentication successful" proc))
  898. (server-log "Authentication failed" proc)
  899. (server-send-string
  900. proc (concat "-error " (server-quote-arg "Authentication failed")))
  901. ;; Before calling `delete-process', give emacsclient time to
  902. ;; receive the error string and shut down on its own.
  903. (sit-for 1)
  904. (delete-process proc)
  905. ;; We return immediately.
  906. (cl-return-from server-process-filter)))
  907. (let ((prev (process-get proc 'previous-string)))
  908. (when prev
  909. (setq string (concat prev string))
  910. (process-put proc 'previous-string nil)))
  911. (condition-case err
  912. (progn
  913. (server-add-client proc)
  914. ;; Send our pid
  915. (server-send-string proc (concat "-emacs-pid "
  916. (number-to-string (emacs-pid)) "\n"))
  917. (if (not (string-match "\n" string))
  918. ;; Save for later any partial line that remains.
  919. (when (> (length string) 0)
  920. (process-put proc 'previous-string string))
  921. ;; In earlier versions of server.el (where we used an `emacsserver'
  922. ;; process), there could be multiple lines. Nowadays this is not
  923. ;; supported any more.
  924. (cl-assert (eq (match-end 0) (length string)))
  925. (let ((request (substring string 0 (match-beginning 0)))
  926. (coding-system (and (default-value 'enable-multibyte-characters)
  927. (or file-name-coding-system
  928. default-file-name-coding-system)))
  929. nowait ; t if emacsclient does not want to wait for us.
  930. frame ; Frame opened for the client (if any).
  931. display ; Open frame on this display.
  932. parent-id ; Window ID for XEmbed
  933. dontkill ; t if client should not be killed.
  934. commands
  935. dir
  936. use-current-frame
  937. frame-parameters ;parameters for newly created frame
  938. tty-name ; nil, `window-system', or the tty name.
  939. tty-type ; string.
  940. files
  941. filepos
  942. args-left)
  943. ;; Remove this line from STRING.
  944. (setq string (substring string (match-end 0)))
  945. (setq args-left
  946. (mapcar 'server-unquote-arg (split-string request " " t)))
  947. (while args-left
  948. (pcase (pop args-left)
  949. ;; -version CLIENT-VERSION: obsolete at birth.
  950. (`"-version" (pop args-left))
  951. ;; -nowait: Emacsclient won't wait for a result.
  952. (`"-nowait" (setq nowait t))
  953. ;; -current-frame: Don't create frames.
  954. (`"-current-frame" (setq use-current-frame t))
  955. ;; -frame-parameters: Set frame parameters
  956. (`"-frame-parameters"
  957. (let ((alist (pop args-left)))
  958. (if coding-system
  959. (setq alist (decode-coding-string alist coding-system)))
  960. (setq frame-parameters (car (read-from-string alist)))))
  961. ;; -display DISPLAY:
  962. ;; Open X frames on the given display instead of the default.
  963. (`"-display"
  964. (setq display (pop args-left))
  965. (if (zerop (length display)) (setq display nil)))
  966. ;; -parent-id ID:
  967. ;; Open X frame within window ID, via XEmbed.
  968. (`"-parent-id"
  969. (setq parent-id (pop args-left))
  970. (if (zerop (length parent-id)) (setq parent-id nil)))
  971. ;; -window-system: Open a new X frame.
  972. (`"-window-system"
  973. (if (fboundp 'x-create-frame)
  974. (setq dontkill t
  975. tty-name 'window-system)))
  976. ;; -resume: Resume a suspended tty frame.
  977. (`"-resume"
  978. (let ((terminal (process-get proc 'terminal)))
  979. (setq dontkill t)
  980. (push (lambda ()
  981. (when (eq (terminal-live-p terminal) t)
  982. (resume-tty terminal)))
  983. commands)))
  984. ;; -suspend: Suspend the client's frame. (In case we
  985. ;; get out of sync, and a C-z sends a SIGTSTP to
  986. ;; emacsclient.)
  987. (`"-suspend"
  988. (let ((terminal (process-get proc 'terminal)))
  989. (setq dontkill t)
  990. (push (lambda ()
  991. (when (eq (terminal-live-p terminal) t)
  992. (suspend-tty terminal)))
  993. commands)))
  994. ;; -ignore COMMENT: Noop; useful for debugging emacsclient.
  995. ;; (The given comment appears in the server log.)
  996. (`"-ignore"
  997. (setq dontkill t)
  998. (pop args-left))
  999. ;; -tty DEVICE-NAME TYPE: Open a new tty frame.
  1000. ;; (But if we see -window-system later, use that.)
  1001. (`"-tty"
  1002. (setq tty-name (pop args-left)
  1003. tty-type (pop args-left)
  1004. dontkill (or dontkill
  1005. (not use-current-frame)))
  1006. ;; On Windows, emacsclient always asks for a tty
  1007. ;; frame. If running a GUI server, force the frame
  1008. ;; type to GUI. (Cygwin is perfectly happy with
  1009. ;; multi-tty support, so don't override the user's
  1010. ;; choice there.) In daemon mode on Windows, we can't
  1011. ;; make tty frames, so force the frame type to GUI
  1012. ;; there too.
  1013. (when (and (eq system-type 'windows-nt)
  1014. (or (daemonp)
  1015. (eq window-system 'w32)))
  1016. (push "-window-system" args-left)))
  1017. ;; -position LINE[:COLUMN]: Set point to the given
  1018. ;; position in the next file.
  1019. (`"-position"
  1020. (if (not (string-match "\\+\\([0-9]+\\)\\(?::\\([0-9]+\\)\\)?"
  1021. (car args-left)))
  1022. (error "Invalid -position command in client args"))
  1023. (let ((arg (pop args-left)))
  1024. (setq filepos
  1025. (cons (string-to-number (match-string 1 arg))
  1026. (string-to-number (or (match-string 2 arg)
  1027. ""))))))
  1028. ;; -file FILENAME: Load the given file.
  1029. (`"-file"
  1030. (let ((file (pop args-left)))
  1031. (if coding-system
  1032. (setq file (decode-coding-string file coding-system)))
  1033. ;; Allow Cygwin's emacsclient to be used as a file
  1034. ;; handler on MS-Windows, in which case FILENAME
  1035. ;; might start with a drive letter.
  1036. (when (and (fboundp 'cygwin-convert-file-name-from-windows)
  1037. (string-match "\\`[A-Za-z]:" file))
  1038. (setq file (cygwin-convert-file-name-from-windows file)))
  1039. (setq file (expand-file-name file dir))
  1040. (push (cons file filepos) files)
  1041. (server-log (format "New file: %s %s"
  1042. file (or filepos ""))
  1043. proc))
  1044. (setq filepos nil))
  1045. ;; -eval EXPR: Evaluate a Lisp expression.
  1046. (`"-eval"
  1047. (if use-current-frame
  1048. (setq use-current-frame 'always))
  1049. (let ((expr (pop args-left)))
  1050. (if coding-system
  1051. (setq expr (decode-coding-string expr coding-system)))
  1052. (push (lambda () (server-eval-and-print expr proc))
  1053. commands)
  1054. (setq filepos nil)))
  1055. ;; -env NAME=VALUE: An environment variable.
  1056. (`"-env"
  1057. (let ((var (pop args-left)))
  1058. ;; XXX Variables should be encoded as in getenv/setenv.
  1059. (process-put proc 'env
  1060. (cons var (process-get proc 'env)))))
  1061. ;; -dir DIRNAME: The cwd of the emacsclient process.
  1062. (`"-dir"
  1063. (setq dir (pop args-left))
  1064. (if coding-system
  1065. (setq dir (decode-coding-string dir coding-system)))
  1066. (setq dir (command-line-normalize-file-name dir))
  1067. (process-put proc 'server-client-directory dir))
  1068. ;; Unknown command.
  1069. (arg (error "Unknown command: %s" arg))))
  1070. ;; If both -no-wait and -tty are given with file or sexp
  1071. ;; arguments, use an existing frame.
  1072. (and nowait
  1073. (not (eq tty-name 'window-system))
  1074. (or files commands)
  1075. (setq use-current-frame t))
  1076. (setq frame
  1077. (cond
  1078. ((and use-current-frame
  1079. (or (eq use-current-frame 'always)
  1080. ;; We can't use the Emacs daemon's
  1081. ;; terminal frame.
  1082. (not (and (daemonp)
  1083. (null (cdr (frame-list)))
  1084. (eq (selected-frame)
  1085. terminal-frame)))))
  1086. (setq tty-name nil tty-type nil)
  1087. (if display (server-select-display display)))
  1088. ((or (and (eq system-type 'windows-nt)
  1089. (daemonp)
  1090. (setq display "w32"))
  1091. (eq tty-name 'window-system))
  1092. (server-create-window-system-frame display nowait proc
  1093. parent-id
  1094. frame-parameters))
  1095. ;; When resuming on a tty, tty-name is nil.
  1096. (tty-name
  1097. (server-create-tty-frame tty-name tty-type proc))))
  1098. (process-put
  1099. proc 'continuation
  1100. (lambda ()
  1101. (with-current-buffer (get-buffer-create server-buffer)
  1102. ;; Use the same cwd as the emacsclient, if possible, so
  1103. ;; relative file names work correctly, even in `eval'.
  1104. (let ((default-directory
  1105. (if (and dir (file-directory-p dir))
  1106. dir default-directory)))
  1107. (server-execute proc files nowait commands
  1108. dontkill frame tty-name)))))
  1109. (when (or frame files)
  1110. (server-goto-toplevel proc))
  1111. (server-execute-continuation proc))))
  1112. ;; condition-case
  1113. (error (server-return-error proc err))))
  1114. (defun server-execute (proc files nowait commands dontkill frame tty-name)
  1115. ;; This is run from timers and process-filters, i.e. "asynchronously".
  1116. ;; But w.r.t the user, this is not really asynchronous since the timer
  1117. ;; is run after 0s and the process-filter is run in response to the
  1118. ;; user running `emacsclient'. So it is OK to override the
  1119. ;; inhibit-quit flag, which is good since `commands' (as well as
  1120. ;; find-file-noselect via the major-mode) can run arbitrary code,
  1121. ;; including code that needs to wait.
  1122. (with-local-quit
  1123. (condition-case err
  1124. (let ((buffers (server-visit-files files proc nowait)))
  1125. (mapc 'funcall (nreverse commands))
  1126. ;; If we were told only to open a new client, obey
  1127. ;; `initial-buffer-choice' if it specifies a file
  1128. ;; or a function.
  1129. (unless (or files commands)
  1130. (let ((buf
  1131. (cond ((stringp initial-buffer-choice)
  1132. (find-file-noselect initial-buffer-choice))
  1133. ((functionp initial-buffer-choice)
  1134. (funcall initial-buffer-choice)))))
  1135. (switch-to-buffer
  1136. (if (buffer-live-p buf) buf (get-buffer-create "*scratch*"))
  1137. 'norecord)))
  1138. ;; Delete the client if necessary.
  1139. (cond
  1140. (nowait
  1141. ;; Client requested nowait; return immediately.
  1142. (server-log "Close nowait client" proc)
  1143. (server-delete-client proc))
  1144. ((and (not dontkill) (null buffers))
  1145. ;; This client is empty; get rid of it immediately.
  1146. (server-log "Close empty client" proc)
  1147. (server-delete-client proc)))
  1148. (cond
  1149. ((or isearch-mode (minibufferp))
  1150. nil)
  1151. ((and frame (null buffers))
  1152. (message "%s" (substitute-command-keys
  1153. "When done with this frame, type \\[delete-frame]")))
  1154. ((not (null buffers))
  1155. (server-switch-buffer (car buffers) nil (cdr (car files)))
  1156. (run-hooks 'server-switch-hook)
  1157. (unless nowait
  1158. (message "%s" (substitute-command-keys
  1159. "When done with a buffer, type \\[server-edit]")))))
  1160. (when (and frame (null tty-name))
  1161. (server-unselect-display frame)))
  1162. ((quit error)
  1163. (when (eq (car err) 'quit)
  1164. (message "Quit emacsclient request"))
  1165. (server-return-error proc err)))))
  1166. (defun server-return-error (proc err)
  1167. (ignore-errors
  1168. (server-send-string
  1169. proc (concat "-error " (server-quote-arg
  1170. (error-message-string err))))
  1171. (server-log (error-message-string err) proc)
  1172. ;; Before calling `delete-process', give emacsclient time to
  1173. ;; receive the error string and shut down on its own.
  1174. (sit-for 5)
  1175. (delete-process proc)))
  1176. (defun server-goto-line-column (line-col)
  1177. "Move point to the position indicated in LINE-COL.
  1178. LINE-COL should be a pair (LINE . COL)."
  1179. (when line-col
  1180. (goto-char (point-min))
  1181. (forward-line (1- (car line-col)))
  1182. (let ((column-number (cdr line-col)))
  1183. (when (> column-number 0)
  1184. (move-to-column (1- column-number))))))
  1185. (defun server-visit-files (files proc &optional nowait)
  1186. "Find FILES and return a list of buffers created.
  1187. FILES is an alist whose elements are (FILENAME . FILEPOS)
  1188. where FILEPOS can be nil or a pair (LINENUMBER . COLUMNNUMBER).
  1189. PROC is the client that requested this operation.
  1190. NOWAIT non-nil means this client is not waiting for the results,
  1191. so don't mark these buffers specially, just visit them normally."
  1192. ;; Bind last-nonmenu-event to force use of keyboard, not mouse, for queries.
  1193. (let ((last-nonmenu-event t) client-record)
  1194. ;; Restore the current buffer afterward, but not using save-excursion,
  1195. ;; because we don't want to save point in this buffer
  1196. ;; if it happens to be one of those specified by the server.
  1197. (save-current-buffer
  1198. (dolist (file files)
  1199. ;; If there is an existing buffer modified or the file is
  1200. ;; modified, revert it. If there is an existing buffer with
  1201. ;; deleted file, offer to write it.
  1202. (let* ((minibuffer-auto-raise (or server-raise-frame
  1203. minibuffer-auto-raise))
  1204. (filen (car file))
  1205. (obuf (get-file-buffer filen)))
  1206. (add-to-history 'file-name-history filen)
  1207. (if (null obuf)
  1208. (progn
  1209. (run-hooks 'pre-command-hook)
  1210. (set-buffer (find-file-noselect filen)))
  1211. (set-buffer obuf)
  1212. ;; separately for each file, in sync with post-command hooks,
  1213. ;; with the new buffer current:
  1214. (run-hooks 'pre-command-hook)
  1215. (cond ((file-exists-p filen)
  1216. (when (not (verify-visited-file-modtime obuf))
  1217. (revert-buffer t nil)))
  1218. (t
  1219. (when (y-or-n-p
  1220. (concat "File no longer exists: " filen
  1221. ", write buffer to file? "))
  1222. (write-file filen))))
  1223. (unless server-buffer-clients
  1224. (setq server-existing-buffer t)))
  1225. (server-goto-line-column (cdr file))
  1226. (run-hooks 'server-visit-hook)
  1227. ;; hooks may be specific to current buffer:
  1228. (run-hooks 'post-command-hook))
  1229. (unless nowait
  1230. ;; When the buffer is killed, inform the clients.
  1231. (add-hook 'kill-buffer-hook 'server-kill-buffer nil t)
  1232. (push proc server-buffer-clients))
  1233. (push (current-buffer) client-record)))
  1234. (unless nowait
  1235. (process-put proc 'buffers
  1236. (nconc (process-get proc 'buffers) client-record)))
  1237. client-record))
  1238. (defvar server-kill-buffer-running nil
  1239. "Non-nil while `server-kill-buffer' or `server-buffer-done' is running.")
  1240. (defun server-buffer-done (buffer &optional for-killing)
  1241. "Mark BUFFER as \"done\" for its client(s).
  1242. This buries the buffer, then returns a list of the form (NEXT-BUFFER KILLED).
  1243. NEXT-BUFFER is another server buffer, as a suggestion for what to select next,
  1244. or nil. KILLED is t if we killed BUFFER (typically, because it was visiting
  1245. a temp file).
  1246. FOR-KILLING if non-nil indicates that we are called from `kill-buffer'."
  1247. (let ((next-buffer nil)
  1248. (killed nil))
  1249. (dolist (proc server-clients)
  1250. (let ((buffers (process-get proc 'buffers)))
  1251. (or next-buffer
  1252. (setq next-buffer (nth 1 (memq buffer buffers))))
  1253. (when buffers ; Ignore bufferless clients.
  1254. (setq buffers (delq buffer buffers))
  1255. ;; Delete all dead buffers from PROC.
  1256. (dolist (b buffers)
  1257. (and (bufferp b)
  1258. (not (buffer-live-p b))
  1259. (setq buffers (delq b buffers))))
  1260. (process-put proc 'buffers buffers)
  1261. ;; If client now has no pending buffers,
  1262. ;; tell it that it is done, and forget it entirely.
  1263. (unless buffers
  1264. (server-log "Close" proc)
  1265. (if for-killing
  1266. ;; `server-delete-client' might delete the client's
  1267. ;; frames, which might change the current buffer. We
  1268. ;; don't want that (bug#640).
  1269. (save-current-buffer
  1270. (server-delete-client proc))
  1271. (server-delete-client proc))))))
  1272. (when (and (bufferp buffer) (buffer-name buffer))
  1273. ;; We may or may not kill this buffer;
  1274. ;; if we do, do not call server-buffer-done recursively
  1275. ;; from kill-buffer-hook.
  1276. (let ((server-kill-buffer-running t))
  1277. (with-current-buffer buffer
  1278. (setq server-buffer-clients nil)
  1279. (run-hooks 'server-done-hook))
  1280. ;; Notice whether server-done-hook killed the buffer.
  1281. (if (null (buffer-name buffer))
  1282. (setq killed t)
  1283. ;; Don't bother killing or burying the buffer
  1284. ;; when we are called from kill-buffer.
  1285. (unless for-killing
  1286. (when (and (not killed)
  1287. server-kill-new-buffers
  1288. (with-current-buffer buffer
  1289. (not server-existing-buffer)))
  1290. (setq killed t)
  1291. (bury-buffer buffer)
  1292. ;; Prevent kill-buffer from prompting (Bug#3696).
  1293. (with-current-buffer buffer
  1294. (set-buffer-modified-p nil))
  1295. (kill-buffer buffer))
  1296. (unless killed
  1297. (if (server-temp-file-p buffer)
  1298. (progn
  1299. (with-current-buffer buffer
  1300. (set-buffer-modified-p nil))
  1301. (kill-buffer buffer)
  1302. (setq killed t))
  1303. (bury-buffer buffer)))))))
  1304. (list next-buffer killed)))
  1305. (defun server-temp-file-p (&optional buffer)
  1306. "Return non-nil if BUFFER contains a file considered temporary.
  1307. These are files whose names suggest they are repeatedly
  1308. reused to pass information to another program.
  1309. The variable `server-temp-file-regexp' controls which filenames
  1310. are considered temporary."
  1311. (and (buffer-file-name buffer)
  1312. (string-match-p server-temp-file-regexp (buffer-file-name buffer))))
  1313. (defun server-done ()
  1314. "Offer to save current buffer, mark it as \"done\" for clients.
  1315. This kills or buries the buffer, then returns a list
  1316. of the form (NEXT-BUFFER KILLED). NEXT-BUFFER is another server buffer,
  1317. as a suggestion for what to select next, or nil.
  1318. KILLED is t if we killed BUFFER, which happens if it was created
  1319. specifically for the clients and did not exist before their request for it."
  1320. (when server-buffer-clients
  1321. (if (server-temp-file-p)
  1322. ;; For a temp file, save, and do make a non-numeric backup
  1323. ;; (unless make-backup-files is nil).
  1324. (let ((version-control nil)
  1325. (buffer-backed-up nil))
  1326. (save-buffer))
  1327. (when (and (buffer-modified-p)
  1328. buffer-file-name
  1329. (y-or-n-p (concat "Save file " buffer-file-name "? ")))
  1330. (save-buffer)))
  1331. (server-buffer-done (current-buffer))))
  1332. (defun server-kill-emacs-query-function ()
  1333. "Ask before exiting Emacs if it has live clients."
  1334. (or (not (let (live-client)
  1335. (dolist (proc server-clients)
  1336. (when (memq t (mapcar 'buffer-live-p (process-get
  1337. proc 'buffers)))
  1338. (setq live-client t)))
  1339. live-client))
  1340. (yes-or-no-p "This Emacs session has clients; exit anyway? ")))
  1341. (defun server-kill-buffer ()
  1342. "Remove the current buffer from its clients' buffer list.
  1343. Designed to be added to `kill-buffer-hook'."
  1344. ;; Prevent infinite recursion if user has made server-done-hook
  1345. ;; call kill-buffer.
  1346. (or server-kill-buffer-running
  1347. (and server-buffer-clients
  1348. (let ((server-kill-buffer-running t))
  1349. (when server-process
  1350. (server-buffer-done (current-buffer) t))))))
  1351. (defun server-edit (&optional arg)
  1352. "Switch to next server editing buffer; say \"Done\" for current buffer.
  1353. If a server buffer is current, it is marked \"done\" and optionally saved.
  1354. The buffer is also killed if it did not exist before the clients asked for it.
  1355. When all of a client's buffers are marked as \"done\", the client is notified.
  1356. Temporary files such as MH <draft> files are always saved and backed up,
  1357. no questions asked. (The variable `make-backup-files', if nil, still
  1358. inhibits a backup; you can set it locally in a particular buffer to
  1359. prevent a backup for it.) The variable `server-temp-file-regexp' controls
  1360. which filenames are considered temporary.
  1361. If invoked with a prefix argument, or if there is no server process running,
  1362. starts server process and that is all. Invoked by \\[server-edit]."
  1363. (interactive "P")
  1364. (cond
  1365. ((or arg
  1366. (not server-process)
  1367. (memq (process-status server-process) '(signal exit)))
  1368. (server-mode 1))
  1369. (server-clients (apply 'server-switch-buffer (server-done)))
  1370. (t (message "No server editing buffers exist"))))
  1371. (defun server-switch-buffer (&optional next-buffer killed-one filepos)
  1372. "Switch to another buffer, preferably one that has a client.
  1373. Arg NEXT-BUFFER is a suggestion; if it is a live buffer, use it.
  1374. KILLED-ONE is t in a recursive call if we have already killed one
  1375. temp-file server buffer. This means we should avoid the final
  1376. \"switch to some other buffer\" since we've already effectively
  1377. done that.
  1378. FILEPOS specifies a new buffer position for NEXT-BUFFER, if we
  1379. visit NEXT-BUFFER in an existing window. If non-nil, it should
  1380. be a cons cell (LINENUMBER . COLUMNNUMBER)."
  1381. (if (null next-buffer)
  1382. (progn
  1383. (let ((rest server-clients))
  1384. (while (and rest (not next-buffer))
  1385. (let ((proc (car rest)))
  1386. ;; Only look at frameless clients, or those in the selected
  1387. ;; frame.
  1388. (when (or (not (process-get proc 'frame))
  1389. (eq (process-get proc 'frame) (selected-frame)))
  1390. (setq next-buffer (car (process-get proc 'buffers))))
  1391. (setq rest (cdr rest)))))
  1392. (and next-buffer (server-switch-buffer next-buffer killed-one))
  1393. (unless (or next-buffer killed-one (window-dedicated-p))
  1394. ;; (switch-to-buffer (other-buffer))
  1395. (message "No server buffers remain to edit")))
  1396. (if (not (buffer-live-p next-buffer))
  1397. ;; If NEXT-BUFFER is a dead buffer, remove the server records for it
  1398. ;; and try the next surviving server buffer.
  1399. (apply 'server-switch-buffer (server-buffer-done next-buffer))
  1400. ;; OK, we know next-buffer is live, let's display and select it.
  1401. (if (functionp server-window)
  1402. (funcall server-window next-buffer)
  1403. (let ((win (get-buffer-window next-buffer 0)))
  1404. (if (and win (not server-window))
  1405. ;; The buffer is already displayed: just reuse the
  1406. ;; window. If FILEPOS is non-nil, use it to replace the
  1407. ;; window's own value of point.
  1408. (progn
  1409. (select-window win)
  1410. (set-buffer next-buffer)
  1411. (when filepos
  1412. (server-goto-line-column filepos)))
  1413. ;; Otherwise, let's find an appropriate window.
  1414. (cond ((window-live-p server-window)
  1415. (select-window server-window))
  1416. ((framep server-window)
  1417. (unless (frame-live-p server-window)
  1418. (setq server-window (make-frame)))
  1419. (select-window (frame-selected-window server-window))))
  1420. (when (window-minibuffer-p)
  1421. (select-window (next-window nil 'nomini 0)))
  1422. ;; Move to a non-dedicated window, if we have one.
  1423. (when (window-dedicated-p)
  1424. (select-window
  1425. (get-window-with-predicate
  1426. (lambda (w)
  1427. (and (not (window-dedicated-p w))
  1428. (equal (frame-terminal (window-frame w))
  1429. (frame-terminal))))
  1430. 'nomini 'visible (selected-window))))
  1431. (condition-case nil
  1432. (switch-to-buffer next-buffer)
  1433. ;; After all the above, we might still have ended up with
  1434. ;; a minibuffer/dedicated-window (if there's no other).
  1435. (error (pop-to-buffer next-buffer)))))))
  1436. (when server-raise-frame
  1437. (select-frame-set-input-focus (window-frame)))))
  1438. ;;;###autoload
  1439. (defun server-save-buffers-kill-terminal (arg)
  1440. ;; Called from save-buffers-kill-terminal in files.el.
  1441. "Offer to save each buffer, then kill the current client.
  1442. With ARG non-nil, silently save all file-visiting buffers, then kill.
  1443. If emacsclient was started with a list of filenames to edit, then
  1444. only these files will be asked to be saved."
  1445. (let ((proc (frame-parameter nil 'client)))
  1446. (cond ((eq proc 'nowait)
  1447. ;; Nowait frames have no client buffer list.
  1448. (if (cdr (frame-list))
  1449. (progn (save-some-buffers arg)
  1450. (delete-frame))
  1451. ;; If we're the last frame standing, kill Emacs.
  1452. (save-buffers-kill-emacs arg)))
  1453. ((processp proc)
  1454. (let ((buffers (process-get proc 'buffers)))
  1455. ;; If client is bufferless, emulate a normal Emacs exit
  1456. ;; and offer to save all buffers. Otherwise, offer to
  1457. ;; save only the buffers belonging to the client.
  1458. (save-some-buffers
  1459. arg (if buffers
  1460. (lambda () (memq (current-buffer) buffers))
  1461. t))
  1462. (server-delete-client proc)))
  1463. (t (error "Invalid client frame")))))
  1464. (define-key ctl-x-map "#" 'server-edit)
  1465. (defun server-unload-function ()
  1466. "Unload the Server library."
  1467. (server-mode -1)
  1468. (substitute-key-definition 'server-edit nil ctl-x-map)
  1469. (save-current-buffer
  1470. (dolist (buffer (buffer-list))
  1471. (set-buffer buffer)
  1472. (remove-hook 'kill-buffer-hook 'server-kill-buffer t)))
  1473. ;; continue standard unloading
  1474. nil)
  1475. (defun server-eval-at (server form)
  1476. "Contact the Emacs server named SERVER and evaluate FORM there.
  1477. Returns the result of the evaluation, or signals an error if it
  1478. cannot contact the specified server. For example:
  1479. (server-eval-at \"server\" \\='(emacs-pid))
  1480. returns the process ID of the Emacs instance running \"server\"."
  1481. (let* ((server-dir (if server-use-tcp server-auth-dir server-socket-dir))
  1482. (server-file (expand-file-name server server-dir))
  1483. (coding-system-for-read 'binary)
  1484. (coding-system-for-write 'binary)
  1485. address port secret process)
  1486. (unless (file-exists-p server-file)
  1487. (error "No such server: %s" server))
  1488. (with-temp-buffer
  1489. (when server-use-tcp
  1490. (let ((coding-system-for-read 'no-conversion))
  1491. (insert-file-contents server-file)
  1492. (unless (looking-at "\\([0-9.]+\\):\\([0-9]+\\)")
  1493. (error "Invalid auth file"))
  1494. (setq address (match-string 1)
  1495. port (string-to-number (match-string 2)))
  1496. (forward-line 1)
  1497. (setq secret (buffer-substring (point) (line-end-position)))
  1498. (erase-buffer)))
  1499. (unless (setq process (make-network-process
  1500. :name "eval-at"
  1501. :buffer (current-buffer)
  1502. :host address
  1503. :service (if server-use-tcp port server-file)
  1504. :family (if server-use-tcp 'ipv4 'local)
  1505. :noquery t))
  1506. (error "Unable to contact the server"))
  1507. (if server-use-tcp
  1508. (process-send-string process (concat "-auth " secret "\n")))
  1509. (process-send-string process
  1510. (concat "-eval "
  1511. (server-quote-arg (format "%S" form))
  1512. "\n"))
  1513. (while (memq (process-status process) '(open run))
  1514. (accept-process-output process 0 10))
  1515. (goto-char (point-min))
  1516. ;; If the result is nil, there's nothing in the buffer. If the
  1517. ;; result is non-nil, it's after "-print ".
  1518. (let ((answer ""))
  1519. (while (re-search-forward "\n-print\\(-nonl\\)? " nil t)
  1520. (setq answer
  1521. (concat answer
  1522. (buffer-substring (point)
  1523. (progn (skip-chars-forward "^\n")
  1524. (point))))))
  1525. (if (not (equal answer ""))
  1526. (read (decode-coding-string (server-unquote-arg answer)
  1527. 'emacs-internal)))))))
  1528. (provide 'server)
  1529. ;;; server.el ends here