Skip to content

Commit

Permalink
Fixed multiple ticks/tildes inside code blocks.
Browse files Browse the repository at this point in the history
  • Loading branch information
fredck committed Feb 25, 2020
1 parent cae7098 commit a24c58b
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/commonmark-rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,25 @@ rules.fencedCodeBlock = {
replacement: function (content, node, options) {
var className = node.firstChild.className || ''
var language = (className.match(/language-(\S+)/) || [null, ''])[1]
var code = node.firstChild.textContent

var fenceChar = options.fence === '~~~' ? '~' : '`'
var fenceSize = 3
var fenceInCodeRegex = new RegExp('^' + fenceChar + '{3,}', 'gm')

var match
while ((match = fenceInCodeRegex.exec(code))) {
if (match[ 0 ].length >= fenceSize) {
fenceSize = match[ 0 ].length + 1
}
}

var fence = fenceChar.repeat(fenceSize)

return (
'\n\n' + options.fence + language + '\n' +
node.firstChild.textContent +
'\n' + options.fence + '\n\n'
'\n\n' + fence + language + '\n' +
code.replace(/^\n|\n$/g, '') +
'\n' + fence + '\n\n'
)
}
}
Expand Down
45 changes: 45 additions & 0 deletions test/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,51 @@ <h2>This is a header.</h2>
<pre class="expected">Foo Bar</pre>
</div>

<div class="case" data-name="triple tildes inside code" data-options='{"codeBlockStyle": "fenced", "fence": "~~~"}'>
<div class="input">
<pre><code>
~~~
Code
~~~
</code></pre>
</div>
<pre class="expected">~~~~
~~~
Code
~~~
~~~~</pre>
</div>

<div class="case" data-name="triple ticks inside code" data-options='{"codeBlockStyle": "fenced", "fence": "```"}'>
<div class="input">
<pre><code>
```
Code
```
</code></pre>
</div>
<pre class="expected">````
```
Code
```
````</pre>
</div>

<div class="case" data-name="four ticks inside code" data-options='{"codeBlockStyle": "fenced", "fence": "```"}'>
<div class="input">
<pre><code>
````
Code
````
</code></pre>
</div>
<pre class="expected">`````
````
Code
````
`````</pre>
</div>

<!-- /TEST CASES -->

<script src="turndown-test.browser.js"></script>
Expand Down

0 comments on commit a24c58b

Please sign in to comment.