UP | HOME

Ping's Tech Notes

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:

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:

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.