function removeMath(text, inline) {
function processMath(i, j) {
var block = blocks
.slice(i, j + 1)
.join("")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
if (indent) block = block.replace(/\n /g, "\n");
while (j > i) blocks[j--] = "";
blocks[i] = "@@" + math.length + "@@";
math.push(block);
start = end = last = null;
}
let start = null;
let end = null;
let last = null;
let indent = null; // for tracking math delimiters
let braces = null;
const math = []; // stores math strings for latter
let blocks = capturingStringSplit(text.replace(/\r\n?/g, "\n"), SPLIT);
for (var i = 1, m = blocks.length; i < m; i += 2) {
var block = blocks[i];
if (block.charAt(0) === "@") {
//
// Things that look like our math markers will get
// stored and then retrieved along with the math.
//
blocks[i] = "@@" + math.length + "@@";
math.push(block);
} else if (start) {
//
// If we are in math or backticks,
// look for the end delimiter,
// but don't go past double line breaks,
// and balance braces within the math,
// but don't process math inside backticks.
//
if (block === end) {
if (braces > 0) {
last = i;
} else if (braces === 0) {
processMath(start, i);
} else {
start = end = last = null;
}
} else if (block.match(/\n.*\n/) || i + 2 >= m) {
if (last) {
i = last;
if (braces >= 0) processMath(start, i);
}
start = end = last = null;
braces = 0;
} else if (block === "{" && braces >= 0) {
braces++;
} else if (block === "}" && braces > 0) {
braces--;
}
} else {
//
// Look for math start delimiters and when
// found, set up the end delimiter.
//
if (block === inline || block === "$$") {
start = i;
end = block;
braces = 0;
} else if (block.substr(1, 5) === "begin") {
start = i;
end = "\\end" + block.substr(6);
braces = 0;
} else if (block.charAt(0) === "`") {
start = last = i;
end = block;
braces = -1; // no brace balancing
} else if (block.charAt(0) === "\n") {
if (block.match(/ $/)) indent = true;
}
}
}
if (last) processMath(start, last);
// the commonmark renderer will render any `\$` as a simple `$`
// which could become a problem if `$` is used as a mathjax inline delimiter
// because then even escaped equations (starting with `\$`) would be detected
// as mathjax equations. Let's double-escape to make sure we still have a `\$`
// after commonmark did its conversion.
function doubleEscapeDelimiters(text, inline) {
if (!inline.startsWith("\\")) {
return text.replace(/\\\$/g, '\\\\$');
}
return text;
}
return { text: doubleEscapeDelimiters(blocks.join(""), inline), math };
}