Aller au contenu

Ajouter Katex à MkDocs

Le code

docs/javascripts/katex.js
;(() => {
  'use strict'

  // macros personnalisées
  const macros = {
    '\\RR': '\\mathbb{R}',
    '\\vect': '{\\begin{pmatrix}#1\\\\#2\\end{pmatrix}}',
  }

  // rendu katex
  function katexMath() {
    let maths = document.querySelectorAll('.arithmatex'),
      tex

    for (let i = 0; i < maths.length; i++) {
      tex = maths[i].textContent || maths[i].innerText
      if (tex.startsWith('\\(') && tex.endsWith('\\)')) {
        katex.render(tex.slice(2, -2), maths[i], {
          displayMode: false,
          macros,
          throwOnError: false,
        })
      } else if (tex.startsWith('\\[') && tex.endsWith('\\]')) {
        katex.render(tex.slice(2, -2), maths[i], {
          displayMode: true,
          macros,
          throwOnError: false,
        })
      }
    }
  }
  ;(() => {
    function onReady(fn) {
      if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', fn)
      } else {
        document.attachEvent('onreadystatechange', function () {
          if (document.readyState === 'interactive') {
            fn()
          }
        })
      }
    }

    onReady(() => {
      if (typeof katex !== 'undefined') {
        katexMath()
      }
    })
  })()
})()
mkdocs.yml
extra_javascript:
    - javascripts/katex.js
    - https://cdn.jsdelivr.net/npm/katex@0.16.3/dist/katex.min.js

extra_css:
    - stylesheets/extra.css
    - https://cdn.jsdelivr.net/npm/katex@0.16.3/dist/katex.min.css

Usage et personnalisation

Ajout de macros

On peut parfaitement ajouter des macros personnalisées, comme avec \newcommand

docs/javascripts/katex.js
(function () {
    'use strict';
    const macros = {
        "\\RR": "\\mathbb{R}",
        "\\vect": "{\\begin{pmatrix}#1\\\\#2\\end{pmatrix}}"
    };
...
Vectors in $\RR^2$ have a shape of

$$\vect{x}{y}$$

Vectors in \(\RR^2\) have a shape of

\[\vect{x}{y}\]

Dernière mise à jour: January 24, 2023
Créé: January 24, 2023