Search code examples
javascriptkatex

How can I render all inline formulas in $..$ with KaTeX?


So I want to have KaTeX inline formulas like with MathJax.
But so far I've found only render() function which "draws" a string to an element.
And I need to modify a part of a text node in DOM.
I really couldn't find how to do this with KaTeX. Does it have such functionality?
MathJax could do this.


Solution

  • Yes, you can render all $-delimited formulas inline using KaTeX's auto-render extension. Per the documentation on that page, $ is not one of the default delimiters so you'll need to set it when you call renderMathInElement() and set display to false, which renders inline. Below is one example and another from KaTeX can be found here.

    Note that \\ in the JavaScript corresponds to \ in the HTML.

    <!doctype html>
    <html>
    <head>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/contrib/auto-render.min.js"></script>
    </head>
    <body>
        <div>The formula $a^2+b^2=c^2$ will be rendered inline, but $$a^2+b^2=c^2$$ will be rendered as a block element.</div>
        <br>
        <div>The formula \(a^2+b^2=c^2\) will be rendered inline, but \[a^2+b^2=c^2\] will be rendered as a block element.</div>
        <script>
          renderMathInElement(
              document.body,
              {
                  delimiters: [
                      {left: "$$", right: "$$", display: true},
                      {left: "\\[", right: "\\]", display: true},
                      {left: "$", right: "$", display: false},
                      {left: "\\(", right: "\\)", display: false}
                  ]
              }
          );
        </script>
    </body>
    </html>