Next: , Previous: Shell, Up: Top


42 Using Emacs as a Server

Various programs such as mail can invoke your choice of editor to edit a particular piece of text, such as a message that you are sending. By convention, most of these programs use the environment variable EDITOR to specify which editor to run. If you set EDITOR to ‘emacs’, they invoke Emacs—but in an inconvenient way, by starting a new Emacs process. This is inconvenient because the new Emacs process doesn't share buffers, a command history, or other kinds of information with any existing Emacs process.

You can solve this problem by setting up Emacs as an edit server, so that it “listens” for external edit requests and acts accordingly. There are two ways to start an Emacs server:

The first is to run the command server-start in an existing Emacs process: either type M-x server-start, or put the expression (server-start) in your initialization file (see Init File). The existing Emacs process is the server; when you exit Emacs, the server dies with the Emacs process.

The second way to start an Emacs server is to run Emacs as a daemon, using the ‘--daemon’ command-line option. See Initial Options. When Emacs is started this way, it calls server-start after initialization, and returns control to the calling terminal instead of opening an initial frame; it then waits in the background, listening for edit requests.

Once an Emacs server is set up, you can use a shell command called emacsclient to connect to the existing Emacs process and tell it to visit a file. If you set the EDITOR environment variable to ‘emacsclient’, programs such as mail will use the existing Emacs process for editing.1

You can run multiple Emacs servers on the same machine by giving each one a unique “server name”, using the variable server-name. For example, M-x set-variable <RET> server-name <RET> foo <RET> sets the server name to ‘foo’. The emacsclient program can specify a server by name, using the ‘-s’ option (see emacsclient Options).


Footnotes

[1] Some programs use a different environment variable; for example, to make TeX use ‘emacsclient’, set the TEXEDIT environment variable to ‘emacsclient +%d %s’.