![[Home]](https://www.emacswiki.org/images/logo218x38.png)
Emacs supports a client/server mode where new files are opened in a running instance of Emacs. This saves you from having to load configuration and packages for every new file you open and allows the sharing of buffers between different emacs frames opened externally. This involves two configuration steps: using EmacsClient to open files, and running the Emacs server. This page focuses on how to launch the server at startup, a.k.a. daemon mode. This feature was introduced in Emacs 23.1
Systemd is the supported method of running applications at startup on most Linux distributions.
If the emacs service file is properly installed, you can simply run:
systemctl --user enable --now emacs
If you don’t have the user service unit installed, you first need to create the file ~/.config/systemd/user/emacs.service with the following content (which was included in prior versions of emacs):
[Unit] Description=Emacs text editor Documentation=info:emacs man:emacs(1) https://gnu.org/software/emacs/ [Service] Type=forking ExecStart=/usr/bin/emacs --daemon ExecStop=/usr/bin/emacsclient --eval "(kill-emacs)" #Environment=SSH_AUTH_SOCK=%t/keyring/ssh Restart=on-failure [Install] WantedBy=default.target
(Modern emacs uses a different unit file, which relies on the --fg-daemon option introduced in version 26.)
If the graphical environment is unavailable when the emacs daemon launches, it will launch in text only mode, which means that text emacsclient sessions (inside of a terminal) will launch, but graphical emacsclient sessions will fail. Unfortunately, on Wayland this is easily triggered even with a graphical login manager (on X11 this is usually only encountered if first logging into a plain tty, starting the emacs daemon, then later starting the X11 environment). We have to instruct systemd to wait until after the graphical environment is available before starting emacs if it’s trying to start them at the same time.
If you already have an emacs user service unit and are running modern systemd (since version 218), run $ EDITOR=emacs systemctl --user edit emacs.service --drop-in=10-after-gfx and add the following content:
[Unit] After=graphical-session.target
Then run $ systemctl --user restart emacs
If your systemd doesn’t have the edit command or support for their drop-in framework, add the following line to the [Unit] section of the service file provided in the section above:
After=graphical-session.target
Unlike many other service units, you do not want a “Requires=” or “Wants=” line corresponding to the “After=” line in these units. This would cause systemd to attempt to start the entirety of that graphics environment when just starting emacs, for example, when logging in to a text tty without already having a graphical session running. (Furthermore, in current KDE, this will cause systemd to attempt to launch plasma-ksmserver either early or an extra copy thereof, which in turn tries to run some X11 commands before Xwayland is fully started. This causes the ksmserver to segfault, which causes other plasma components to crash, and will mess with your login in a variety of ways, including freezing the mouse and keyboard until they are reconnected, and being unable to launch any graphical windows in that session until the emacs service is stopped.)
With only the “After=” directive, systemd will do the right thing and delay emacs’s launch if it is being started as part of a graphical login, and let it start in text mode if there’s no graphics server available. If the user wants to do some work in text mode and then latter open graphical windows (eg working in a tty then also opening a graphical session), they will have to issue $ systemctl --user restart emacs after, which is just a limitation of how emacs (cough the gtk…) handles graphical environments.
emacs --daemon
In Emacs 26.1+, you can force the daemon to run in the foreground:
emacs --fg-daemon
There are other ways to launch emacs --daemon depending on your requirements.
EL 7 does not support --user configurations for systemd. Instead, you can use this unit file:
[Unit]
Description=Emacs: the extensible, self-documenting text editor
[Service]
Type=forking
ExecStart=/usr/bin/emacs --daemon --user %u
ExecStop=/usr/bin/emacsclient --eval "(progn (setq kill-emacs-hook 'nil) (kill-emacs))"
Restart=always
User=%i
WorkingDirectory=%h
[Install]
WantedBy=multi-user.target
Save it as /usr/lib/systemd/system/emacs@.service and then install it:
systemctl daemon-reload systemctl enable emacs@<user> systemctl start emacs@<user>
add /usr/bin/emacs --daemon to your ~/.xinitrc
You can place an init script to place in /etc/init.d/emacsd. Here are examples for GNU Debian/Ubuntu.
Gentoo includes support for running Emacs as a daemon in the app-emacs/emacs-daemon package.
Every user who wants to connect to an Emacs server must have an own instance of the daemonized Emacs. The init script automatically determines the user by its name, so you create a symbolic linke emacs.service file from ~/.config/systemd/user/default.target.wants to ~/.config/systemd/user/graphical-session.target.wants, but that didn’t change anything. (do not copy the script, or you will miss eventual updates!) in your /etc/init.d directory:
This may be added to the boot sequence (and will run under the user’s privileges)
Further customizations can be done through the /etc/conf.d/emacs file, which is extensively commented. You may also create individual /etc/conf.d/emacs.username files for “multiplexed” user configuration.
Just add the relevant configuration option as described in the manual. To restart the daemon after changing the user configuration, run
systemctl --user restart emacs
If you’re running Emacs 23 or higher, you can run Emacs Daemon via macOS’s launchd. The easiest solution is to use a tool like Lingon to create the plist file or can create one manually like this:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>gnu.emacs.daemon</string> <key>ProgramArguments</key> <array> <string>/Applications/Emacs.app/Contents/MacOS/Emacs</string> <string>--daemon</string> </array> <key>RunAtLoad</key> <true/> <key>ServiceDescription</key> <string>Gnu Emacs Daemon</string> </dict> </plist>
This can then be installed in ~/Library/LaunchAgents and loaded via:
launchctl load -w ~/Library/LaunchAgents/gnu.emacs.daemon.plist
For further instructions see [1]
To set environment variable(s) for the daemon, add an EnvironmentVariables <dictionary of strings> section to the plist file. See the launchd.plist man page for details man 5 launchd.plist for details.
You can run emacs --daemon by creating a shortcut file or .bat file in the startup folder. See EmacsMsWindowsIntegration for details.
The simplest way to stop the emacs daemon from within emacs is to use the kill-emacs or save-buffers-kill-emacs commands.
Here is a more advanced function will ask if you want to save any modified buffers, quit your session, and shutdown the associated emacs server instance.
;; define function to shutdown emacs server instance (defun server-shutdown () "Save buffers, Quit, and Shutdown (kill) server" (interactive) (save-some-buffers) (kill-emacs) )
From outside of emacs this can be achieved using emacsclient, using the -e execute command:
emacsclient -e '(kill-emacs)'
This will shutdown the daemon immediately with out prompting or saving files.
If you would like emacs to prompt if there are unsaved buffers or existing clients/frames, you can add the following functions to your .emacs file then use the command:
emacsclient -e '(client-save-kill-emacs)'
The display on which the new frame should be opened can optionally be specified. If a prompt is required this function will always open an frame as an x window.
(defun client-save-kill-emacs(&optional display)
" This is a function that can bu used to save buffers and
shutdown the emacs daemon. It should be called using
emacsclient -e '(client-save-kill-emacs)'. This function will
check to see if there are any modified buffers, active clients
or frame. If so, an x window will be opened and the user will
be prompted."
(let (new-frame modified-buffers active-clients-or-frames)
; Check if there are modified buffers, active clients or frames.
(setq modified-buffers (modified-buffers-exist))
(setq active-clients-or-frames ( or (> (length server-clients) 1)
(> (length (frame-list)) 1)
))
; Create a new frame if prompts are needed.
(when (or modified-buffers active-clients-or-frames)
(when (not (eq window-system 'x))
(message "Initializing x windows system.")
(x-initialize-window-system))
(when (not display) (setq display (getenv "DISPLAY")))
(message "Opening frame on display: %s" display)
(select-frame (make-frame-on-display display '((window-system . x)))))
; Save the current frame.
(setq new-frame (selected-frame))
; When displaying the number of clients and frames:
; subtract 1 from clients (this client).
; subtract 2 from frames (the frame just created and the default frame.)
(when (or (not active-clients-or-frames)
(yes-or-no-p (format "There are currently %d clients and %d frames. Exit anyway?" (- (length server-clients) 1) (- (length (frame-list)) 2))))
; If the user quits during the save dialog then don't exit emacs.
; Still close the terminal though.
(let((inhibit-quit t))
; Save buffers
(with-local-quit
(save-some-buffers))
(if quit-flag
(setq quit-flag nil)
; Kill all remaining clients
(progn
(dolist (client server-clients)
(server-delete-client client))
; Exit emacs
(kill-emacs)))
))
; If we made a frame then kill it.
(when (or modified-buffers active-clients-or-frames) (delete-frame new-frame))
)
)
(defun modified-buffers-exist()
"This function will check to see if there are any buffers
that have been modified. It will return true if there are
and nil otherwise. Buffers that have buffer-offer-save set to
nil are ignored."
(let (modified-found)
(dolist (buffer (buffer-list))
(when (and (buffer-live-p buffer)
(buffer-modified-p buffer)
(not (buffer-base-buffer buffer))
(or
(buffer-file-name buffer)
(progn
(set-buffer buffer)
(and buffer-offer-save (> (buffer-size) 0))))
)
(setq modified-found t)
)
)
modified-found
)
)
When the emacs daemon is started as a GNOME startup application (by adding “emacs --daemon” as one of the startup applications), you can use the following code in your init file to make emacs register as a client with the GNOME session manager, and shutdown gracefully when the session ends.
;;; save & shutdown when we get an "end of session" signal on dbus (require 'dbus) (defun my-register-signals (client-path) "Register for the 'QueryEndSession' and 'EndSession' signals from Gnome SessionManager. When we receive 'QueryEndSession', we just respond with 'EndSessionResponse(true, \"\")'. When we receive 'EndSession', we append this EndSessionResponse to kill-emacs-hook, and then call kill-emacs. This way, we can shut down the Emacs daemon cleanly before we send our 'ok' to the SessionManager." (setq my-gnome-client-path client-path) (let ( (end-session-response (lambda (&optional arg) (dbus-call-method-asynchronously :session "org.gnome.SessionManager" my-gnome-client-path "org.gnome.SessionManager.ClientPrivate" "EndSessionResponse" nil t "") ) ) ) (dbus-register-signal :session "org.gnome.SessionManager" my-gnome-client-path "org.gnome.SessionManager.ClientPrivate" "QueryEndSession" end-session-response ) (dbus-register-signal :session "org.gnome.SessionManager" my-gnome-client-path "org.gnome.SessionManager.ClientPrivate" "EndSession" `(lambda (arg) (add-hook 'kill-emacs-hook ,end-session-response t) (kill-emacs) ) ) ) ) ;; DESKTOP_AUTOSTART_ID is set by the Gnome desktop manager when emacs ;; is autostarted. We can use it to register as a client with gnome ;; SessionManager. (dbus-call-method-asynchronously :session "org.gnome.SessionManager" "/org/gnome/SessionManager" "org.gnome.SessionManager" "RegisterClient" 'my-register-signals "Emacs server" (getenv "DESKTOP_AUTOSTART_ID"))
It is possible to run multiple Emacs servers on one machine. This makes it possible to isolate tasks and use different preference files for different workloads.
Instructions can be found on MultiEmacsServer.
Emacs won’t start the daemon if its permissions aren’t secure. If you receive an error that /tmp/emacs1000 (or another number) isn’t safe, do `ls -l /tmp`. The entry for the emacs1000 directory will probably look like `drwxr-x—`. Simply do a `chmod 700 /tmp/emacs1000` to set them to the correct `drwx——` and start the daemon again.
There are unfortunate possibilities of being unable to connect to a running server> This has been observed as: 1) the server being stopped and then all visible frames closed (e.g. server-force-delete + ssh disconnect); 2) the server socket file being deleted. There may be other examples.
It may be possible to connect to the process with gdb and then call some function to execute lisp code to restart the server. If anyone knows how to do that, please insert that information here.
We don’t know how to re-connect to the running server in vanilla emacs, but here is a workaround, which sets up a signal handler to restart the server. Add the following to your emacs startup elisp:
(defun signal-restart-server () "Handler for SIGUSR1 signal, to (re)start an emacs server. Can be tested from within emacs with: (signal-process (emacs-pid) 'sigusr1) or from the command line with: $ kill -USR1 <emacs-pid> $ emacsclient -c " (interactive) (server-force-delete) (server-start) ) (define-key special-event-map [sigusr1] 'signal-restart-server)
Once that code has been loaded, sending a USR1 to the emacs process will restart the server. You can now reconnect. Joy.