From 73130cad02b2e63b4941d12a47ccc92f696d003c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sven=20M=C3=A4der?= Date: Thu, 1 Apr 2021 12:09:51 +0200 Subject: [PATCH] Refactor latex replace code --- src/editor/serialize.ts | 97 +++++++++++++++++++++-------------------- 1 file changed, 49 insertions(+), 48 deletions(-) diff --git a/src/editor/serialize.ts b/src/editor/serialize.ts index 6655c64347..3eda28818a 100644 --- a/src/editor/serialize.ts +++ b/src/editor/serialize.ts @@ -47,60 +47,61 @@ export function htmlSerializeIfNeeded(model: EditorModel, {forceHTML = false} = const orig = md; if (SettingsStore.getValue("feature_latex_maths")) { - // detect math with tex delimiters, inline: $...$, display $$...$$ - // preferably use negative lookbehinds, not supported in all major browsers: - // const displayPattern = "^(?\n\n\n\n`; - }); + // conditions for display math detection \[...\]: + // - pattern starts at beginning of line or is not prefixed with backslash + // - pattern is not empty + "display": "(^|[^\\\\])\\\\\\[(?!\\\\\\])(.*?)\\\\\\]", - md = md.replace(RegExp(inlinePatternAlternative, "gm"), function(m, p1, p2) { - const p2e = AllHtmlEntities.encode(p2); - return `${p1}`; - }); + // conditions for inline math detection \(...\): + // - pattern starts at beginning of line or is not prefixed with backslash + // - pattern is not empty + "inline": "(^|[^\\\\])\\\\\\((?!\\\\\\))(.*?)\\\\\\)", + }, + }; - // detect math with latex delimiters, inline: \(...\), display \[...\] + patternNames.forEach(function(patternName) { + patternTypes.forEach(function(patternType) { + // get the regex replace pattern from config or use the default + const pattern = (SdkConfig.get()["latex_maths_delims"] || + {})[patternType + "_pattern_" + patternName] || + patternDefaults[patternName][patternType]; - // conditions for display math detection \[...\]: - // - pattern starts at beginning of line or is not prefixed with backslash - // - pattern is not empty - const displayPattern = (SdkConfig.get()['latex_maths_delims'] || {})['display_pattern'] || - "(^|[^\\\\])\\\\\\[(?!\\\\\\])(.*?)\\\\\\]"; - - // conditions for inline math detection \(...\): - // - pattern starts at beginning of line or is not prefixed with backslash - // - pattern is not empty - const inlinePattern = (SdkConfig.get()['latex_maths_delims'] || {})['inline_pattern'] || - "(^|[^\\\\])\\\\\\((?!\\\\\\))(.*?)\\\\\\)"; - - md = md.replace(RegExp(displayPattern, "gms"), function(m, p1, p2) { - const p2e = AllHtmlEntities.encode(p2); - return `${p1}
\n\n
\n\n`; - }); - - md = md.replace(RegExp(inlinePattern, "gms"), function(m, p1, p2) { - const p2e = AllHtmlEntities.encode(p2); - return `${p1}`; + md = md.replace(RegExp(pattern, "gms"), function(m, p1, p2) { + const p2e = AllHtmlEntities.encode(p2); + switch (patternType) { + case "display": + return `${p1}
\n\n
\n\n`; + case "inline": + return `${p1}`; + } + }); + }); }); // make sure div tags always start on a new line, otherwise it will confuse