TikZ Images in org-latex-preview

2024/09/14

If you use LaTeX within org-mode you may come across a situation where you would like to embed TikZ diagrams and have Emacs preview them with org-latex-preview. Unfortunately Emacs does not handle this very well out of the box. The reason for this is not entirely clear to me. However, one reddit comment suggests this is because the default program used to generate LaTeX previews, dvipng, does not work well with TikZ. Fortunately, dvisvgm seems to handle TikZ more effectively. Once you have dvisvgm installed, adding the following snippet into your configuration file should get LaTeX previews working as expected.

(setq org-preview-latex-process-alist
      '((dvisvgm :programs ("latex" "dvisvgm")
                 :description "dvi > svg"
                 :message "you need to install the programs: latex and dvisvgm."
                 :image-input-type "dvi"
                 :image-output-type "svg"
                 :image-size-adjust (1.7 . 1.5)
                 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
                 :image-converter ("dvisvgm %f -n -b min -c %S --currentcolor -o %O"))))

(setq org-latex-packages-alist
      '(("" "tikz" t)
        ("" "tikz-cd" t)))

(setq org-latex-create-formula-image-program 'dvisvgm)

The image-size-adjust parameters in the snipper above work well for me, but feel free to adjust to your liking.

You can test whether the preview works now. If you need a sample TikZ snippet to try, here’s one you can use.

\begin{tikzcd}
F \arrow[r] & E \arrow[d, "\pi"] \\
            & M
\end{tikzcd}

Here’s a video showing how TikZ previews look both before and after adding the above snippet to your configuration.