From 7250ec6ffb91ff2da46bde731f8af936651ec685 Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Thu, 20 Feb 2025 12:14:54 +0100 Subject: [PATCH] Add catching of mathjax exceptions Closes GH-112. --- packages/rehype-mathjax/lib/create-plugin.js | 36 ++++++++++++++++++-- packages/rehype-mathjax/package.json | 3 +- packages/rehype-mathjax/test/index.js | 19 +++++++++++ 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/packages/rehype-mathjax/lib/create-plugin.js b/packages/rehype-mathjax/lib/create-plugin.js index 2feacbe..d3702ed 100644 --- a/packages/rehype-mathjax/lib/create-plugin.js +++ b/packages/rehype-mathjax/lib/create-plugin.js @@ -1,5 +1,6 @@ /** * @import {ElementContent, Element, Root} from 'hast' + * @import {VFile} from 'vfile' */ /** @@ -210,10 +211,12 @@ export function createPlugin(createRenderer) { * * @param {Root} tree * Tree. + * @param {VFile} file + * File. * @returns {undefined} * Nothing. */ - return function (tree) { + return function (tree, file) { const renderer = createRenderer(options || emptyOptions) let found = false /** @type {Element | Root} */ @@ -265,11 +268,38 @@ export function createPlugin(createRenderer) { found = true const text = toText(scope, {whitespace: 'pre'}) - const result = renderer.render(text, {display}) + /** @type {Array | undefined} */ + let result + + try { + result = renderer.render(text, {display}) + } catch (error) { + const cause = /** @type {Error} */ (error) + + file.message('Could not render math with mathjax', { + ancestors: [...parents, element], + cause, + place: element.position, + ruleId: 'mathjax-error', + source: 'rehype-mathjax' + }) + + result = [ + { + type: 'element', + tagName: 'span', + properties: { + className: ['mathjax-error'], + style: 'color:#cc0000', + title: String(cause) + }, + children: [{type: 'text', value: text}] + } + ] + } const index = parent.children.indexOf(scope) parent.children.splice(index, 1, ...result) - return SKIP }) diff --git a/packages/rehype-mathjax/package.json b/packages/rehype-mathjax/package.json index 4f34c5b..6bd2530 100644 --- a/packages/rehype-mathjax/package.json +++ b/packages/rehype-mathjax/package.json @@ -12,7 +12,8 @@ "hastscript": "^9.0.0", "mathjax-full": "^3.0.0", "unified": "^11.0.0", - "unist-util-visit-parents": "^6.0.0" + "unist-util-visit-parents": "^6.0.0", + "vfile": "^6.0.0" }, "description": "rehype plugin to transform inline and block math with MathJax", "exports": { diff --git a/packages/rehype-mathjax/test/index.js b/packages/rehype-mathjax/test/index.js index d8cc09a..b0cefe7 100644 --- a/packages/rehype-mathjax/test/index.js +++ b/packages/rehype-mathjax/test/index.js @@ -261,4 +261,23 @@ test('rehype-mathjax', async function (t) { ).trim() ) }) + + await t.test('should catch mathjax exceptions', async function () { + const file = await unified() + .use(rehypeParse, {fragment: true}) + .use(rehypeMathJaxSvg) + .use(rehypeStringify) + .process('\\a{₹}.') + + const value = String(file).replace(/