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

21,358

Solution 1

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 2

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

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

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.

Solution 5

Add this to your .bashrc/.zshrc

if ! ps -e -o args | grep -q '^emacs --daemon$'; then
  emacs --daemon
else
  echo "Emacs server Online"
fi

Update: now I prefer to use this line instead:

if ! ps -e -o args | grep -i 'emacs' | grep 'daemon'; then

because the process name will depend on your machine or the way you installed emacs.


Now your shell will start the deamon on startup, but only if it is not already running. Less wait time when you first run emacsclient -t, and it is faster than letting emacs --daemon check if it's already running.

As an alternative you could simply add:

eval 'emacsclient -e "(server-running-p)"'
Share:
21,358
Meng Lu
Author by

Meng Lu

Updated on December 09, 2021

Comments

  • Meng Lu
    Meng Lu over 2 years

    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