server.el 62 KB

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