Exporting .org files to HTML in batch
Ping Zhou, 2020-01-09
I use org-mode in Emacs and have multiple .org files to track different information in my life. Sometimes I want to export my .org files as HTML so they can be easily viewed on another device. The org-mode package does provide commands to do this on individual file (such as “org-html-export-to-html”), but doing this on each file manually is tedious. So I decided to write my own elisp function to augment my Emacs environment.
The goal of my elisp function is pretty simple:
- Given a folder, it will search for “.org” files recursively
- And for each .org file found, it exports it to an HTML file
Here is my elisp code:
;; Export .org file to HTML (defun pz/export-org (f) (interactive) (message "exporting from %s" f) (let ((current-buffers (buffer-list)) (tmp-buffer) (open (find-buffer-visiting f)) (org-file-buffer (find-file-noselect f))) (with-current-buffer org-file-buffer (org-html-export-to-html)) (unless open (kill-buffer org-file-buffer))) ) ;; Recursively export all .org files to HTML (defun pz/export-all-org () (interactive) (let ((dir (read-directory-name "Directory: "))) (mapc 'pz/export-org (directory-files-recursively dir "org$"))))
The first function (pz/export-org
) simply export a given .org file to HTML. It basically calls org-html-export-to-html
on current buffer. The tricky part is dealing with the buffers:
- If the file is not opened yet (not in buffer list), it should open it in a temporary buffer.
- Otherwise it should “visit” the buffer of the file.
- When it finishes exporting, should it kill the buffer? We should only kill the buffer if it is opened temporarily. We do not want to kill the buffer if the file was already opened before this function is called.
The next function (pz/export-all-org
) is pretty straightforward. It uses the directory-files-recursively
to recursively search for “org” files, and call pz/export-org
on each of them.