Skip to content

Commit 23b1706

Browse files
authored
fix: do not add a newline to an empty code block (#4073)
* fix: do not add a newline to an empty code block Renderer.code appended a newline unconditionally, so a code block with no content rendered as <pre><code>\n</code></pre> instead of <pre><code></code></pre>. This fixes CommonMark examples 126, 130, 144 and 237. The spec suite did not catch it because htmlIsEqual leaves html-differ's ignoreWhitespaces at its default of true, and whitespace inside pre/code is significant, so all four were already reported as passing. * test: move the empty code block tests to test/specs/new Uses renderExact so the fixture compares exactly, which htmlIsEqual does not, and keeps the assertions out of marked.test.js.
1 parent df57534 commit 23b1706

3 files changed

Lines changed: 30 additions & 1 deletion

File tree

‎src/Renderer.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ export class _Renderer<ParserOutput = string, RendererOutput = string> {
2525
code({ text, lang, escaped }: Tokens.Code): RendererOutput {
2626
const langString = (lang || '').match(other.notSpaceStart)?.[0];
2727

28-
const code = text.replace(other.endingNewline, '') + '\n';
28+
// An empty code block has no content, so it must not gain a newline.
29+
const code = text ? text.replace(other.endingNewline, '') + '\n' : '';
2930

3031
if (!langString) {
3132
return '<pre><code>'
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<pre><code></code></pre>
2+
<p>sep</p>
3+
<pre><code class="language-;"></code></pre>
4+
<p>sep</p>
5+
<pre><code>x
6+
</code></pre>
7+
<p>sep</p>
8+
<pre><code></code></pre>

‎test/specs/new/empty_code_block.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
renderExact: true
3+
---
4+
```
5+
```
6+
7+
sep
8+
9+
````;
10+
````
11+
12+
sep
13+
14+
```
15+
x
16+
```
17+
18+
sep
19+
20+
```

0 commit comments

Comments
 (0)