Skip to content

Instantly share code, notes, and snippets.

@mattvague
Last active April 9, 2022 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattvague/961ad897f2e6b9777668abe43bca4a45 to your computer and use it in GitHub Desktop.
Save mattvague/961ad897f2e6b9777668abe43bca4a45 to your computer and use it in GitHub Desktop.
/**
* @typedef {import('mdast').Root} Root
* @typedef {import('mdast-util-math')} DoNotTouchAsThisImportIncludesMathInTree
* @typedef Options
* @property {string} [startDelimiter=string]
* @property {string} [endDelimiter=string]
*/
import {visit, CONTINUE} from 'unist-util-visit'
import * as acorn from 'acorn'
/**
* WIP!!!
* Plugin to support parsing JS expressions in math (for use in MDX)
* e.g.
* ```
* export const myVar = "x"
* $$
* What is the derivative of $f(\eval{myVar}) = \eval{myVar}^2 + \eval{1 + 2 + 3}$?
* $$
* ```
*
* @type {import('unified').Plugin<[Options?] | void[], Root, Root>}
*/
export default function casPlugin(options = {}) {
return (tree) => {
visit(tree, "math", (node, index, parent) => {
const expression = `String.raw\`${node.value}\``
const estree = acorn.parse(expression, { ecmaVersion: 2020 })
parent.children.splice(index, 1, {
type: 'mdxJsxFlowElement',
name: 'Katex',
attributes: [],
children: [{
type: 'mdxTextExpression',
value: expression,
data: {
estree
}
}]
})
return [CONTINUE, index]
});
visit(tree, "inlineMath", (node, index, parent) => {
const expression = `String.raw\`${node.value}\``
const estree = acorn.parse(expression, { ecmaVersion: 2020 })
parent.children.splice(index, 1, {
type: 'mdxJsxTextElement',
name: 'Katex',
children: [{
type: 'mdxTextExpression',
value: expression,
data: {
estree
}
}]
})
return [CONTINUE, index]
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment