How to run the emacs daemon only when needed

emacs

From what I have read, one way to speed up the emacs startup is to run emacs --daemon on login and then open files using emacslient instead of emacs, which will access the running emacs server instead of creating a new emacs instance.

However, I prefer to not put proframs in my autostart unless absolutely necessary, as a way yo speed up the login process. Is there a robust way to detect if an emacs server is running? This would let me write a simple script that would spawn the emacs server the first time I open a file with emacs.

#!/bin/sh
if emacs_daemon_is_not_running # <-- How do I do this?
then
    emacs --daemon
fi
emacsclient -c "$@"

Best Answer

You shouldn't even need to test if emacs is already running or not. emacsclient can start the emacs daemon if it's not already running. From emacsclient(1):

   -a, --alternate-editor=EDITOR
          if the Emacs server is not running,  run  the  specified  editor
          instead.   This can also be specified via the `ALTERNATE_EDITOR'
          environment variable.  If the  value  of  EDITOR  is  the  empty
          string,  run `emacs --daemon' to start Emacs in daemon mode, and
          try to connect to it.

I use an alias, ge, for editing files, defined like this:

alias ge="emacsclient -c -n --alternate-editor=\"\""
Related Question