diff --git a/.changeset/fuzzy-pots-think.md b/.changeset/fuzzy-pots-think.md new file mode 100644 index 000000000..39a82b319 --- /dev/null +++ b/.changeset/fuzzy-pots-think.md @@ -0,0 +1,6 @@ +--- +"markdown-it-myst": patch +"myst-parser": patch +--- + +Only trim end of line for myst-directives, not both the start and end of lines. This is important for keeping indentation in code blocks. diff --git a/packages/markdown-it-myst/src/directives.ts b/packages/markdown-it-myst/src/directives.ts index cdc07435e..dc36073ca 100644 --- a/packages/markdown-it-myst/src/directives.ts +++ b/packages/markdown-it-myst/src/directives.ts @@ -56,7 +56,7 @@ function runDirectives(state: StateCore): boolean { body.shift(); bodyOffset++; } - const bodyString = body.join('\n').trim(); + const bodyString = body.join('\n').trimEnd(); const directiveOpen = new state.Token('parsed_directive_open', '', 1); directiveOpen.info = info; directiveOpen.hidden = true; diff --git a/packages/myst-parser/tests/directives/code.yml b/packages/myst-parser/tests/directives/code.yml index 76e733194..355eb3572 100644 --- a/packages/myst-parser/tests/directives/code.yml +++ b/packages/myst-parser/tests/directives/code.yml @@ -24,6 +24,34 @@ cases: value: |- # here is math 1+2 + - title: code-block with indentation + markdown: |- + ```{code-block} c + :linenos: true + :lineno-start: 2 + :emphasize-lines: 3 + for (int i = 0; i < 10; i++) { + /* do something */ + } + ``` + mdast: + type: root + children: + - type: mystDirective + name: code-block + args: c + options: + emphasize-lines: 3 + lineno-start: 2 + linenos: true + value: " for (int i = 0; i < 10; i++) {\n /* do something */\n }" + children: + - type: code + lang: c + showLineNumbers: true + startingLineNumber: 2 + emphasizeLines: [3] + value: " for (int i = 0; i < 10; i++) {\n /* do something */\n }" - title: code-block with name language options parses markdown: |- ```{code-block} python diff --git a/packages/myst-parser/tests/myst.spec.ts b/packages/myst-parser/tests/myst.spec.ts index b23069ac0..00169acfb 100644 --- a/packages/myst-parser/tests/myst.spec.ts +++ b/packages/myst-parser/tests/myst.spec.ts @@ -85,8 +85,10 @@ function stripPositions(tree: GenericParent) { return tree; } -function removeTightAnnotations(tree: GenericParent) { +function fixMystDirectives(tree: GenericParent) { selectAll('mystDirective', tree).forEach((node) => { + // Node markdown is trimmed + (node as any).value = (node as any).value?.trim(); // These are added on afterwards and we aren't taking them into account in myst spec delete (node as any).tight; }); @@ -115,7 +117,7 @@ describe('Testing myst --> mdast conversions', () => { test.each(mystCases)('%s', (_, { myst, mdast }) => { if (myst) { const mdastString = yaml.dump(mdast); - const newAst = removeTightAnnotations( + const newAst = fixMystDirectives( replaceMystCommentNodes( stripPositions( mystParse(myst, {