How to export org file to HTML file when save?

Note: The below was written for Emacs 23. Check the answer by @AndreasSpindler for an up-to-date solution.

Emacs has a couple of hooks which are called in certain events. The hook you are looking for is probably the after-save-hook. Just set it to the function you want to run every time you save the file. In your case this would be org-html-export-to-html.

There are many ways to do this, but the following method is probably the fastest and doesn't involve any "real" elisp. Put the following lines somewhere in your org file:

# Local variables:
# after-save-hook: org-html-export-to-html
# end:

The next time you open that file, you'll get a warning and be asked if the local variable should be set (as that's potentially unsafe, but not a problem here). Press y and everything should just work.


The command for this is

C-c C-e h h     (org-html-export-to-html)

Export as an HTML file. For an Org file myfile.org, the HTML file will be myfile.html. The file will be overwritten without warning. C-c C-e h o Export as an HTML file and immediately open it with a browser.

Reference


With Org-Mode 8.3 and Emacs 24.5.1 the accepted answer creates a pseudo-buffer *Org HTML Export* that you have to save manually, while the key C-c C-e h h more conveniently saves the file directly.

To really auto-export in the background try the following code:

# Local variables:
# eval: (add-hook 'after-save-hook 'org-html-export-to-html t t)
# end:

You can combine this solution with the following function in your .emacs:

(defun toggle-html-export-on-save ()
  "Enable or disable export HTML when saving current buffer."
  (interactive)
  (when (not (eq major-mode 'org-mode))
    (error "Not an org-mode file!"))
  (if (memq 'org-html-export-to-html after-save-hook)
      (progn (remove-hook 'after-save-hook 'org-html-export-to-html t)
             (message "Disabled org html export on save"))
    (add-hook 'after-save-hook 'org-html-export-to-html nil t)
    (set-buffer-modified-p t)
    (message "Enabled org html export on save")))

Tags:

Emacs

Org Mode