Skip to content

Commit

Permalink
Merge pull request #108 from lonekorean/pre-code-blocks
Browse files Browse the repository at this point in the history
<pre> code blocks
  • Loading branch information
lonekorean authored Feb 22, 2024
2 parents 6c8e0c8 + 25efa40 commit 4fb3f27
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/translator.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@ function initTurndownService() {
}
});

// convert <pre> into a code block with language when appropriate
turndownService.addRule('pre', {
filter: node => {
// a <pre> with <code> inside will already render nicely, so don't interfere
return node.nodeName === 'PRE' && !node.querySelector('code');
},
replacement: (content, node) => {
const language = node.getAttribute('data-wetm-language') || '';
return '\n\n```' + language + '\n' + node.textContent + '\n```\n\n';
}
});

return turndownService;
}

Expand All @@ -100,6 +112,10 @@ function getPostContent(post, turndownService, config) {
// by escaping angle brackets (will be unescaped during turndown conversion)
content = content.replace(/<(!--more( .*)?--)>/, '&lt;$1&gt;');

// some WordPress plugins specify a code language in an HTML comment above a
// <pre> block, save it to a data attribute so the "pre" rule can use it
content = content.replace(/(<!-- wp:.+? \{"language":"(.+?)"\} -->\r?\n<pre )/g, '$1data-wetm-language="$2" ');

// use turndown to convert HTML to Markdown
content = turndownService.turndown(content);

Expand Down

0 comments on commit 4fb3f27

Please sign in to comment.