I use Emacs in terminals and start/close Emacs frequently as needed like in a file checking-editing-closing loop. However, Emacs seems take some time to start up especially some heavy modes are used. How to make Emacs start up faster?
(If you just want the solution/script first, find the command in the summary section.)
My solution is to make use of the server/client feature of Emacs
Table of Contents
This is how it works.
Emacs supports server/client architecture which is the key mechanism for faster Emacs startup here. Starting the server once and it is acceptable if it takes some time. When editing a file, start an Emacs client to connect to the server to edit the file, which is fast.
However, several other tunnings/scripts are need to make it more handy.
How and when to start the Emacs server?
Invoking it at the startup of the desktop environment as a autostart script?—What if the server is killed? What if you are working on a remote server? Manually start it?—It will too annoying.
Either choice is not good enough. On the other hand, the
-a option has a very nice feature: "If the value of EDITOR is the empty string, run
emacs --daemon to start Emacs in daemon mode, and try to connect to it". So, with the
-a="" option in the command, the first time the
emacsclient is invoked and there is no server running, the Emacs server is automatically started.
After each invoking of the emacsclient, should I always switch to the server instance?
Not needed. Emacs support the convenient "multiple tty" feature. With the
emacsclient starts a new frame just at the terminal or console where it is invoked: "-c, –create-frame create a new frame instead of trying to use the current Emacs frame".
How to manually shutdown the Emacs server?
Simply killing the Emacs is not safe—some files may have been changed and not saved yet. Let’s use an elisp function to save the buffers and kill the emacs in the
;; define function to shutdown emacs server instance (defun server-shutdown () "Save buffers, Quit, and Shutdown (kill) server" (interactive) (save-some-buffers) (kill-emacs))
When you want to kill the emacs server, run
emacsclient -e '(server-shutdown)' which can be put into a command file like
In summary, the command
The key is this command:
emacsclient -c -a="" $*. For faster invoking, save it as a executable command, like
em, in some directory in your
#!/bin/env bash emacsclient -c -a="" $*
When you want to edit a file, simply run
All the functions/scripts can be found in my Emacs config.