Ajouter Katex à MkDocs
Le code
=== "docs/javascripts/katex.js"
```js title="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"
```yaml title="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
=== "katex.js"
```js title="docs/javascripts/katex.js" hl_lines="3 4 5 6"
(function () {
'use strict';
const macros = {
"\\RR": "\\mathbb{R}",
"\\vect": "{\\begin{pmatrix}#1\\\\#2\\end{pmatrix}}"
};
...
```
=== "Markdown"
```latex
Vectors in $\RR^2$ have a shape of
$$\vect{x}{y}$$
```
=== "Rendu"
Vectors in $\RR^2$ have a shape of
$$\vect{x}{y}$$