# How can I export to LaTeX every time I save an Org mode buffer?

I'm trying to set up a buffer-local behavior so that optionally, only after I execute the babel section, Org exports to LaTeX asynchronously after each save. I tried the following:

(defun kdm/org-save-and-export ()
(interactive)
(org-latex-export-to-latex t))



But it creates file.tex.tex.tex.tex indefinitely. How do I modify this to only save 1x, and be a buffer-local change?

Probably, Emacs is creating a file.tex buffer and then saving it, triggering the after-save-hook again indefinitely. Try checking major-mode before calling the export function:

(defun kdm/org-save-and-export ()
(interactive)
(if (eq major-mode 'org-mode)
(org-latex-export-to-latex)))


• Thanks. Works, although the async doesn't seem to work, so I removed t from org-latex-export-to-latex. – mankoff Mar 8 '15 at 14:52
• I edited your answer to make the hook buffer-local. – mankoff Mar 8 '15 at 15:47
• I tried the above solution, it didn't take any effect, no export taking place. – Yu Shen Aug 30 '17 at 18:06

I made a little edit since it was a pain to have every org file i saved be exported to latex. This way it exports every time is saved with the condition it was exported manually at least once, this also works for other file extensions if you edit the ".tex" part

(defun kdm/org-save-and-export ()
(interactive)
(if (and (eq major-mode 'org-mode)
(ido-local-file-exists-p (concat (file-name-sans-extension (buffer-name)) ".tex")))
(org-latex-export-to-pdf)))