How to start emacs server only if it is not started?

I'd like to use emacsclient to edit emails in Mutt.

I added this in .emacs

(server-start)

And in .muttrc I added

set editor="emacsclient -nw %s"

It seems they work. When I start a second Emacs, it complains there is already a server running so it issues errors. How to make sure to do (server-start) only if the server isn't already started?

Thanks


Solution 1:

This code starts the server only if it's not running:

(load "server")
(unless (server-running-p) (server-start))

Solution 2:

The emacs daemon can be started automatically in a very simple manner. Just add this to your .bashrc/.zshrc/whatever

export ALTERNATE_EDITOR=""

Now when you invoke emacsclient (using either --tty or --create-frame) the server will be started (with emacs --daemon) if it's not already running.

I also find this shell alias handy:

alias e='emacsclient --tty'

Note that since Emacs 23 this is the preferred way to use Emacs in daemon mode. (start-server) is now mostly deprecated.

Solution 3:

A bit of a late answer, but here is the solution that works for me. Whenever I start emacsclient, I use emacsclient -a '' -c The -a '' tells emacsclient to attempt to connect to an existing server, and if no server exists, start one then connect to it.

Solution 4:

Avoid the problem alltogether via

emacs --daemon

in any shell or terminal so that Emacs runs in the background. That way emacsclient is always happy as there is always an Emacs server to connect to.

This being Emacs, there is also a function that starts the server only when needed but I can't quite recall its name right now. I use the --daemon option happily quite happily myself.