diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts
index c88ab6bbe9f9..438cd3ae9936 100644
--- a/packages/shared/src/markdownChunks.test.ts
+++ b/packages/shared/src/markdownChunks.test.ts
@@ -1112,6 +1112,34 @@ describe("chunked Markdown footnotes", () => {
["lazy header inside a list item", "- intro\n| a |\n | --- |\n x | [^1]", []],
["prose outside a list table", "- intro\n | a |\n | --- |\nx | [^1]", ["1"]],
["overindented list table header", "- intro\n | a |\n | --- |\n x | [^1]", ["1"]],
+ ["quoted header cells", "> | `l | [^1] | r` |\n> | --- | --- | --- |", ["1"]],
+ ["quoted table after prose", "> intro\n> | `l | [^1] | r` |\n> | - | - | - |", ["1"]],
+ ["nested quoted table", "> > | `l | [^1] | r` |\n> > | - | - | - |", ["1"]],
+ ["quoted table rows", "> | a | b |\n> | - | - |\n> | `l | [^1] |\n> | x | ` |", ["1"]],
+ ["quoted delimiter with a different width", "> | `l | [^1] | r` |\n> | - | - |", []],
+ ["unquoted delimiter under a quote", "> | `l | [^1] | r` |\n| - | - | - |", []],
+ ["prose after a quoted table", "> | a |\n> | - |\n\n`l | [^1] | r`", []],
+ ["lazy line after a quoted table", "> | a | b |\n> | - | - |\n`l | [^1] | r`", []],
+ ["quoted list after a quoted table", "> | a | b |\n> | - | - |\n> - `l | [^1] | r`", []],
+ ["quoted table after a table", "| a |\n| - |\n> | `l | [^1] | r` |\n> | - | - | - |", ["1"]],
+ ["quoted fence", "> ```\n> | `l | [^1] | r` |\n> | - | - | - |\n> ```", []],
+ ["quoted HTML block", ">
\n> | `l | [^1] | r` |\n> | - | - | - |", []],
+ [
+ "quoted fence after it closes",
+ "> ```\n> x\n> ```\n> | `l | [^1] | r` |\n> | - | - | - |",
+ ["1"],
+ ],
+ ["quoted indented code after a table", "> | a | b |\n> | - | - |\n> `l | [^1] | r`", []],
+ [
+ "ordered marker in quoted prose",
+ "> intro\n> 2. | `l | [^1] | r` |\n> | - | - | - | - |",
+ ["1"],
+ ],
+ ["quoted list item", "> - x\n> | `l | [^1] | r` |\n> | - | - | - |", []],
+ ["quote in a list item", "- > | `l | [^1] | r` |\n > | - | - | - |", ["1"]],
+ ["quote outside a list item", "- > | `l | [^1] | r` |\n> | - | - | - |", []],
+ ["quoted fence holding a quote marker", "> ```\n> > x\n> ```\n> actual[^1]", ["1"]],
+ ["loose list item in a quote", "> - a\n>\n> b [^1]", ["1"]],
])("matches GFM footnotes around a table boundary: %s", (_name, block, refs) => {
const filler = "filler paragraph text.\n\n".repeat(10);
const text = `${filler}${block}\n\n${filler}[^1]: note\n`;
diff --git a/packages/shared/src/markdownChunks.ts b/packages/shared/src/markdownChunks.ts
index 40ef8c612051..cf013574a6f9 100644
--- a/packages/shared/src/markdownChunks.ts
+++ b/packages/shared/src/markdownChunks.ts
@@ -22,6 +22,7 @@ const LIST_ITEM = /^( {0,3}(?:[-*+]|\d{1,9}[.)]))([ \t]+|(?=\r?$))/;
// Further markers on an item's first line open nested items that start on the same line.
const NESTED_LIST_MARKER = /([-*+]|\d{1,9}[.)])([ \t]+|(?=\r?$))/gy;
const BLOCK_QUOTE = /^ {0,3}>/;
+const QUOTE_MARKER = /^ {0,3}>[ \t]?/;
const DISPLAY_MATH_OPEN = /^ {0,3}\$\$/;
// CommonMark HTML blocks of types 1-5 and display math run past blank lines until their closer.
const SPANNING_BLOCKS: ReadonlyArray = [
@@ -847,6 +848,78 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S
return splitMarkdownBlocks(text, targetChars);
}
+interface QuoteLine {
+ readonly depth: number;
+ readonly column: number;
+ readonly text: string;
+ /** A delimiter row makes the previous line a table header. */
+ readonly kind: "prose" | "literal" | "delimiter" | "row";
+ /** An open fence, HTML block or indented code that the next line may continue. */
+ readonly closer: ((line: string) => boolean) | "indented" | null;
+ readonly paragraph: boolean;
+ /** The open paragraph belongs to a list item, where a table cannot start lazily. */
+ readonly inItem: boolean;
+}
+
+/** Follows the blocks inside a quote far enough to find its tables and literal lines. */
+function scanQuoteLine(
+ source: string,
+ column: number,
+ previous: QuoteLine | null,
+): QuoteLine | null {
+ // Inside an open fence or HTML block, a `>` past the block's own quote depth is content.
+ const fenceDepth =
+ typeof previous?.closer === "function" && previous.column === column ? previous.depth : null;
+ let depth = 0;
+ let text = source;
+ for (let marker; depth !== fenceDepth && (marker = QUOTE_MARKER.exec(text)); depth++) {
+ text = text.slice(marker[0].length);
+ }
+ if (depth === 0) return null;
+ const prev = previous?.depth === depth && previous.column === column ? previous : null;
+ const line = { depth, column, text, paragraph: false, inItem: false };
+ const blank = BLANK_LINE.test(text);
+ if (typeof prev?.closer === "function") {
+ return { ...line, kind: "literal", closer: prev.closer(text) ? null : prev.closer };
+ }
+ const inParagraph = prev?.paragraph === true;
+ const indent = indentationColumn(/^[ \t]*/.exec(text)![0]);
+ if ((!blank && indent >= 4 && !inParagraph) || (blank && prev?.closer === "indented")) {
+ return { ...line, kind: "literal", closer: "indented" };
+ }
+ if (blank) return { ...line, kind: "prose", closer: null };
+ const closer = blockCloser(text);
+ if (closer !== undefined) return { ...line, kind: "literal", closer };
+ if (opensNonParagraph(text)) return { ...line, kind: "prose", closer: null };
+ const item = LIST_ITEM.exec(text);
+ if ((prev?.kind === "delimiter" || prev?.kind === "row") && !item) {
+ return { ...line, kind: "row", closer: null };
+ }
+ const marker = item?.[1]!.trimStart();
+ const opensItem =
+ item !== null &&
+ (!inParagraph ||
+ (!BLANK_LINE.test(text.slice(item[0].length)) &&
+ (!/^\d/.test(marker!) || /^1[.)]$/.test(marker!))));
+ if (
+ inParagraph &&
+ !prev.inItem &&
+ !opensItem &&
+ (text.includes("|") || text.includes(":")) &&
+ TABLE_DELIMITER.test(text) &&
+ splitTableCells(prev.text).length === splitTableCells(text).length
+ ) {
+ return { ...line, kind: "delimiter", closer: null };
+ }
+ return {
+ ...line,
+ kind: "prose",
+ closer: null,
+ paragraph: true,
+ inItem: opensItem || (inParagraph && prev.inItem),
+ };
+}
+
function splitMarkdownBlocks(
text: string,
targetChars: number,
@@ -886,6 +959,10 @@ function splitMarkdownBlocks(
let previousIndent = 0;
// Prose after a quote line may be its lazy continuation, which an underline cannot end.
let afterQuote = false;
+ let previousQuote: QuoteLine | null = null;
+ // Quoted table rows by line, without their quote markers, and where each table starts.
+ const quotedRows = new Map();
+ const tableHeaders = new Set();
let definitionChars = 0;
let footnoteChars = 0;
let footnoteCapExceeded = false;
@@ -978,6 +1055,7 @@ function splitMarkdownBlocks(
let closedBlock = false;
let plainProse = false;
let setextHeading = false;
+ let lineQuote: QuoteLine | null = null;
if (closes !== null) {
if (closes(continued)) {
@@ -1345,6 +1423,21 @@ function splitMarkdownBlocks(
: 1;
if (startsTable && isBodyLine[lineIndex - 1] === 1) isBodyLine[lineIndex - 1] = 4;
if (inTable && isBodyLine[lineIndex - 1] === 4) isBodyLine[lineIndex] = 4;
+ // A table inside a quote splits its cells before code spans, like one outside.
+ lineQuote = scanQuoteLine(
+ item && opensItem ? (itemFenceIndent ? itemContent : "") : content,
+ item && opensItem ? itemFenceIndent : contentColumn,
+ previousQuote,
+ );
+ if (lineQuote?.kind === "delimiter") {
+ isBodyLine[lineIndex - 1] = 4;
+ quotedRows.set(lineIndex - 1, previousQuote!.text);
+ tableHeaders.add(lineIndex - 1);
+ }
+ if (lineQuote?.kind === "delimiter" || lineQuote?.kind === "row") {
+ isBodyLine[lineIndex] = 4;
+ quotedRows.set(lineIndex, lineQuote.text);
+ }
}
}
}
@@ -1363,6 +1456,7 @@ function splitMarkdownBlocks(
openWrappers = 0;
}
afterBlankLine = blank;
+ previousQuote = lineQuote;
afterClosedBlock = closedBlock;
afterPlainProse = plainProse;
previousIndent = indent;
@@ -1403,8 +1497,10 @@ function splitMarkdownBlocks(
for (let i = start; i < end; i++) {
if (isBodyLine[i] === 4) {
flushBlock();
- const cells = splitTableCells(sourceLines[i]!);
- if (i === start || isBodyLine[i - 1] !== 4) tableColumns = cells.length;
+ const cells = splitTableCells(quotedRows.get(i) ?? sourceLines[i]!);
+ if (i === start || isBodyLine[i - 1] !== 4 || tableHeaders.has(i)) {
+ tableColumns = cells.length;
+ }
for (const cell of cells.slice(0, tableColumns))
refs.push(...extractFootnoteRefs(cell, capturedFootnoteKeys, true));
continue;
diff --git a/scripts/scenarios/quoted-table-footnote-keeps-its-reference.e2e.ts b/scripts/scenarios/quoted-table-footnote-keeps-its-reference.e2e.ts
new file mode 100644
index 000000000000..3a885bd17039
--- /dev/null
+++ b/scripts/scenarios/quoted-table-footnote-keeps-its-reference.e2e.ts
@@ -0,0 +1,51 @@
+import { expect } from "e2e";
+
+import { test, WEB } from "./t3.ts";
+
+test(
+ "A quoted Markdown table links to a footnote elsewhere in the file",
+ WEB,
+ async ({ t3, app, browser, screen }) => {
+ const markdown = [
+ "> | `left | Quoted reference[^note] | right` |",
+ "> | --- | --- | --- |",
+ "",
+ "Background paragraph. ".repeat(900),
+ "",
+ "## Notes",
+ "",
+ "[^note]: Shared explanation.",
+ "",
+ ].join("\n");
+ const project = await t3.project("documentation", { "release.md": markdown });
+ const thread = await t3.thread({
+ project,
+ title: "Release notes",
+ messages: ['See :codex-file-citation{path="release.md"}'],
+ });
+ await t3.open(thread);
+
+ await screen.getByRole("button", /^Agent See/).tap();
+ await screen.getByRole("link", /^release\.md/).tap();
+ await screen.getByRole("button", "Show rendered markdown").tap();
+ await screen.getByText("Quoted reference", { exact: false }).waitFor();
+ await app.screenshot("quoted-table-footnote");
+ const reference = browser.locator("blockquote table a[data-footnote-ref]");
+ await expect(reference).toHaveCount(1);
+ const noteInView = () =>
+ browser.evaluate(() => {
+ const notes = document.querySelectorAll("section[data-footnotes] li");
+ const note = [...notes].find((item) => item.textContent?.includes("Shared explanation."));
+ const rect = note?.getBoundingClientRect();
+ return rect !== undefined && rect.top >= 0 && rect.bottom <= window.innerHeight;
+ });
+ await expect.poll(noteInView).toBe(false);
+ const clicked = await browser.evaluate(() => {
+ const anchor = document.querySelector("blockquote table a[data-footnote-ref]");
+ anchor?.click();
+ return anchor !== null;
+ });
+ expect(clicked).toBe(true);
+ await expect.poll(noteInView).toBe(true);
+ },
+);