Batch export of org-mode files from the command line

Dror picture Dror · Feb 27, 2014 · Viewed 9.4k times · Source

Assume that I have in a certain directory several org-mode files: foo1.org, foo2.org, etc. I would like to have a script (maybe a makefile) that I could invoke something like

$ generate-pdfs

and foo1.pdf, foo2.pdf, etc. will be generated.

I thought that something like emacs --batch --eval <MAGIC> is a good start, but I don't know the magic.

A solution that is solely inside emacs could be of interest as well.

Answer

florianlh picture florianlh · Feb 28, 2014

As you said, Emacs has the --batch option to perform operations with Emacs from the shell. In addition to that, you can use the -l flag to load Emacs Lisp code from a file and execute it, and the -f flag to execute a single Lisp function.

Here is a basic example, which exports a single org-mode file to HTML:

emacs myorgfile.org --batch -f org-html-export-to-html --kill

Perhaps you want something more advanced like exporting/publishing a full org-mode project. I do not have sample code for that, but it should not be too complicated.

I also have a sample Makefile I wrote some time ago to export all org-mode files in the directory to HTML (and also copy the HTML files to another directory):

OUT_DIR=/some/output/dir/html
# Using GNU Make-specific functions here
FILES=$(patsubst %.org,$(OUT_DIR)/%.html,$(wildcard *.org))

.PHONY: all clean install-doc

all: install-doc

install-doc: $(OUT_DIR) $(FILES)

$(OUT_DIR):
        mkdir -v -p $(OUT_DIR)

%.html: %.org
        emacs $< --batch -f org-html-export-to-html--kill

$(OUT_DIR)/%.html: %.html
        install -v -m 644 -t $(OUT_DIR) $<
        rm $<

clean:
        rm *.html

EDIT:

With Org-mode 8 and the new export engine the function for HTML export has changed.

To make the previous examples work with Org 7 or older, replace org-html-export-to-html with org-export-as-html.