From d3860d6ce9c0d55b416b294cff6be67f734d9b84 Mon Sep 17 00:00:00 2001 From: Gregory Heytings Date: Sun, 24 Oct 2021 15:08:31 +0000 Subject: [PATCH] Option to stop emacs server when it has no clients anymore. * lisp/server.el (server-stop-when-no-clients): New function. * doc/emacs/misc.texi (Emacs Server): Document the new function, and mention that an Emacs server can be started with emacsclient. --- doc/emacs/misc.texi | 10 ++++++++++ lisp/server.el | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/doc/emacs/misc.texi b/doc/emacs/misc.texi index 810d212021..a68632831a 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,11 @@ Emacs Server emacs --daemon=foo @end example +@findex server-stop-when-no-clients + If you want to automatically stop the Emacs server when it has no +clients anymore, put the expression @code{(server-stop-when-no-clients)} +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..fb1cb886e1 100644 --- a/lisp/server.el +++ b/lisp/server.el @@ -1746,6 +1746,15 @@ server-save-buffers-kill-terminal (server-delete-client proc))) (t (error "Invalid client frame"))))) +;;;###autoload +(defun server-stop-when-no-clients () + "Automatically stop server when it has no remaining clients. +This function is meant to be put in init files." + (when (daemonp) + (run-with-timer 10 2 (lambda () + (unless (cdr (frame-list)) + (save-buffers-kill-emacs)))))) + (define-key ctl-x-map "#" 'server-edit) (defun server-unload-function () -- 2.33.0