Search code examples
next.jstailwind-cssmarkdoc

Is it possible to write math formula using markdoc?


I'm using the tailwind syntax template to take class notes and need to write math formula such as y_i = e(x_i) ≡ x_i + s_i mod 2 with y_i meaning y subscript i.

Regular markdown enclose math formula with $, it does not work for markdoc (I've tried enclosing it with $$ and that does not work either).

markdoc is used throughout the site to generate table of contents and such, so I can't use another markdown package.

Have any of you find a way to write math formula using markdoc ?


Solution

  • I've found a way to display math formula using the tailwind syntax template:

    1. Install the following packages: react-markdown, rehype-katex, remark-math
    2. In src/components, create a file MathFormula (or whatever suits you) with the following code:
    import 'katex/dist/katex.min.css'
    
    import Markdown from 'react-markdown'
    import rehypeKatex from 'rehype-katex'
    import remarkMath from 'remark-math'
    
    export function MathFormula({ formula }: { formula: string }) {
      return (
        <Markdown remarkPlugins={[remarkMath]} rehypePlugins={[rehypeKatex]}>
          {formula}
        </Markdown>
      )
    }
    
    
    1. Add the following entry in src/markdoc/tags.js:
    mathFormula: {
      attributes: {
        formula: { type: String },
      },
      render: MathFormula,
    },
    
    1. In you md file, you can now use: {% mathFormula formula="$d_k(y) = x ≡ a^1 * (y - b) mod 26$" /%}

    The formula will be properly displayed