Enable Code highlight and Math formulas For Markdown document

['latex'],['markdown'],['nodejs']

Enable code highlight and Math in Visual Studio Code

If you are using Visual Studio Code, it is easy to enable both code highlight and Math by installing one extension: Markdown all in one.

Initialize a new markdown document end with .md. To enable code highlight, surround code with ``` (straight single quote, usually under esc key). like this:

    ```python
    def func():
        print("hello python")
    ```

Check here to find all supported languages.

To enable inline math formulas written by LaTex, use $ to surround your LaTex marks. for example:

This inline $\sqrt{\frac{a}{b}}$ math 

This inline ab\sqrt{\frac{a}{b}} math

To display math formulas in blocks, use $ $ like this:

$
M=\begin{bmatrix} 
  1 & 2 & 1 \\ 
  3 & 0 & 1 \\ 
  0 & 2 & 4 
\end{bmatrix}
$
M=[121301024] M=\begin{bmatrix} 1 & 2 & 1 \\ 3 & 0 & 1 \\ 0 & 2 & 4 \end{bmatrix}

I found this page list lots of straightforward samples.

Enable code highlight and Math Equation in NodeJs

The code highlight feature is brought by highlight.js. and LaTex Math feature is brought by markdown-it-texmath. So, these two features can be also enabled in NodeJs code.

This is useful when you are trying to programmatically process your markdown documents and translate to HTML string and turn documents to web pages.

Install 3 required NodeJS packages.

Install package markdown-it. We can use this package to translate markdown document to HTML.

npm install markdown-it

Install package highlight.js. This package is required to enable the code highlight feature in markdown-it.

npm install highlight.js

Install package markdown-it-texmath. This package will do the LaTex translation work.

npm install markdown-it-texmath

Now, place the following code in the beginning of your NodeJS file.

const hljs = require('highlight.js'); // https://highlightjs.org/
const tm = require('markdown-it-texmath');
const md = require('markdown-it')(
    {
        highlight: function (str, lang) {
            if (lang && hljs.getLanguage(lang)) {
                try {
                    return hljs.highlight(lang, str).value;
                } catch (__) { }
            }
            return ''; // use external default escaping
        }
    }
).use(tm, {
        engine: require('katex'),
        delimiters: 'dollars',
        katexOptions: { macros: { "\\RR": "\\mathbb{R}" } }
    }
);

Next, load the markdown string, use md the markdown object handler to translate markdown to HTML.

var html_content = md.render(markdown_doc_string);

Done.