From b699c16bac38923e43992edf27039a5d9bcca4f1 Mon Sep 17 00:00:00 2001 From: Gregory Heytings Date: Sun, 24 Oct 2021 18:40:39 +0000 Subject: [PATCH] Option to automatically stop Emacs server. * lisp/server.el (server-stop-automatically): New function. * doc/emacs/misc.texi (Emacs Server): Document the new function. Also mention that an Emacs server can be started with emacsclient. --- doc/emacs/misc.texi | 11 +++++++++++ lisp/server.el | 23 +++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/doc/emacs/misc.texi b/doc/emacs/misc.texi index 5123a716dc..893e5f1843 100644 --- a/doc/emacs/misc.texi +++ b/doc/emacs/misc.texi @@ -1697,6 +1697,11 @@ Emacs Server calls @code{server-start} after initialization and does not open an initial frame. It then waits for edit requests from clients. +@item +Run the command @code{emacsclient} with the @samp{--alternate-editor=""} +command-line option. This starts an Emacs daemon only if no Emacs daemon +is already running. + @cindex systemd unit file @item If your operating system uses @command{systemd} to manage startup, @@ -1763,6 +1768,12 @@ Emacs Server emacs --daemon=foo @end example +@findex server-stop-automatically + If you want to automatically stop the Emacs server when it has no +clients, no unsaved buffers and no running processes anymore, put the +expression @code{(server-stop-automatically)} in your init file +(@pxref{Init File}). + @findex server-eval-at If you have defined a server by a unique server name, it is possible to connect to the server from another Emacs instance and evaluate Lisp diff --git a/lisp/server.el b/lisp/server.el index 6359a76199..944f1a3dce 100644 --- a/lisp/server.el +++ b/lisp/server.el @@ -1746,6 +1746,29 @@ server-save-buffers-kill-terminal (server-delete-client proc))) (t (error "Invalid client frame"))))) +;;;###autoload +(defun server-stop-automatically () + "Automatically stop server when possible. +The server is stopped when it has no remaining clients, no remaining +unsaved buffers, and no running processes with a query-on-exit flag. +This function is meant to be put in init files." + (when (daemonp) + (run-with-timer + 10 2 + (lambda () + (unless (cdr (frame-list)) + (when (and + (not (memq t (mapcar (lambda (b) + (and (buffer-file-name b) + (buffer-modified-p b))) + (buffer-list)))) + (not (memq t (mapcar (lambda (p) + (and (memq (process-status p) + '(run stop open listen)) + (process-query-on-exit-flag p))) + (process-list))))) + (kill-emacs))))))) + (define-key ctl-x-map "#" 'server-edit) (defun server-unload-function () -- 2.33.0