5

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)
    (org-remove-latex-fragment-image-overlays)
    (save-excursion
      (save-restriction
        (let (beg end at msg)
          (cond
           ((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))
            (org-back-to-heading)
            (setq beg (point) end (org-end-of-subtree t)
                  msg "Creating images for subtree...%s"))
           (t
            (if (setq at (org-inside-LaTeX-fragment-p))
                (goto-char (max (point-min) (- (cdr at) 2)))
              (org-back-to-heading))
            (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)
          (org-format-latex
           (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
                                                       (file-name-nondirectory
                                                        buffer-file-name)))
           default-directory 'overlays msg at 'forbuffer
           org-latex-create-formula-image-program)
          (message msg "done.  Use `C-c C-c' to remove images."))))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.