Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix deep nested code in pre #486

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions src/commonmark-rules.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,14 @@ rules.indentedCodeBlock = {
return (
options.codeBlockStyle === 'indented' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
node.querySelector('code')
)
},

replacement: function (content, node, options) {
return (
'\n\n ' +
node.firstChild.textContent.replace(/\n/g, '\n ') +
node.querySelector('code').textContent.replace(/\n/g, '\n ') +
'\n\n'
)
}
Expand All @@ -103,15 +102,15 @@ rules.fencedCodeBlock = {
return (
options.codeBlockStyle === 'fenced' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
node.querySelector('code')
)
},

replacement: function (content, node, options) {
var className = node.firstChild.getAttribute('class') || ''
var codeElement = node.querySelector('code')
var className = codeElement.getAttribute('class') || ''
var language = (className.match(/language-(\S+)/) || [null, ''])[1]
var code = node.firstChild.textContent
var code = codeElement.textContent

var fenceChar = options.fence.charAt(0)
var fenceSize = 3
Expand Down
18 changes: 18 additions & 0 deletions test/turndown-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,21 @@ test('remove elements are overridden by keep', function (t) {
'Hello <del>world</del><ins>World</ins>'
)
})

test('deep nested code in pre is converted to code block (indented)', function (t) {
t.plan(1)
var turndownService = new TurndownService()
t.equal(turndownService.turndown(
'<pre><div><code>Hi</code></div></pre>'),
' Hi'
)
})

test('deep nested code in pre is converted to code block (fenced)', function (t) {
t.plan(1)
var turndownService = new TurndownService({ codeBlockStyle: 'fenced' })
t.equal(turndownService.turndown(
'<pre><div><code>Hi</code></div></pre>'),
'```\nHi\n```'
)
})