Skip to content

Commit

Permalink
Fix double-escaping of non-highlighted code blocks in Astro-flavored …
Browse files Browse the repository at this point in the history
…markdown (#4169)
  • Loading branch information
hippotastic committed Aug 5, 2022
1 parent 9315ce6 commit 16034f0
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/strong-hotels-cross.md
@@ -0,0 +1,5 @@
---
'@astrojs/markdown-remark': patch
---

Fix double-escaping of non-highlighted code blocks in Astro-flavored markdown
5 changes: 3 additions & 2 deletions packages/markdown/remark/src/rehype-escape.ts
@@ -1,4 +1,4 @@
import { visit } from 'unist-util-visit';
import { visit, SKIP } from 'unist-util-visit';

export function escapeEntities(value: string): string {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
Expand All @@ -14,8 +14,9 @@ export default function rehypeEscape(): any {
visit(el, 'raw', (raw) => {
raw.value = escapeEntities(raw.value);
});
// Do not visit children to prevent double escaping
return SKIP;
}
return el;
});
};
}
22 changes: 18 additions & 4 deletions packages/markdown/remark/test/entities.test.js
Expand Up @@ -2,11 +2,25 @@ import { renderMarkdown } from '../dist/index.js';
import { expect } from 'chai';

describe('entities', () => {
const renderAstroMd = (text) => renderMarkdown(text, { isAstroFlavoredMd: false });

it('should not unescape entities', async () => {
const { code } = await renderAstroMd(`&lt;i&gt;This should NOT be italic&lt;/i&gt;`);
it('should not unescape entities in regular Markdown', async () => {
const { code } = await renderMarkdown(`&lt;i&gt;This should NOT be italic&lt;/i&gt;`, {
isAstroFlavoredMd: false,
});

expect(code).to.equal(`<p>&#x3C;i>This should NOT be italic&#x3C;/i></p>`);
});

it('should not escape entities in code blocks twice in Astro-flavored markdown', async () => {
const { code } = await renderMarkdown(
`\`\`\`astro\n<h1>{x && x.name || ''}!</h1>\n\`\`\``,
{
isAstroFlavoredMd: true,
syntaxHighlight: false,
}
);

expect(code).to.equal(
`<pre is:raw><code class="language-astro">&lt;h1&gt;{x &amp;&amp; x.name || ''}!&lt;/h1&gt;\n</code></pre>`
);
});
});

0 comments on commit 16034f0

Please sign in to comment.