Skip to content

Commit bcb6008

Browse files
committed
backport - fix for #12042
1 parent 582c9e5 commit bcb6008

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

src/command/convert/jupyter.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
jupyterCellSrcAsLines,
3131
jupyterCellSrcAsStr,
3232
} from "../../core/jupyter/jupyter-shared.ts";
33+
import { assert } from "testing/asserts";
3334

3435
export async function markdownToJupyterNotebook(
3536
file: string,
@@ -71,11 +72,15 @@ export async function jupyterNotebookToMarkdown(
7172
case "raw":
7273
// see if this is the front matter
7374
if (frontMatter === undefined) {
74-
frontMatter = partitionYamlFrontMatter(
75-
jupyterCellSrcAsStr(cell),
76-
)?.yaml;
77-
if (!frontMatter) {
78-
md.push(...mdFromRawCell(cellWithOptions));
75+
const { yaml: cellYaml, markdown: cellMarkdown } =
76+
partitionYamlFrontMatter(
77+
jupyterCellSrcAsStr(cell),
78+
) || {};
79+
if (cellYaml) {
80+
frontMatter = cellYaml;
81+
}
82+
if (cellMarkdown) {
83+
md.push(cellMarkdown);
7984
}
8085
} else {
8186
md.push(...mdFromRawCell(cellWithOptions));
@@ -130,14 +135,22 @@ export async function jupyterNotebookToMarkdown(
130135
}
131136
}
132137

138+
// if we found front matter, then the markdown source will start with enough
139+
// newlines for the front matter to have been detected in the first place.
140+
// So we only need to add newlines if there was no front matter.
141+
//
142+
// If this invariant breaks, we have a bug of some kind, so let's just assert it
143+
assert(frontMatter || !mdSource.match(/^\n\n/));
144+
const maybeYamlMdBreak = frontMatter ? "" : "\n\n";
145+
133146
// return yaml + markdown
134147
const yamlText = stringify(yaml, {
135148
indent: 2,
136149
lineWidth: -1,
137150
sortKeys: false,
138151
skipInvalid: true,
139152
});
140-
return `---\n${yamlText}---\n\n${mdSource}`;
153+
return `---\n${yamlText}---${maybeYamlMdBreak}${mdSource}`;
141154
}
142155

143156
async function mdFromCodeCell(

0 commit comments

Comments
 (0)