Calling org-preview-latex-fragment blocks user input for a second or two depending on the size of your fragment, and with universal args, converting all fragments in buffer can take minutes. It would be nice to have this be async, so I could continue to type while the conversion happens. I was pointed toward this package, but my elisp-fu is not up to par. What would it take to make this function work asynchronously?

(defun org-preview-latex-fragment (&optional subtree)
  "Preview the LaTeX fragment at point, or all locally or globally.
If the cursor is in a LaTeX fragment, create the image and overlay
it over the source code.  If there is no fragment at point, display
all fragments in the current text, from one headline to the next.  With
prefix SUBTREE, display all fragments in the current subtree.  With a
double prefix arg \\[universal-argument] \\[universal-argument], or when \
the cursor is before the first headline,
display all fragments in the buffer.
The images can be removed again with \\[org-ctrl-c-ctrl-c]."
  (interactive "P")
  (unless buffer-file-name
    (user-error "Can't preview LaTeX fragment in a non-file buffer"))
  (when (display-graphic-p)
        (let (beg end at msg)
           ((or (equal subtree '(16))
                (not (save-excursion
                       (re-search-backward org-outline-regexp-bol nil t))))
            (setq beg (point-min) end (point-max)
                  msg "Creating images for buffer...%s"))
           ((equal subtree '(4))
            (setq beg (point) end (org-end-of-subtree t)
                  msg "Creating images for subtree...%s"))
            (if (setq at (org-inside-LaTeX-fragment-p))
                (goto-char (max (point-min) (- (cdr at) 2)))
            (setq beg (point) end (progn (outline-next-heading) (point))
                  msg (if at "Creating image...%s"
                        "Creating images for entry...%s"))))
          (message msg "")
          (narrow-to-region beg end)
          (goto-char beg)
           (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
           default-directory 'overlays msg at 'forbuffer
          (message msg "done.  Use `C-c C-c' to remove images."))))))
  • Did you figure out a solution to this issue? Sep 17, 2019 at 20:35
  • I know this is a very old question, but this along many other improvements are coming to Org 9.7, expected to release in Q3 2023: youtube.com/watch?v=n-AfvuV-bYo
    – tralph3
    May 16 at 23:20


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.