Daemonic Emacs

Emacs is many things, but lightweight is not one of them. You don’t want to be
starting a new Emacs process every time you edit a file, especially if you have
an extensive set of customizations and extensions being loaded by default. If
you’re using a recent version of Emacs and you’re not using its ability to run
as a daemonized server, you’re missing out.

This is a feature which was long available in XEmacs but only recently found its
way into core FSF Emacs. When passed the --daemon option, Emacs will
start up, but without any “frames” (AKA windows) showing. So long as you also
have emacs configured to start as a server (see below), you can now use the
emacsclient command to open new windows from the running Emacs
instance. These new windows will open instantaneously since they don’t have to
wait for Emacs to start up, and they will all share a common buffer list,
kill-ring, etc.

Here’s some code from my .emacs which initializes Emacs as a server:

This is a bit more complicated than strictly necessary. Like much of my Emacs
configuration, it evolved over years of using multiple Emacs versions on
multiple platforms. The important part is that it starts the Emacs server with
(server-start). It also starts up the “edit-server.el” library,
which enables the Chrome Edit in Emacs” extension to talk to the running Emacs
process.

With this configuration out of the way, I need to make sure I start Emacs up in
daemon mode unless a daemon is already running. Here’s the script I use to open files in Emacs:

This script uses emacsclient to first attempt to contact an existing
Emacs server. If it fails, the -a option tells it to try an alternate
editor. The "" argument for -a is special: it tells
emacsclient to start a new daemon Emacs process and then re-attempt the
server connection attempt. I usually create a launcher icon for this file on my
GNOME panel so I can quickly open a new Emacs window.

All that remains is to configure the shell to use that script as the default editor:

And there you have it: instantaneous Emacs windows with shared context,
accessible both from the desktop and the command line.

5 comments

  1. This article mentions that loading emacs can be time consuming especially if you have lots of customizations.
    If you really like your customizations, and you always want them, then try loading these in the site-lisp directory and
    rebuilding emacs.  When emacs is compiled the make file runs the emacs executable, which causes the lisp engine
    to load, and then the executable is written to call an internal function that creates a new elf executable from the
    running image in memory. 

Leave a Reply

Your email address will not be published. Required fields are marked *