Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if emacs server is running

Tags:

emacs

I'd like to execute some code in my init file only if emacs server is running (specifically if emacs is started with the --daemon flag). There doesn't seem to be any hook that runs when server-start is called and there's no variable I can look at to see if the server is running.

A hack is to use (featurep 'server), since the server feature is not loaded unless the server is started, and this does seem to work for my purposes, but I'd like to know what the right way of doing this is. Thanks.

like image 309
pheaver Avatar asked Sep 13 '10 22:09

pheaver


2 Answers

If a server process is running, the associated process object is server-process. Testing if server-process is non-nil tells you whether the server is supposed to be running; you can test its status to check that it's in an acceptable state.

(and (boundp 'server-process)
     (memq (process-status server-process) '(connect listen open run)))

You can test whether Emacs was invoked as a daemon with (daemonp).

like image 161
Gilles 'SO- stop being evil' Avatar answered Sep 28 '22 04:09

Gilles 'SO- stop being evil'


Update: the code posted by Gilles throws if a buffer has no process, like "Buffer scratch has no process". When this code is used in ~/.emacs.el then we risk that Emacs does not start up. To catch the error:

(defun --running-as-server ()
    "Returns true if `server-start' has been called."
  (condition-case nil
      (and (boundp 'server-process)
           (memq (process-status server-process)
                 '(connect listen open run)))
    (error)))
like image 27
Andreas Spindler Avatar answered Sep 28 '22 04:09

Andreas Spindler