Friday, June 20, 2008

Run emacs in batch mode to byte-compile elisp files

emacs is my favorite text editor. (No flame please.)

Little known and used perhaps is the fact that emacs does run in batch mode. By batch, I mean emacs accepts and executes commands in the command line, without any user interaction.

You can emulate a typical emacs text editing session as follow:
$ emacs -batch afile.txt -l runme.el -f save-buffer -kill

This command opens the afile.txt in batch emacs mode.

The -l parameter specifies an elisp file to load and execute. In this example, it loads the elisp file named runme.el which modifies the file buffer.

Next, it saves the buffer. Note that the -f parameter tells emacs to run a command, save-buffer in this case.

Finally, the -kill tells emacs to exit.

Below, I run emacs in batch to byte-compile a list of source elisp files. This comes in handy if you have a lot of source elisp files to compile.

$ emacs -batch -l runme.el -kill

Note that I do not need to save the buffer. Hence, no save-buffer.

The output byte-code files (.elc) will be put in the same directory as the source elisp files.

The runme.el file contains the commands to byte-compile the source elisp files.
$ cat runme.el
(byte-compile-file "/home/peter/emacs/mods/log4j-mode.el")
(byte-compile-file "/home/peter/emacs/mods/vm-w3m.el")


Aravinda said...

Thanks a lot, I created a el file with list of files using below command and compiled using your code :)

find .emacs.d/site-lisp/ -name "*.el" | awk '{print "(byte-compile-file \"" $1 "\")";}' > runme.el

Tom Roche said...

One can also run purely from the commandline, without a commandfile. E.g., to byte-compile *.el from the cwd, do

find ./ -name '*.el' | xargs emacs -batch -f batch-byte-compile

However you may have problems with compile order, in which case creating/editing the commandfile will be useful.

Miguel Guedes said...

This works nicely for adhoc byte-compilations:

$ echo "foo.el" | emacs -Q -f byte-compile-file --batch