Syntax highlight Markdown formulas using LaTeX highlighting

I often write non-trivial mathematical formulas inside Markdown documents, and having them syntax-highlighted would really help.

In Markdown, LaTeX math formulae are denoted: $x^2$ and $$x^2$$, and are escaped as \$x\$and \$\$x\$\$.

Markdown math formulas are rendered via MathJax (to match future googlers' keywords).

If I use vim-markdown to syntax highlight the Markdown, how can I use vimtex to syntax highlight only the text inside the formulae?

Note: I only want the text inside $ to be treated differently if the filetype is markdown or foobar (future proofing against my lack of VimL). Bonus: I'd like the $ delimiters themselves to use the syntax highlight group Statement.

Hints:

I think these are along the right path, but I couldn't work out how the solution from them:

• Perhaps vim-SyntaxRange would help. (I couldn't work out how to set it up with the delimiters.)
• vim wikia's Different syntax highlighting within regions of a file
• " Block math. Look for "$$[anything]$$"
syn region math start=/\$\$/ end=/\$\$/
" Inline math. Look for "$[not$][anything]$" syn match math_block '\$[^$].\{-}\$'


I don't use vim-Markdown, but just by skimming over its readme, I found its syntax extension for LaTeX math

Used as $x^2$, $$x^2$$, escapable as \$x\$ and \$\$x\$\$.

let g:vim_markdown_math = 1


The plugin code uses :syntax include of the tex syntax, just like you also could do with my vim-SyntaxRange plugin.

• When using vim-markdown with g:vim_markdown_math = 1 I see the formula and fencing \$ as uncoloured. What do you see? – Tom Hale Jun 3 '18 at 9:06
• drmingdrmer/vim-syntax-markdown does highlight formulae for me, but is too simplistic, hence the question. – Tom Hale Jun 3 '18 at 9:07
• Note that you didn't address activation only if filetype is markdown or foobar. – Tom Hale Jun 3 '18 at 9:31
• As I don't use that plugin, I haven't tried anything. The SyntaxAttr.vim - Show syntax highlighting attributes of character under cursor plugin will help you with troubleshooting. As per my answer, this seems to be supported by vim-markdown, and its code looks fine to me, so it's likely a configuration error on your side. – Ingo Karkat Jun 3 '18 at 14:32
• For the activation: vim-markdown is a filetype plugin; it will activate for the markdown filetype by default. If you want this for a foobar filetype, too, you can either au BufRead,BufNewFile *.foobar setf markdown (just including additional patterns to markdown), or au FileType foobar runtime! ftplugin/markdown.vim ftplugin/markdown_*.vim ftplugin/markdown/*.vim (inheriting from the markdown filetype). All of this is common Vim filetype stuff, so I didn't include it in my answer. – Ingo Karkat Jun 3 '18 at 14:37