On Mastodon I follow a number of folks at the Mathstodon instance. Because that instance is about mathematics, they’ve enabled the rendering of LaTeX formulae in their web interface.

However, since I am not on that particular instance, all the toots with equations show up as ugly LaTeX when I view them. There is no plan to enable MathJax on most instances, as it’s a significant payload for every user, and a tiny percentage of toots have LaTeX embedded in them.

I went searching for a way to locally inject MathJax in the page via some sort of addon, but then decided to explore mastodon.el instead. Within an hour I had whipped a function that does what I need:

Screenshot of a toot with equations rendered.

The code is below:

(defun mn:preview-latex-toot (&optional arg)
  "Toggle preview of the LaTeX fragments in Mastodon toots.

If the cursor is on a Mastodon toot, create the image and
overlay it over the source code.

With a `\\[universal-argument]' prefix argument ARG, display
image for all toots in the buffer.

With a `\\[universal-argument] \\[universal-argument]' prefix
argument ARG, clear images for the current toot.

With a `\\[universal-argument] \\[universal-argument] \
\\[universal-argument]' prefix argument ARG, clear images for the
whole buffer."
  (interactive "P")
  (let ((toot-begin (previous-single-property-change
             (point)
             'byline
             (current-buffer)))
    (toot-end (next-single-property-change
           (point)
           'byline
           (current-buffer))))
    (cond
     ((not (display-graphic-p)) nil)
     ;; Clear whole buffer.
     ((equal arg '(64))
      (org-clear-latex-preview (point-min) (point-max))
      (message "LaTeX previews removed from buffer"))
     ;; Clear current toot.
     ((equal arg '(16))
      (org-clear-latex-preview toot-begin toot-end))
     ;; Preview whole buffer.
     ((equal arg '(4))
      (message "Creating LaTeX previews in buffer...")
      (org--latex-preview-region (point-min) (point-max))
      (message "Creating LaTeX previews in buffer... done."))
     ((org--latex-preview-region toot-begin toot-end)))))

(define-key mastodon-mode-map (kbd "C-c C-x C-l") #'mn:preview-latex-toot)

If you press C-c C-x C-l on a toot, it will render the equations in that toot.

With a C-u prefix, it will render it in the whole buffer.

With a C-u C-u prefix, it will clear it in the toot.

With a C-u C-u C-u prefix, it will clear it in the whole buffer.

Much of the code was taken from org-latex-preview.