diff --git a/ts/editable/mathjax-element.ts b/ts/editable/mathjax-element.ts index 5f17c1f3c..247ccb458 100644 --- a/ts/editable/mathjax-element.ts +++ b/ts/editable/mathjax-element.ts @@ -13,6 +13,13 @@ const mathjaxTagPattern = const mathjaxBlockDelimiterPattern = /\\\[(.*?)\\\]/gsu; const mathjaxInlineDelimiterPattern = /\\\((.*?)\\\)/gsu; +function trimBreaks(text: string): string { + return text + .replace(//gsu, "\n") + .replace(/^\n*/, "") + .replace(/\n*$/, ""); +} + export const Mathjax: DecoratedElementConstructor = class Mathjax extends HTMLElement implements DecoratedElement @@ -23,9 +30,10 @@ export const Mathjax: DecoratedElementConstructor = class Mathjax const stored = undecorated.replace( mathjaxTagPattern, (_match: string, block: string | undefined, text: string) => { + const trimmed = trimBreaks(text); return typeof block === "string" && block !== "false" - ? `\\[${text}\\]` - : `\\(${text}\\)`; + ? `\\[${trimmed}\\]` + : `\\(${trimmed}\\)`; }, ); @@ -35,10 +43,12 @@ export const Mathjax: DecoratedElementConstructor = class Mathjax static toUndecorated(stored: string): string { return stored .replace(mathjaxBlockDelimiterPattern, (_match: string, text: string) => { - return `<${Mathjax.tagName} block="true">${text}`; + const trimmed = trimBreaks(text); + return `<${Mathjax.tagName} block="true">${trimmed}`; }) .replace(mathjaxInlineDelimiterPattern, (_match: string, text: string) => { - return `<${Mathjax.tagName}>${text}`; + const trimmed = trimBreaks(text); + return `<${Mathjax.tagName}>${trimmed}`; }); }