保存时如何将org文件导出到HTML文件?

How to export org file to HTML file when save?

我想在保存时将我的 org 文件导出到 HTML 文件到特定目录。 我可以使用 Emacs 和 Org-mode,但我不会 Elisp。

这个命令是

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

导出为 HTML 文件。对于 Org 文件 myfile.org,HTML 文件将是 myfile.html。该文件将在没有警告的情况下被覆盖。 C-c C-e h o 导出为 HTML 文件并立即用浏览器打开。

Reference

注意:下面是为 Emacs 23 编写的。查看@AndreasSpindler 的答案以获得最新的解决方案。

Emacs 有几个 hooks 在某些事件中调用。您正在寻找的钩子可能是 after-save-hook。每次保存文件时,只需将其设置为您想要 运行 的功能即可。在您的情况下,这将是 org-html-export-to-html.

有很多方法可以做到这一点,但以下方法可能是最快的并且不涉及任何 "real" elisp。将以下几行放在您的组织文件中的某处:

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

下次打开该文件时,您会收到警告并询问是否应设置局部变量(因为这可能不安全,但这不是问题)。按 y 一切正常。

对于 Org-Mode 8.3 和 Emacs 24.5.1,接受的答案会创建一个伪缓冲区 *Org HTML Export*,您必须手动保存它,而键 C-c C-e h h 更方便地直接保存文件。

要真正在后台自动导出,请尝试以下代码:

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

您可以将此解决方案与 .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")))