Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8573 fix(editor): preserve nested fences through Markdown saves (#9902)

Jiahaoddaaf6a7684c
diff --git a/packages/ui/markdown/linkify.test.ts b/packages/ui/markdown/linkify.test.ts
new file mode 100644
index 0000000000..cc68f9b85f
--- /dev/null
+++ b/packages/ui/markdown/linkify.test.ts
@@ -0,0 +1,170 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest'
+import { performance } from 'node:perf_hooks'
+import { findCodeRanges, findBlockCodeRanges, preprocessLinks } from './linkify'
+
+describe('fenced code boundaries used by preprocessing and chunked loading', () => {
+ it.each([
+ ['````markdown', '```'],
+ ['````markdown', '~~~'],
+ ['````markdown', '````javascript'],
+ ['```markdown', '- ```'],
+ ['```markdown', '> ```'],
+ ['~~~text', '```'],
+ ['~~~~text', '~~~'],
+ ['``````javascript', "const ticks = '`````';"],
+ ])('keeps %s open across a literal %s line', (opening, inner) => {
+ const closing = opening.match(/^[`~]+/)![0]
+ const block = `${opening}\n${inner}\nhttps://example.com\n${closing}`
+ const source = `Intro\n\n${block}\n\nhttps://outside.example`
+ expect(findBlockCodeRanges(source)).toEqual([
+ { start: 7, end: 7 + block.length },
+ ])
+ expect(preprocessLinks(source)).toBe(
+ `Intro\n\n${block}\n\n[https://outside.example](https://outside.example)`,
+ )
+ })
+
+ it('protects unclosed fences through the end of the input', () => {
+ const source = 'Intro\n\n````\n```\nhttps://example.com'
+ expect(findBlockCodeRanges(source)).toEqual([{ start: 7, end: source.length }])
+ expect(preprocessLinks(source)).toBe(source)
+ })
+
+ it.each([
+ ['a quote at a blank line', '> ```\n> https://inside.example', '\n\n'],
+ ['a quote at a line without >', '> ```\n> https://inside.example', '\n'],
+ ['a list item at a blank line', '- ```\n https://inside.example', '\n\n'],
+ ['a list item at an unindented line', '- ```\n https://inside.example', '\n'],
+ ['a list nested in a quote', '> - ```\n> https://inside.example', '\n> '],
+ ])('ends an unclosed fence with %s', (_, code, separator) => {
+ const source = `${code}${separator}https://outside.example`
+ const [range, ...rest] = findBlockCodeRanges(source)
+ expect(rest).toEqual([])
+ expect(range!.start).toBe(0)
+ expect(range!.end).toBeGreaterThanOrEqual(code.length)
+ expect(range!.end).toBeLessThan(source.indexOf('https://outside.example'))
+ expect(preprocessLinks(source)).toBe(
+ `${code}${separator}[https://outside.example](https://outside.example)`,
+ )
+ })
+
+ it('keeps blank lines inside a list item fence', () => {
+ const source = '- ```\n a\n\n https://example.com\n ```'
+ expect(findBlockCodeRanges(source)).toEqual([{ start: 0, end: source.length }])
+ })
+
+ it('lets a line that ends the container open a new fence', () => {
+ const source = '> ```\n> a\n```\nhttps://example.com'
+ expect(findBlockCodeRanges(source)).toEqual([
+ { start: 0, end: 9 },
+ { start: 10, end: source.length },
+ ])
+ })
+
+ it.each(['> ', '> > ', ' '])('protects fences with the prefix %j', (prefix) => {
+ const source = `${prefix}\`\`\`\`\n${prefix}\`\`\`\n${prefix}https://example.com\n${prefix}\`\`\`\``
+ expect(preprocessLinks(source)).toBe(source)
+ })
+
+ it('protects a list code block with indented continuation lines', () => {
+ const source = '- ````\n ```\n https://example.com\n ````'
+ expect(preprocessLinks(source)).toBe(source)
+ })
+
+ it.each([
+ ['- ', '\t'],
+ ['-\t', '\t'],
+ ['1. ', '\t'],
+ ['12) ', '\t'],
+ ['> - ', '>\t'],
+ ['- > ', '\t> '],
+ ])('keeps tab-indented code literal in %j', (prefix, continuation) => {
+ const source = `${prefix}\`\`\`\n${continuation}https://inside.example\n${continuation}\`\`\``
+ expect(preprocessLinks(source)).toBe(source)
+ })
+
+ it.each([
+ ['- item', ' '],
+ ['12) item', ' '],
+ ['> - item\n>', '> '],
+ ['- parent\n - child', ' '],
+ ['- item\nlazy continuation', ' '],
+ ])('ends a fence opened after %j at its container boundary', (item, prefix) => {
+ const code = `${item}\n\n${prefix}\`\`\`\n${prefix}https://inside.example`
+ const source = `${code}\n\nhttps://outside.example`
+ expect(preprocessLinks(source)).toBe(
+ `${code}\n\n[https://outside.example](https://outside.example)`,
+ )
+ })
+
+ it('keeps an indented code block containing fences literal', () => {
+ const source = ' ```\n https://inside.example\n ```\n\nhttps://outside.example'
+ expect(preprocessLinks(source)).toBe(
+ ' ```\n https://inside.example\n ```\n\n[https://outside.example](https://outside.example)',
+ )
+ })
+
+ it.each(['`', '``', '```'])('keeps matching %s inline spans protected', (ticks) => {
+ const source = `before ${ticks}https://example.com${ticks} after`
+ expect(preprocessLinks(source)).toBe(source)
+ })
+})
+
+it('keeps the URL inside a multiline triple-backtick inline span literal', () => {
+ const source = 'before ```https://example.com\ncontinuation``` after'
+ expect(preprocessLinks(source)).toBe(source)
+ expect(findCodeRanges(source)).toContainEqual({ start: 7, end: source.indexOf(' after') })
+})
+
+it('protects a URL on the second line of a multiline inline span', () => {
+ const source = 'before ```first\nhttps://example.com\ncontinuation``` after'
+ expect(preprocessLinks(source)).toBe(source)
+})
+
+it.each([
+ ['- > ', ' > '],
+ ['> - ', '> '],
+ ['- > - ', ' > '],
+ ['> - > ', '> > '],
+ ['1. > ', ' > '],
+ ['> 12) > ', '> > '],
+])('protects mixed container fences starting with %j', (opening, continuation) => {
+ const source = `${opening}\`\`\`text\n${continuation}https://example.com\n${continuation}\`\`\``
+ expect(preprocessLinks(source)).toBe(source)
+})
+
+it('does not join inline code across a blank paragraph boundary', () => {
+ const source = 'before `unmatched\n\nhttps://example.com\n` after'
+ expect(preprocessLinks(source)).toBe(
+ 'before `unmatched\n\n[https://example.com](https://example.com)\n` after',
+ )
+})
+
+it('does not join inline code across a CRLF blank line', () => {
+ const source = 'before `unmatched\r\n\r\nhttps://example.com\r\n` after'
+ expect(preprocessLinks(source)).toBe(
+ 'before `unmatched\r\n\r\n[https://example.com](https://example.com)\r\n` after',
+ )
+})
+
+it('protects inline code immediately after a longer fenced closer', () => {
+ const source = '```text\nliteral\n````\nbefore ``` https://example.com ``` after'
+ expect(preprocessLinks(source)).toBe(source)
+})
+
+it('does not extend inline code across a fenced block', () => {
+ const source = 'before `unmatched https://outside.example\n~~~text\n`literal\n~~~'
+ expect(preprocessLinks(source)).toBe(
+ 'before `unmatched [https://outside.example](https://outside.example)\n~~~text\n`literal\n~~~',
+ )
+})
+
+it.each(['x', ''])('scans repeated list prefixes without backtracking (%j)', (suffix) => {
+ const source = '- '.repeat(25) + suffix + '\n\nhttps://example.com'
+ const start = performance.now()
+ expect(preprocessLinks(source)).toBe(
+ '- '.repeat(25) + suffix + '\n\n[https://example.com](https://example.com)',
+ )
+ expect(performance.now() - start).toBeLessThan(250)
+})
diff --git a/packages/ui/markdown/linkify.ts b/packages/ui/markdown/linkify.ts
index fab1ba7a5d..3b8f8f3648 100644
--- a/packages/ui/markdown/linkify.ts
+++ b/packages/ui/markdown/linkify.ts
@@ -1,4 +1,6 @@
import LinkifyIt from 'linkify-it'
+import { fromMarkdown } from 'mdast-util-from-markdown'
+import type { Nodes } from 'mdast'
/**
* Linkify - URL and file path detection for markdown preprocessing
@@ -73,19 +75,45 @@ export function shouldAutoLink(value: string): boolean {
)
}
+/**
+ * Find block-code ranges using the same CommonMark parser as the read-only
+ * renderer. Container membership depends on preceding lines and tab columns,
+ * not just the prefix on a fence's opening line. Include indented code too:
+ * its literal backticks must not be mistaken for standalone fences.
+ */
+export function findBlockCodeRanges(text: string): CodeRange[] {
+ // Plain paragraphs and inline code need no block parse.
+ if (!/`{3}|~{3}| {4}|\t/.test(text)) return []
+
+ const ranges: CodeRange[] = []
+ const pending: Nodes[] = [fromMarkdown(text)]
+ while (pending.length > 0) {
+ const node = pending.pop()!
+ if (node.type === 'code') {
+ const start = node.position?.start.offset
+ const end = node.position?.end.offset
+ if (start !== undefined && end !== undefined) {
+ // Include list/quote prefixes so chunking keeps the opening line.
+ ranges.push({ start: text.lastIndexOf('\n', start - 1) + 1, end })
+ }
+ } else if ('children' in node) {
+ // Reverse push preserves source order without recursion on nested lists.
+ for (let i = node.children.length - 1; i >= 0; i--) {
+ pending.push(node.children[i]!)
+ }
+ }
+ }
+ return ranges
+}
+
/**
* Find all code block and inline code ranges in text
* These ranges should be excluded from link detection
*/
export function findCodeRanges(text: string): CodeRange[] {
- const ranges: CodeRange[] = []
-
- // Find fenced code blocks (```...```)
- const fencedRegex = /```[\s\S]*?```/g
+ const blockRanges = findBlockCodeRanges(text)
+ const ranges = [...blockRanges]
let match
- while ((match = fencedRegex.exec(text)) !== null) {
- ranges.push({ start: match.index, end: match.index + match[0].length })
- }
// Find display math blocks ($$...$$)
const displayMathRegex = /\$\$[\s\S]*?\$\$/g
@@ -107,16 +135,26 @@ export function findCodeRanges(text: string): CodeRange[] {
}
}
- // Find inline code (`...`)
- // But skip escaped backticks and code inside fenced blocks
- const inlineRegex = /(?<!`)`(?!`)([^`\n]+)`(?!`)/g
+ // Find inline code spans with matching backtick runs.
+ // Ignore spans inside fenced code or math blocks.
+ // Inline code can span soft line breaks, but not a blank paragraph boundary
+ // (LF or CRLF).
+ const inlineRegex = /(?<!`)(`+)(?!`)((?:[^\n]|\n(?![ \t]*\r?\n))*?)(?<!`)\1(?!`)/g
while ((match = inlineRegex.exec(text)) !== null) {
const pos = match.index
- // Check if this is inside a fenced block or math block
- const insideOther = ranges.some((r) => pos >= r.start && pos < r.end)
- if (!insideOther) {
- ranges.push({ start: pos, end: pos + match[0].length })
+ const end = pos + match[0].length
+ // An inline span cannot cross a block-code boundary.
+ const crossedBlock = blockRanges.find((r) => pos < r.end && end > r.start)
+ if (crossedBlock) {
+ inlineRegex.lastIndex = crossedBlock.end
+ continue
+ }
+ const insideOther = ranges.find((r) => pos >= r.start && pos < r.end)
+ if (insideOther) {
+ inlineRegex.lastIndex = insideOther.end
+ continue
}
+ ranges.push({ start: pos, end })
}
return ranges
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 51694c3b16..abac217f1f 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -42,6 +42,7 @@
"input-otp": "^1.4.2",
"linkify-it": "^5.0.0",
"katex": "catalog:",
+ "mdast-util-from-markdown": "^2.0.3",
"next-themes": "^0.4.6",
"react-day-picker": "^9.14.0",
"react-markdown": "^10.1.0",
@@ -69,6 +70,7 @@
"@testing-library/jest-dom": "catalog:",
"@testing-library/react": "catalog:",
"@types/linkify-it": "^5.0.0",
+ "@types/mdast": "^4.0.4",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@typescript/native": "catalog:",
diff --git a/packages/views/editor/extensions/code-block.test.ts b/packages/views/editor/extensions/code-block.test.ts
new file mode 100644
index 0000000000..59a00bb65a
--- /dev/null
+++ b/packages/views/editor/extensions/code-block.test.ts
@@ -0,0 +1,117 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import { createEditorExtensions } from ".";
+import { preprocessMarkdown } from "../utils/preprocess";
+import {
+ MARKDOWN_CHUNK_THRESHOLD,
+ parseMarkdownChunked,
+ type MarkdownManagerLike,
+} from "../utils/parse-markdown-chunked";
+
+const editors: Editor[] = [];
+
+afterEach(() => {
+ editors.forEach((editor) => editor.destroy());
+ editors.length = 0;
+ document.body.innerHTML = "";
+});
+
+function load(markdown: string): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ const processed = preprocessMarkdown(markdown, { cdnDomain: "" });
+ const chunked = processed.length > MARKDOWN_CHUNK_THRESHOLD;
+ const editor = new Editor({
+ element,
+ extensions: createEditorExtensions({ disableMentions: true }),
+ content: chunked ? "" : processed,
+ contentType: chunked ? undefined : "markdown",
+ });
+ if (chunked) {
+ const manager = (editor.storage as { markdown: { manager: MarkdownManagerLike } })
+ .markdown.manager;
+ editor.commands.setContent(parseMarkdownChunked(manager, processed), {
+ emitUpdate: false,
+ });
+ }
+ editors.push(editor);
+ return editor;
+}
+
+function roundTrip(source: string, content: string, language: string | null) {
+ const editor = load(source);
+ expect(editor.state.doc.child(1).type.name).toBe("codeBlock");
+ expect(editor.state.doc.child(1).textContent).toBe(content);
+ expect(editor.state.doc.child(1).attrs.language).toBe(language);
+
+ // Editing an unrelated paragraph saves every block in ContentEditor.
+ editor.commands.setTextSelection(1);
+ editor.commands.insertContent("Edited ");
+ const beforeSave = editor.getJSON();
+ const saved = editor.getMarkdown();
+ const reloaded = load(saved);
+ expect(reloaded.getJSON()).toEqual(beforeSave);
+ expect(reloaded.getMarkdown()).toBe(saved);
+ return saved;
+}
+
+describe("code block Markdown save and reload", () => {
+ for (const length of [3, 4, 6]) {
+ for (const language of ["", "markdown", "typescript", "unknown-language"]) {
+ it(`preserves a ${length}-backtick line with language '${language}'`, () => {
+ const inner = "`".repeat(length);
+ const outer = "`".repeat(length + 1);
+ const content = `before\n${inner}\n# still code\n\n<tag> & *literal*\nafter`;
+ const source = `Intro\n\n${outer}${language}\n${content}\n${outer}\n\nOutro`;
+ const saved = roundTrip(source, content, language || null);
+ expect(saved).toContain(`${outer}${language}\n${content}\n${outer}`);
+ });
+ }
+ }
+
+ it.each([
+ ["", ""],
+ ["javascript", "console.log('hello');"],
+ ["", "one `tick` and ``two``"],
+ ["text", "first\n\nlast\n"],
+ ])("keeps ordinary '%s' blocks unchanged (%j)", (language, content) => {
+ const source = `Intro\n\n\`\`\`${language}\n${content}\n\`\`\`\n\nOutro`;
+ expect(roundTrip(source, content, language || null)).toBe(`Edited ${source}`);
+ });
+
+ it("safely serializes tilde-fenced input containing backtick fences", () => {
+ const content = "```js\nconst value = 1;\n```\ntail";
+ roundTrip(`Intro\n\n~~~markdown\n${content}\n~~~\n\nOutro`, content, "markdown");
+ });
+
+ it("preserves nested fences in a blockquote", () => {
+ const source = "Intro\n\n> `````markdown\n> before\n> ````\n> after\n> `````\n\nOutro";
+ const editor = load(source);
+ const saved = editor.getMarkdown();
+ expect(load(saved).getJSON()).toEqual(editor.getJSON());
+ });
+});
+
+describe("production preprocessing and large-document loading", () => {
+ it("keeps a URL literal after serialization grows the outer fence", () => {
+ const content = "https://example.com\nconst ticks = '`````';";
+ const source = `Intro\n\n\`\`\`javascript\n${content}\n\`\`\`\n\nOutro`;
+ roundTrip(source, content, "javascript");
+ });
+
+ it("keeps URLs literal between nested fences on initial load", () => {
+ const content = "```\nhttps://example.com\n```\nafter";
+ const source = `Intro\n\n\`\`\`\`markdown\n${content}\n\`\`\`\`\n\nOutro`;
+ roundTrip(source, content, "markdown");
+ });
+
+ it.each(["```", "~~~", "````javascript"])(
+ "does not split a large code block at an inner %s line",
+ (inner) => {
+ const content = `${"x".repeat(4_100)}\n${inner}\n\n# still literal\n${"y".repeat(4_100)}`;
+ const source = `Intro\n\n\`\`\`\`markdown\n${content}\n\`\`\`\`\n\nOutro`;
+ expect(source.length).toBeGreaterThan(MARKDOWN_CHUNK_THRESHOLD);
+ roundTrip(source, content, "markdown");
+ },
+ );
+});
diff --git a/packages/views/editor/extensions/code-block.ts b/packages/views/editor/extensions/code-block.ts
new file mode 100644
index 0000000000..a5c16b5a07
--- /dev/null
+++ b/packages/views/editor/extensions/code-block.ts
@@ -0,0 +1,14 @@
+import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
+
+export const CodeBlockExtension = CodeBlockLowlight.extend({
+ renderMarkdown(node, helpers) {
+ const content = helpers.renderChildren(node.content ?? []);
+ // A literal fence inside the code must not close the serialized block.
+ let fenceLength = 3;
+ for (const [run] of content.matchAll(/`+/g)) {
+ fenceLength = Math.max(fenceLength, run.length + 1);
+ }
+ const fence = "`".repeat(fenceLength);
+ return `${fence}${node.attrs?.language ?? ""}\n${content}\n${fence}`;
+ },
+});
diff --git a/packages/views/editor/extensions/code.test.ts b/packages/views/editor/extensions/code.test.ts
index 2635fc20f7..c768e3e1dc 100644
--- a/packages/views/editor/extensions/code.test.ts
+++ b/packages/views/editor/extensions/code.test.ts
@@ -3,6 +3,7 @@ import { Editor } from "@tiptap/core";
import StarterKit from "@tiptap/starter-kit";
import { Markdown } from "@tiptap/markdown";
import { createEditorExtensions } from ".";
+import { preprocessMarkdown } from "../utils/preprocess";
let editor: Editor | null = null;
@@ -122,3 +123,61 @@ describe("fenced code language", () => {
);
});
});
+
+it("preserves multiline inline code through preprocessing, save and reload", () => {
+ const source = "before ```https://example.com\ncontinuation``` after";
+ editor = makeProductionEditor();
+ editor.commands.setContent(source, { contentType: "markdown" });
+ const expected = editor.getJSON();
+ expect(editor.view.dom.querySelector("code")?.textContent).toBe(
+ "https://example.com continuation",
+ );
+
+ editor.commands.setContent(preprocessMarkdown(source, { cdnDomain: "" }), {
+ contentType: "markdown",
+ });
+ expect(editor.getJSON()).toEqual(expected);
+ const saved = editor.getMarkdown();
+ editor.commands.setContent(preprocessMarkdown(saved, { cdnDomain: "" }), {
+ contentType: "markdown",
+ });
+ expect(editor.getJSON()).toEqual(expected);
+ expect(editor.getMarkdown()).toBe(saved);
+});
+
+it.each([
+ "before ```first\nhttps://example.com\ncontinuation``` after",
+ "Intro\n\n- > ```text\n > https://example.com\n > ```\n\nOutro",
+ "Intro\n\n> - ```text\n> https://example.com\n> ```\n\nOutro",
+ "Intro\n\n- > - ```text\n > https://example.com\n > ```\n\nOutro",
+ "Intro\n\n> - > ```text\n> > https://example.com\n> > ```\n\nOutro",
+])("adds no preprocessing mutations to mixed-container or multiline code (%j)", (source) => {
+ editor = makeProductionEditor();
+ editor.commands.setContent(source, { contentType: "markdown" });
+ const expected = editor.getJSON();
+ const rawSaved = editor.getMarkdown();
+ let hasCode = false;
+ editor.state.doc.descendants((node) => {
+ if (node.type.name === "codeBlock" || node.marks.some((mark) => mark.type.name === "code")) {
+ hasCode = true;
+ }
+ });
+ expect(hasCode).toBe(true);
+ expect(editor.getText()).toContain("https://example.com");
+ // Compare with the raw parser at each phase: stock list/quote serialization
+ // can normalize container structure independently of link preprocessing.
+ editor.commands.setContent(rawSaved, { contentType: "markdown" });
+ const rawReloaded = editor.getJSON();
+ const rawSecondSave = editor.getMarkdown();
+ editor.commands.setContent(preprocessMarkdown(source, { cdnDomain: "" }), {
+ contentType: "markdown",
+ });
+ expect(editor.getJSON()).toEqual(expected);
+ const saved = editor.getMarkdown();
+ expect(saved).toBe(rawSaved);
+ editor.commands.setContent(preprocessMarkdown(saved, { cdnDomain: "" }), {
+ contentType: "markdown",
+ });
+ expect(editor.getJSON()).toEqual(rawReloaded);
+ expect(editor.getMarkdown()).toBe(rawSecondSave);
+});
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 72a9259a3c..c4929d7f40 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -21,7 +21,7 @@
*/
import type { RefObject } from "react";
import StarterKit from "@tiptap/starter-kit";
-import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
+import { CodeBlockExtension } from "./code-block";
import Placeholder from "@tiptap/extension-placeholder";
import Link from "@tiptap/extension-link";
import Typography from "@tiptap/extension-typography";
@@ -231,7 +231,7 @@ export function createEditorExtensions(
// `- ` still falls through to PatchedListItem's bullet list.
TaskList,
PatchedTaskItem,
- CodeBlockLowlight.extend({
+ CodeBlockExtension.extend({
addNodeView() {
return ReactNodeViewRenderer(CodeBlockView);
},
diff --git a/packages/views/editor/utils/highlight-markdown.test.ts b/packages/views/editor/utils/highlight-markdown.test.ts
index 5bd40bbbc0..143fc857d6 100644
--- a/packages/views/editor/utils/highlight-markdown.test.ts
+++ b/packages/views/editor/utils/highlight-markdown.test.ts
@@ -39,6 +39,23 @@ describe("highlightToHtml", () => {
expect(highlightToHtml(md)).toBe(md);
});
+ it("ignores == inside a longer fence that contains a nested fence", () => {
+ // The editor saves a block containing ``` with a ```` outer fence.
+ const md = '````markdown\n```js\nconst a = "==keep==";\n```\n````';
+ expect(highlightToHtml(md)).toBe(md);
+ });
+
+ it("ignores == inside inline code delimited by several backticks", () => {
+ const md = "before ```a `b` ==keep==``` after";
+ expect(highlightToHtml(md)).toBe(md);
+ });
+
+ it("highlights after a quoted unclosed fence ends", () => {
+ expect(highlightToHtml("> ```\n> code\n\n==outside==")).toBe(
+ "> ```\n> code\n\n<mark>outside</mark>",
+ );
+ });
+
it("ignores == inside inline math", () => {
expect(highlightToHtml("$a ==b== c$")).toBe("$a ==b== c$");
});
diff --git a/packages/views/editor/utils/highlight-match.test.ts b/packages/views/editor/utils/highlight-match.test.ts
index 9af70b3865..e97fbc30f9 100644
--- a/packages/views/editor/utils/highlight-match.test.ts
+++ b/packages/views/editor/utils/highlight-match.test.ts
@@ -70,4 +70,13 @@ describe("findLiteralRanges", () => {
const fencePos = text.indexOf("==x==");
expect(ranges.some((r) => fencePos >= r.start && fencePos < r.end)).toBe(true);
});
+
+ it.each([
+ ["a longer outer fence around an inner ``` block", "````markdown\n```js\n==x==\n```\n````"],
+ ["a tilde fence", "~~~\n==x==\n~~~"],
+ ["an unclosed fence", "```\ncode\n==x=="],
+ ])("treats == inside %s as literal", (_, text) => {
+ const pos = text.indexOf("==x==");
+ expect(findLiteralRanges(text).some((r) => pos >= r.start && pos < r.end)).toBe(true);
+ });
});
diff --git a/packages/views/editor/utils/highlight-match.ts b/packages/views/editor/utils/highlight-match.ts
index 7291b136ac..8eb88d9f6c 100644
--- a/packages/views/editor/utils/highlight-match.ts
+++ b/packages/views/editor/utils/highlight-match.ts
@@ -15,6 +15,8 @@
* literal paragraphs, matching how the editor lexes it)
*/
+import { findCodeRanges } from "@multica/ui/markdown/linkify";
+
export interface Range {
start: number;
end: number;
@@ -29,27 +31,12 @@ const BLANK_LINE_RE = /\r?\n[ \t]*\r?\n/;
/**
* Spans where `==` must NOT be interpreted as highlight syntax: fenced code,
- * inline code, and inline/display math. Mirrors the code-range scan in
- * @multica/ui/markdown's linkify so highlight and autolink skip the same
- * literal contexts. Earlier (block-level) ranges win so a `==`/backtick inside
- * a fenced block is not also counted as inline.
+ * inline code, and inline/display math. This is linkify's code-range scan, so
+ * highlight and autolink skip exactly the same literal contexts, including
+ * longer or tilde fences and inline code delimited by several backticks.
*/
export function findLiteralRanges(text: string): Range[] {
- const ranges: Range[] = [];
- const add = (re: RegExp) => {
- let m: RegExpExecArray | null;
- re.lastIndex = 0;
- while ((m = re.exec(text)) !== null) {
- const start = m.index;
- if (ranges.some((r) => start >= r.start && start < r.end)) continue;
- ranges.push({ start, end: start + m[0].length });
- }
- };
- add(/```[\s\S]*?```/g); // fenced code
- add(/\$\$[\s\S]*?\$\$/g); // display math
- add(/(?<!\$)\$(?!\$)[^$\n]+\$(?!\$)/g); // inline math
- add(/(?<!`)`(?!`)[^`\n]+`(?!`)/g); // inline code
- return ranges;
+ return findCodeRanges(text);
}
function isInside(pos: number, ranges: Range[]): boolean {
diff --git a/packages/views/editor/utils/parse-markdown-chunked.ts b/packages/views/editor/utils/parse-markdown-chunked.ts
index 8be8b09efd..70195b489c 100644
--- a/packages/views/editor/utils/parse-markdown-chunked.ts
+++ b/packages/views/editor/utils/parse-markdown-chunked.ts
@@ -1,4 +1,5 @@
import type { JSONContent } from "@tiptap/core";
+import { findBlockCodeRanges } from "@multica/ui/markdown/linkify";
/**
* Above this source size, ContentEditor parses markdown in chunks instead of in
@@ -41,11 +42,19 @@ export function parseMarkdownChunked(
const chunks: string[] = [];
let current: string[] = [];
let currentLen = 0;
- let inFence = false;
+ const codeRanges = findBlockCodeRanges(markdown);
+ let rangeIndex = 0;
+ let offset = 0;
for (const line of lines) {
- // Track fenced code blocks so a cut never lands inside one.
- if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
+ // Use the same fence boundaries as link preprocessing; shorter or mixed
+ // literal fences inside a code block must not create chunk boundaries.
+ while (codeRanges[rangeIndex] && offset >= codeRanges[rangeIndex]!.end) {
+ rangeIndex += 1;
+ }
+ const range = codeRanges[rangeIndex];
+ const inFence = range !== undefined && offset >= range.start;
+ offset += line.length + 1;
current.push(line);
currentLen += line.length + 1;
diff --git a/packages/views/editor/utils/preprocess-code.test.ts b/packages/views/editor/utils/preprocess-code.test.ts
new file mode 100644
index 0000000000..d8a65afe00
--- /dev/null
+++ b/packages/views/editor/utils/preprocess-code.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import { createEditorExtensions } from "../extensions";
+import { preprocessMarkdown } from "./preprocess";
+import { highlightToHtml } from "./highlight-markdown";
+import { preprocessLinks } from "@multica/ui/markdown/linkify";
+import { preprocessIssueIdentifiers } from "@multica/ui/markdown";
+
+describe("code boundaries in editor and read-only preprocessing", () => {
+ it("keeps tab-indented list code literal through editor preprocessing", () => {
+ const source =
+ "Intro\n\n- ```\n\thttps://example.com ==keep==\n\t```\n\nOutro";
+ const editor = new Editor({
+ extensions: createEditorExtensions({ disableMentions: true }),
+ content: source,
+ contentType: "markdown",
+ });
+ try {
+ const raw = editor.getJSON();
+ expect(JSON.stringify(raw)).toContain('"type":"codeBlock"');
+ expect(editor.getText()).toContain("https://example.com ==keep==");
+ const processed = preprocessMarkdown(source, { cdnDomain: "" });
+ editor.commands.setContent(processed, { contentType: "markdown" });
+ expect.soft(editor.getJSON()).toEqual(raw);
+ expect
+ .soft(editor.getMarkdown())
+ .not.toContain("[https://example.com](https://example.com)");
+ expect.soft(highlightToHtml(source)).toBe(source);
+ expect.soft(preprocessLinks(source)).toBe(source);
+ } finally {
+ editor.destroy();
+ }
+ });
+
+ it("ends an unclosed fence opened on a list continuation line", () => {
+ const source = "- item\n\n ```\n code\n\n==outside== MUL-123 ./foo.ts";
+ expect.soft(preprocessLinks(source)).toContain("[./foo.ts](./foo.ts)");
+ expect.soft(highlightToHtml(source)).toContain("<mark>outside</mark>");
+ expect
+ .soft(preprocessIssueIdentifiers(source))
+ .toContain("[MUL-123](mention://issue/MUL-123)");
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1f6f423762..135948fdb7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -777,6 +777,9 @@ importers:
linkify-it:
specifier: ^5.0.0
version: 5.0.0
+ mdast-util-from-markdown:
+ specifier: ^2.0.3
+ version: 2.0.3
next-themes:
specifier: ^0.4.6
@@ -844,6 +847,9 @@ importers:
'@types/linkify-it':
specifier: ^5.0.0
version: 5.0.0
+ '@types/mdast':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/react':
specifier: ^19.2.0
version: 19.2.14