Skip to content

Commit 16034f0

Browse files
authored
Fix double-escaping of non-highlighted code blocks in Astro-flavored markdown (#4169)
1 parent 9315ce6 commit 16034f0

3 files changed

Lines changed: 26 additions & 6 deletions

File tree

.changeset/strong-hotels-cross.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@astrojs/markdown-remark': patch
3+
---
4+
5+
Fix double-escaping of non-highlighted code blocks in Astro-flavored markdown

packages/markdown/remark/src/rehype-escape.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { visit } from 'unist-util-visit';
1+
import { visit, SKIP } from 'unist-util-visit';
22

33
export function escapeEntities(value: string): string {
44
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -14,8 +14,9 @@ export default function rehypeEscape(): any {
1414
visit(el, 'raw', (raw) => {
1515
raw.value = escapeEntities(raw.value);
1616
});
17+
// Do not visit children to prevent double escaping
18+
return SKIP;
1719
}
18-
return el;
1920
});
2021
};
2122
}

packages/markdown/remark/test/entities.test.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,25 @@ import { renderMarkdown } from '../dist/index.js';
22
import { expect } from 'chai';
33

44
describe('entities', () => {
5-
const renderAstroMd = (text) => renderMarkdown(text, { isAstroFlavoredMd: false });
6-
7-
it('should not unescape entities', async () => {
8-
const { code } = await renderAstroMd(`&lt;i&gt;This should NOT be italic&lt;/i&gt;`);
5+
it('should not unescape entities in regular Markdown', async () => {
6+
const { code } = await renderMarkdown(`&lt;i&gt;This should NOT be italic&lt;/i&gt;`, {
7+
isAstroFlavoredMd: false,
8+
});
99

1010
expect(code).to.equal(`<p>&#x3C;i>This should NOT be italic&#x3C;/i></p>`);
1111
});
12+
13+
it('should not escape entities in code blocks twice in Astro-flavored markdown', async () => {
14+
const { code } = await renderMarkdown(
15+
`\`\`\`astro\n<h1>{x && x.name || ''}!</h1>\n\`\`\``,
16+
{
17+
isAstroFlavoredMd: true,
18+
syntaxHighlight: false,
19+
}
20+
);
21+
22+
expect(code).to.equal(
23+
`<pre is:raw><code class="language-astro">&lt;h1&gt;{x &amp;&amp; x.name || ''}!&lt;/h1&gt;\n</code></pre>`
24+
);
25+
});
1226
});

0 commit comments

Comments
 (0)