CSS solution to handle LaTeX macro definitions

Use case and problem

Sometimes it is necessary to put some LaTeX macro definitions in a Markdown file, like here:

# Error function

$$
\newcommand{\dd}{\operatorname{d}}
\newcommand{\erf}{\operatorname{erf}}
$$

In mathematics, the error function, often denoted by **erf**, is a complex function of a complex variable defined as:

$$ \erf{z} = \frac{2}{\sqrt{\pi}} \int_0^z \exp(-t^2) \dd t $$

The problem is that in the live preview view all LaTeX math commands with no visible output, like the macro definitions above, produce just empty space giving the user no cue what is there until he/she places the cursor on the empty region:

Here the same in the reading view — also too much space between the heading and the text:

Solution

The following CSS snippet should solve the problem:

.cm-s-obsidian mjx-math:empty::after {
    content: "LaTeX math";
    font-family: var(--default-font);
    color: var(--text-faint);
}

.markdown-rendered mjx-math:empty {
    display: none;
}

In the live preview view it marks the empty math regions with “LaTeX math” unless the cursor is in them:

In the reading view it disables them completely:

I hope someone will find this solution useful.

P.S: You will possibly need to adapt this snippet to work with Obsidian v0.16 new CSS. I tested it only for v0.15.9.

P.P.S. I am aware of the obsidian-latex plugin, but sometimes need to put some specific macro definitions directly in a Markdown file.

Just today I was looking for something like this and suddenly I found your post.

Have you thought about making a plug-in? I have made a very simple one and it works perfectly.

If you want I explain you how, so the author of the plug-in is you. I followed this video, where a guy explains how to modify the plug-in to change the letters to red, I just added your code there.