Skip to content

Commit e22b5ed

Browse files
authored
Fix Python code comments mistaken for embedded notebook titles (#14643)
When an embedded Jupyter notebook ({{< embed notebook.ipynb >}}) has no real markdown heading, a Python comment inside a code cell (e.g. # plt.savefig(...)) could get picked up as the notebook's title in the sidebar and "Source" button. Root cause: the shared scanner markdownWithExtractedHeading (src/core/pandoc/pandoc-partition.ts) treated any #-prefixed line as an ATX heading, with no awareness of fenced code blocks. findTitle scans every cell's markdown, not just code cells, so this also reached markdown cells whose authored content can contain a fenced block nested in a list item. Fix: make the scanner fence-aware, tracking CommonMark ``` / ~~~ fence open/close state and skipping heading detection inside a fence. Fence markers are recognized indented up to 3 spaces, matching CommonMark's own limit. A real heading anywhere in the notebook is still promoted; only a fenced line that merely looks like a heading is skipped now. This fixes every caller of the scanner, not just the embed path. Fixes #14577
1 parent ab395f6 commit e22b5ed

9 files changed

Lines changed: 298 additions & 11 deletions

File tree

‎news/changelog-1.10.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ All changes included in 1.10:
1616

1717
- ([#14468](https://github.com/quarto-dev/quarto-cli/issues/14468)): The `axe` accessibility report UI (HTML overlay, revealjs report slide, dashboard offcanvas) now uses its own theme-independent colors instead of inheriting from `brand` or theme. Keeps the report readable regardless of page styling, and stops `axe` from clobbering brand colors set via `_brand.yml`.
1818
- ([#14602](https://github.com/quarto-dev/quarto-cli/pull/14602), [#14632](https://github.com/quarto-dev/quarto-cli/pull/14632)): Fix ORCID profile link having no accessible name for screen readers in HTML, Reveal.js, and ipynb title-block author metadata. (author: @mcanouil for #14602)
19-
- ([#14604](https://github.com/quarto-dev/quarto-cli/issues/14604)): The `axe` accessibility report UI now shows each violation's WCAG conformance level (e.g. `WCAG 2.0 AA (1.4.3)`) or `Best Practice`, derived from the violation's axe-core tags.
19+
- ([#14604](https://github.com/quarto-dev/quarto-cli/issues/14604)): The `axe` accessibility report UI now shows each violation's WCAG conformance level (e.g. `WCAG 2.0 AA (1.4.3)`) or `Best Practice`, derived from the violation's axe-core tags.
2020

2121
## Formats
2222

@@ -104,6 +104,7 @@ All changes included in 1.10:
104104
- ([#14472](https://github.com/quarto-dev/quarto-cli/issues/14472)): Add support for Kotlin in code annotations and YAML cell options. (author: @barendgehrels)
105105
- ([#14529](https://github.com/quarto-dev/quarto-cli/issues/14529)): Fix bundled Julia engine path leaking into rendered YAML metadata and pandoc log output when running an installed Quarto. The internal subtree-engine filter only matched the source-tree share-path layout (`resources/extension-subtrees/`) and missed installed layouts where the path is `share/extension-subtrees/`.
106106
- ([#14576](https://github.com/quarto-dev/quarto-cli/issues/14576)): Fix website render hanging when sidebar titles contain double-underscore (dunder) names.
107+
- ([#14577](https://github.com/quarto-dev/quarto-cli/issues/14577)): Fix an embedded notebook with no explicit title using a Python comment inside a code cell as the notebook title. Heading extraction now skips fenced code blocks, so a comment that merely looks like a heading is never promoted; first real markdown heading anywhere in the notebook markdown body is still used as before if not `title` provided.
107108
- ([#14582](https://github.com/quarto-dev/quarto-cli/issues/14582)): Fix format detection for extension formats (e.g. `acm-pdf`) in project preview, manuscript notebooks, MECA bundles, and website format ordering.
108109
- ([#14583](https://github.com/quarto-dev/quarto-cli/issues/14583)): Fix a shortcode used as an image source (e.g. `![]({{< meta logo >}})`) getting the `default-image-extension` appended, producing a doubled extension once the shortcode resolves.
109110
- ([#14595](https://github.com/quarto-dev/quarto-cli/issues/14595)): Fix reload preview in code-server environment

‎src/core/pandoc/pandoc-partition.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export function partitionMarkdown(markdown: string): PartitionedMarkdown {
6363
);
6464

6565
return {
66-
yaml: (partitioned ? readYamlFromMarkdown(partitioned.yaml) : undefined),
66+
yaml: partitioned ? readYamlFromMarkdown(partitioned.yaml) : undefined,
6767
headingText,
6868
headingAttr,
6969
containsRefs,
@@ -72,13 +72,40 @@ export function partitionMarkdown(markdown: string): PartitionedMarkdown {
7272
};
7373
}
7474

75+
// CommonMark allows fence markers indented up to 3 spaces (content lines
76+
// inside the fence can have any indentation, including none).
77+
const kFenceOpenRegex = /^ {0,3}(`{3,}|~{3,})/;
78+
const kFenceCloseRegex = /^ {0,3}(`{3,}|~{3,})\s*$/;
79+
7580
export function markdownWithExtractedHeading(markdown: string) {
7681
const mdLines: string[] = [];
7782
let headingText: string | undefined;
7883
let headingAttr: PandocAttr | undefined;
7984
let contentBeforeHeading = false;
85+
let fence: { char: string; length: number } | undefined;
8086

8187
for (const line of lines(markdown)) {
88+
// Skip heading detection while inside a fenced code block (``` or ~~~,
89+
// CommonMark-style) so a line that merely looks like a heading is
90+
// never mistaken for the document heading.
91+
if (fence) {
92+
mdLines.push(line);
93+
const closeMatch = line.match(kFenceCloseRegex);
94+
if (
95+
closeMatch && closeMatch[1][0] === fence.char &&
96+
closeMatch[1].length >= fence.length
97+
) {
98+
fence = undefined;
99+
}
100+
continue;
101+
}
102+
const openMatch = !headingText && line.match(kFenceOpenRegex);
103+
if (openMatch) {
104+
fence = { char: openMatch[1][0], length: openMatch[1].length };
105+
mdLines.push(line);
106+
continue;
107+
}
108+
82109
if (!headingText) {
83110
if (line.match(/^\#{1,}\s/)) {
84111
const parsedHeading = parsePandocTitle(line);
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
title: "Embed code-comment title (issue 14577)"
3+
format: html
4+
_quarto:
5+
tests:
6+
html:
7+
ensureFileRegexMatches:
8+
-
9+
# The notebook source link uses the filename as the title
10+
- 'Source:\s*notebook\.ipynb'
11+
-
12+
# The Python comment must never be used as the notebook title
13+
- 'Source:\s*(#\s*)?plt\.savefig'
14+
postRenderCleanup:
15+
- notebook-preview.html
16+
- notebook.out.ipynb
17+
- notebook_files
18+
---
19+
20+
The embedded notebook has no markdown heading cells and a code cell whose last
21+
line is a Python comment (`# plt.savefig(...)`). The notebook markdown a code
22+
cell carries is its fenced source, and heading extraction is not fence-aware,
23+
so the `#` comment matched the ATX-heading regex and was promoted to the
24+
notebook title — surfacing in the "Source" link and sidebar.
25+
26+
The title used for the "Source" link must fall back to the notebook filename,
27+
not the code comment.
28+
29+
{{< embed notebook.ipynb echo=true >}}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
title: "Embedded notebook title still promotes a heading after prose"
3+
format: html
4+
_quarto:
5+
tests:
6+
html:
7+
ensureFileRegexMatches:
8+
-
9+
# A heading is still promoted to the title even when a prose
10+
# paragraph precedes it in the notebook's markdown cell.
11+
- 'Source:\s*Some Header'
12+
postRenderCleanup:
13+
- heading-after-content-preview.html
14+
- heading-after-content.out.ipynb
15+
- heading-after-content_files
16+
---
17+
18+
The embedded notebook's first markdown cell has prose before its only heading
19+
(`# Some Header`). Unlike `fixupFrontMatter` (used for a notebook's own
20+
front-matter title, see #5363 / #6411, commit `24672a4af`), the embed "Source"
21+
link title (`findTitle` in `jupyter-embed.ts`) does not require the heading to
22+
be the very first thing in the cell — it promotes the first heading it finds
23+
in any cell. Only content inside a fenced code block (a comment that merely
24+
looks like an ATX heading, see #14577) is excluded from heading detection.
25+
26+
{{< embed heading-after-content.ipynb >}}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"id": "m1",
6+
"metadata": {},
7+
"source": ["Some intro content here.\n", "\n", "# Some Header\n", "\n", "More content after the header.\n"]
8+
},
9+
{
10+
"cell_type": "code",
11+
"execution_count": 1,
12+
"id": "c1",
13+
"metadata": {},
14+
"outputs": [{"name": "stdout", "output_type": "stream", "text": ["hi\n"]}],
15+
"source": ["print('hi')"]
16+
}
17+
],
18+
"metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"name": "python"}},
19+
"nbformat": 4, "nbformat_minor": 5
20+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": 1,
6+
"id": "c1",
7+
"metadata": {},
8+
"outputs": [
9+
{
10+
"name": "stdout",
11+
"output_type": "stream",
12+
"text": [
13+
"hello\n"
14+
]
15+
}
16+
],
17+
"source": [
18+
"print('hello')\n",
19+
"# plt.savefig('./fig/Shockley-parity/lowest_solution.svg')"
20+
]
21+
}
22+
],
23+
"metadata": {
24+
"kernelspec": {
25+
"display_name": "Python 3",
26+
"language": "python",
27+
"name": "python3"
28+
},
29+
"language_info": {
30+
"name": "python"
31+
}
32+
},
33+
"nbformat": 4,
34+
"nbformat_minor": 5
35+
}

‎tests/smoke/embed/render-embed.test.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
*
66
*/
77
import { dirname, extname, join } from "../../../src/deno_ral/path.ts";
8+
import { safeRemoveSync } from "../../../src/deno_ral/fs.ts";
89
import { docs, outputForInput } from "../../utils.ts";
910
import {
1011
ensureFileRegexMatches,
@@ -42,8 +43,8 @@ testRender(input, format, false, [
4243
], {
4344
teardown: () => {
4445
// clean up the notebook that is referenced by `embed-qmd-qmd`
45-
Deno.removeSync(nbOutput);
46-
Deno.removeSync(nbSupporting, { recursive: true });
46+
safeRemoveSync(nbOutput);
47+
safeRemoveSync(nbSupporting, { recursive: true });
4748

4849
return Promise.resolve();
4950
},
@@ -95,9 +96,9 @@ testRender(ipynbInput, format, false, [
9596
], {
9697
teardown: () => {
9798
// clean up the notebook that is referenced by `embed-qmd-qmd`
98-
Deno.removeSync(ipynbPreviewNb);
99-
Deno.removeSync(ipynbPreviewSupporting, { recursive: true });
100-
Deno.removeSync(ipynbPreviewRendered);
99+
safeRemoveSync(ipynbPreviewNb);
100+
safeRemoveSync(ipynbPreviewSupporting, { recursive: true });
101+
safeRemoveSync(ipynbPreviewRendered);
101102

102103
return Promise.resolve();
103104
},
@@ -128,7 +129,7 @@ testRender(docInput, "html", false, [
128129

129130
const cleanup = ["notebook.embed_files", "notebook.embed-preview.html", "notebook2.embed_files", "notebook2.embed-preview.html"];
130131
cleanup.forEach((path) => {
131-
Deno.removeSync(join(dir, path), {recursive: true});
132+
safeRemoveSync(join(dir, path), {recursive: true});
132133
})
133134
return Promise.resolve();
134135
},

‎tests/smoke/smoke-all.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,9 @@ const postRenderCleanup = () => {
170170
for (const file of postRenderCleanupFiles) {
171171
console.log(`Cleaning up ${file} in ${Deno.cwd()}`);
172172
if (safeExistsSync(file)) {
173-
Deno.removeSync(file);
173+
// recursive so a registered entry can be a directory (e.g. an embedded
174+
// notebook's `*_files` support dir), not just a single file
175+
safeRemoveSync(file, { recursive: true });
174176
}
175177
}
176178
}

‎tests/unit/pandoc-partition.test.ts‎

Lines changed: 148 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
* Copyright (C) 2020-2022 Posit Software, PBC
55
*
66
*/
7-
import { assert } from "testing/asserts";
7+
import { assert, assertEquals } from "testing/asserts";
88
import { Metadata } from "../../src/config/types.ts";
9-
import { languagesWithClasses, partitionMarkdown } from "../../src/core/pandoc/pandoc-partition.ts";
9+
import { languagesWithClasses, markdownWithExtractedHeading, partitionMarkdown } from "../../src/core/pandoc/pandoc-partition.ts";
1010
import { unitTest } from "../test.ts";
1111

1212
// deno-lint-ignore require-await
@@ -73,3 +73,149 @@ y = 2
7373
assert(result.has("python"), "Should have language 'python'");
7474
assert(result.get("python") === "foo", "python should have class 'foo'");
7575
});
76+
77+
// deno-lint-ignore require-await
78+
unitTest(
79+
"markdownWithExtractedHeading - ignores an ATX-heading-like line inside a fenced code block",
80+
async () => {
81+
const markdown = [
82+
"```{python}",
83+
"print('hello')",
84+
"# plt.savefig('x.svg')",
85+
"```",
86+
].join("\n");
87+
const result = markdownWithExtractedHeading(markdown);
88+
assertEquals(
89+
result.headingText,
90+
undefined,
91+
"A comment inside a fenced code block must not be treated as a heading",
92+
);
93+
},
94+
);
95+
96+
// deno-lint-ignore require-await
97+
unitTest(
98+
"markdownWithExtractedHeading - still extracts a real heading after a closed fenced code block",
99+
async () => {
100+
const markdown = [
101+
"```{python}",
102+
"print('hello')",
103+
"```",
104+
"",
105+
"# Real Heading",
106+
].join("\n");
107+
const result = markdownWithExtractedHeading(markdown);
108+
assertEquals(result.headingText, "Real Heading");
109+
assert(
110+
result.contentBeforeHeading,
111+
"The fenced block content should still count as content before the heading",
112+
);
113+
},
114+
);
115+
116+
// deno-lint-ignore require-await
117+
unitTest(
118+
"markdownWithExtractedHeading - still promotes a heading that follows a prose paragraph (no fence)",
119+
async () => {
120+
const markdown = [
121+
"Some intro paragraph.",
122+
"",
123+
"# Real Heading",
124+
].join("\n");
125+
const result = markdownWithExtractedHeading(markdown);
126+
assertEquals(
127+
result.headingText,
128+
"Real Heading",
129+
"Non-fenced prose before a heading must not prevent heading extraction",
130+
);
131+
},
132+
);
133+
134+
// deno-lint-ignore require-await
135+
unitTest(
136+
"markdownWithExtractedHeading - ignores an ATX-heading-like line inside a tilde-fenced code block",
137+
async () => {
138+
const markdown = [
139+
"~~~python",
140+
"# not a heading",
141+
"~~~",
142+
].join("\n");
143+
const result = markdownWithExtractedHeading(markdown);
144+
assertEquals(result.headingText, undefined);
145+
},
146+
);
147+
148+
// deno-lint-ignore require-await
149+
unitTest(
150+
"markdownWithExtractedHeading - ignores an ATX-heading-like line inside a fenced code block whose fence markers are indented up to 3 spaces",
151+
async () => {
152+
const markdown = [
153+
"- a list item with a nested code block",
154+
"",
155+
" ```python",
156+
"# not a heading",
157+
" ```",
158+
].join("\n");
159+
const result = markdownWithExtractedHeading(markdown);
160+
assertEquals(result.headingText, undefined);
161+
},
162+
);
163+
164+
// deno-lint-ignore require-await
165+
unitTest(
166+
"markdownWithExtractedHeading - closes a fence whose closing marker is indented, then extracts the following heading",
167+
async () => {
168+
const markdown = [
169+
"```python",
170+
"code",
171+
" ```",
172+
"# Real Heading",
173+
].join("\n");
174+
const result = markdownWithExtractedHeading(markdown);
175+
assertEquals(result.headingText, "Real Heading");
176+
},
177+
);
178+
179+
// deno-lint-ignore require-await
180+
unitTest(
181+
"markdownWithExtractedHeading - extracts a setext-style heading",
182+
async () => {
183+
const markdown = [
184+
"Real Heading",
185+
"===",
186+
].join("\n");
187+
const result = markdownWithExtractedHeading(markdown);
188+
assertEquals(result.headingText, "Real Heading");
189+
assertEquals(result.lines, []);
190+
},
191+
);
192+
193+
// deno-lint-ignore require-await
194+
unitTest(
195+
"markdownWithExtractedHeading - no heading present",
196+
async () => {
197+
const markdown = [
198+
"Just a paragraph.",
199+
"",
200+
"Another paragraph.",
201+
].join("\n");
202+
const result = markdownWithExtractedHeading(markdown);
203+
assertEquals(result.headingText, undefined);
204+
assertEquals(result.lines, markdown.split("\n"));
205+
},
206+
);
207+
208+
// deno-lint-ignore require-await
209+
unitTest(
210+
"markdownWithExtractedHeading - contentBeforeHeading is false when the heading is the first line",
211+
async () => {
212+
const markdown = [
213+
"# Real Heading",
214+
"",
215+
"Some body text.",
216+
].join("\n");
217+
const result = markdownWithExtractedHeading(markdown);
218+
assertEquals(result.headingText, "Real Heading");
219+
assertEquals(result.contentBeforeHeading, false);
220+
},
221+
);

0 commit comments

Comments
 (0)