Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(web): normalize malformed ATX headings safely

Iams4kura85485a0f7608
diff --git a/web/lib/latex.ts b/web/lib/latex.ts
index b9b6a5461..19e48f054 100644
--- a/web/lib/latex.ts
+++ b/web/lib/latex.ts
@@ -6,6 +6,8 @@
* This utility converts between formats.
*/
+import { normalizeAtxHeadings } from "./markdown-display";
+
// A single-dollar math span must be tight at both ends. This mirrors the
// delimiter rule used by remark-math and avoids treating ordinary prices such
// as "$5 and $10" as one formula. The body accepts escaped characters so an
@@ -75,10 +77,6 @@ export function convertLatexDelimiters(content: string): string {
return result;
}
-function normalizeEditorMdHeadings(content: string): string {
- return content.replace(/^(#{1,6})([^#\s])/gm, "$1 $2");
-}
-
const LIKELY_LATEX_BLOCK_RE = /\\[A-Za-z]+|\\\\|[_^&]/;
function looksLikeLatexBlock(lines: string[]): boolean {
@@ -390,7 +388,7 @@ export function processMarkdownContent(content: string): string {
if (!content) return "";
let result = String(content);
- result = normalizeEditorMdHeadings(result);
+ result = normalizeAtxHeadings(result);
result = normalizeEditorMdInlineMath(result);
result = convertEditorMdFences(result);
result = injectEditorMdTableOfContents(result);
diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.ts
index 17dacb327..4d723c3cc 100644
--- a/web/lib/markdown-display.ts
+++ b/web/lib/markdown-display.ts
@@ -154,6 +154,15 @@ const MALFORMED_STRONG_EMPHASIS_REGEX =
/(?<!\S)\*\*(?=\S)([^*\n]*?[::])[ \t]+\*\*(?=\S)/g;
const ESCAPED_UNICODE_RUN_REGEX = /(?:\\u[0-9a-fA-F]{4}){3,}/g;
const INDENTED_CODE_LINE_REGEX = /^(?: {4}|\t)/;
+const FENCE_LINE_REGEX = /^ {0,3}(`{3,}|~{3,})(.*)$/;
+const MALFORMED_ATX_HEADING_REGEX = /^(#{1,6})([^#\s])/;
+const RAW_HTML_CODE_BLOCK_OPEN_REGEX = /^ {0,3}<(pre|code)(?=[\s/>]|$)/i;
+const RAW_HTML_CODE_SELF_CLOSING_REGEX =
+ /^ {0,3}<(?:pre|code)(?=[\s/>]|$)[^>]*\/\s*>/i;
+const RAW_HTML_CODE_BLOCK_CLOSE_REGEX = {
+ pre: /<\/pre\s*>/i,
+ code: /<\/code\s*>/i,
+} as const;
const PROTECTED_SPAN_REGEX = /```[\s\S]*?```|`[^`\n]*`/g;
const PROTECTED_PLACEHOLDER_REGEX = /\u0000PROTECTED_(\d+)\u0000/g;
const HTML_ATTR_VALUE = /(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+)/.source;
@@ -891,11 +900,67 @@ function decodeEscapedUnicodeRun(escaped: string): string {
}
}
+/** Insert a separator after column-zero ATX hashes outside code blocks. */
+export function normalizeAtxHeadings(content: string): string {
+ let fenceMarker = "";
+ let fenceLength = 0;
+ let htmlCodeTag: keyof typeof RAW_HTML_CODE_BLOCK_CLOSE_REGEX | "" = "";
+
+ return content
+ .split("\n")
+ .map((line) => {
+ const fence = FENCE_LINE_REGEX.exec(line);
+
+ if (fenceMarker) {
+ if (
+ fence &&
+ fence[1][0] === fenceMarker &&
+ fence[1].length >= fenceLength &&
+ fence[2].trim() === ""
+ ) {
+ fenceMarker = "";
+ fenceLength = 0;
+ }
+ return line;
+ }
+
+ if (htmlCodeTag) {
+ if (RAW_HTML_CODE_BLOCK_CLOSE_REGEX[htmlCodeTag].test(line)) {
+ htmlCodeTag = "";
+ }
+ return line;
+ }
+
+ if (fence) {
+ fenceMarker = fence[1][0];
+ fenceLength = fence[1].length;
+ return line;
+ }
+
+ const htmlCodeBlock = RAW_HTML_CODE_BLOCK_OPEN_REGEX.exec(line);
+ if (htmlCodeBlock) {
+ const tag = htmlCodeBlock[1].toLowerCase() as "pre" | "code";
+ if (
+ !RAW_HTML_CODE_SELF_CLOSING_REGEX.test(line) &&
+ !RAW_HTML_CODE_BLOCK_CLOSE_REGEX[tag].test(line)
+ ) {
+ htmlCodeTag = tag;
+ }
+ return line;
+ }
+
+ return line.replace(MALFORMED_ATX_HEADING_REGEX, "$1 $2");
+ })
+ .join("\n");
+}
+
export function normalizeMarkdownForDisplay(content: string): string {
if (!content) return "";
const normalized = stripInvisibleCharacters(
- decodeEscapedUnicodeRuns(String(content).replace(/\r\n/g, "\n")),
+ normalizeAtxHeadings(
+ decodeEscapedUnicodeRuns(String(content).replace(/\r\n/g, "\n")),
+ ),
)
.replace(EMPTY_DETAILS_REGEX, "")
.replace(EMPTY_SUMMARY_REGEX, "")
diff --git a/web/tests/latex.test.ts b/web/tests/latex.test.ts
index fef53b51a..0014f10c4 100644
--- a/web/tests/latex.test.ts
+++ b/web/tests/latex.test.ts
@@ -110,6 +110,34 @@ test("headings: does not split 7+ consecutive hashes", () => {
assert.equal(result.trim(), "#######");
});
+test("headings: leaves heading-like fenced code verbatim", () => {
+ const input = [
+ "```c",
+ "##define FEATURE",
+ "```",
+ "",
+ "~~~text",
+ "###literal",
+ "~~~",
+ ].join("\n");
+
+ assert.equal(processMarkdownContent(input), input);
+});
+
+test("headings: leaves raw HTML code blocks verbatim", () => {
+ const input = [
+ "<pre>",
+ "###literal",
+ "</pre>",
+ "",
+ "<code>",
+ "##define FEATURE",
+ "</code>",
+ ].join("\n");
+
+ assert.equal(processMarkdownContent(input), input);
+});
+
// ---------------------------------------------------------------------------
// processMarkdownContent — inline math normalisation ($$...$$ → $...$)
// ---------------------------------------------------------------------------
diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.ts
index 5789483b7..c459987c1 100644
--- a/web/tests/markdown-display.test.ts
+++ b/web/tests/markdown-display.test.ts
@@ -145,6 +145,72 @@ test("normalizeMarkdownForDisplay removes empty details blocks", () => {
assert.equal(normalizeMarkdownForDisplay(input), "Before\n\nAfter");
});
+test("normalizeMarkdownForDisplay repairs missing ATX heading separators", () => {
+ const input = ["##Title", "###第一部分", "# Already spaced", "#######"].join(
+ "\n",
+ );
+ const expected = [
+ "## Title",
+ "### 第一部分",
+ "# Already spaced",
+ "#######",
+ ].join("\n");
+
+ assert.equal(normalizeMarkdownForDisplay(input), expected);
+ assert.equal(normalizeMarkdownForDisplay(expected), expected);
+});
+
+test("normalizeMarkdownForDisplay leaves heading-like fenced code verbatim", () => {
+ const input = [
+ "```c",
+ "##define FEATURE",
+ "```",
+ "",
+ "~~~text",
+ "###literal",
+ "~~~",
+ "",
+ "```python",
+ "##unfinished",
+ ].join("\n");
+
+ assert.equal(normalizeMarkdownForDisplay(input), input);
+});
+
+test("normalizeMarkdownForDisplay leaves raw HTML code blocks verbatim", () => {
+ const input = [
+ "<pre",
+ ' class="example">',
+ "###literal",
+ "</pre>",
+ "",
+ "<code>",
+ "##define FEATURE",
+ "</code>",
+ "",
+ "###Heading",
+ ].join("\n");
+ const expected = input.replace("###Heading", "### Heading");
+
+ assert.equal(normalizeMarkdownForDisplay(input), expected);
+});
+
+test("normalizeMarkdownForDisplay does not mistake code-like prose for HTML blocks", () => {
+ const inputs = [
+ "`<pre>`\n###Heading",
+ String.raw`\<pre>` + "\n###Heading",
+ "<!-- example: <pre> -->\n###Heading",
+ "<[email protected]>\n###Heading",
+ ];
+
+ for (const input of inputs) {
+ assert.equal(
+ normalizeMarkdownForDisplay(input),
+ input.replace("###Heading", "### Heading"),
+ );
+ }
+});
+
test("normalizeMarkdownForDisplay decodes dense non-ASCII JSON escapes", () => {
const input = "\\u300c\\u6570\\u5236\\u8f6c\\u6362\\u300d";
assert.equal(normalizeMarkdownForDisplay(input), "「数制转换」");