Skip to content

Build your personal knowledge base with Trilium Notes

Add highlighted code block rules

Dom Christie611f0f037c4e
diff --git a/src/gfm.js b/src/gfm.js
index e70db46490..69d25b4b70 100644
--- a/src/gfm.js
+++ b/src/gfm.js
@@ -1,9 +1,15 @@
+import highlightedCodeBlock from './highlighted-code-block'
import strikethrough from './strikethrough'
import tables from './tables'
import taskListItems from './task-list-items'
function gfm (turndownService) {
- turndownService.use([strikethrough, tables, taskListItems])
+ turndownService.use([
+ highlightedCodeBlock,
+ strikethrough,
+ tables,
+ taskListItems
+ ])
}
-export { gfm, strikethrough, tables, taskListItems }
+export { gfm, highlightedCodeBlock, strikethrough, tables, taskListItems }
diff --git a/src/highlighted-code-block.js b/src/highlighted-code-block.js
new file mode 100644
index 0000000000..97052de574
--- /dev/null
+++ b/src/highlighted-code-block.js
@@ -0,0 +1,25 @@
+var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/
+
+export default function highlightedCodeBlock (turndownService) {
+ turndownService.addRule('highlightedCodeBlock', {
+ filter: function (node) {
+ var firstChild = node.firstChild
+ return (
+ node.nodeName === 'DIV' &&
+ highlightRegExp.test(node.className) &&
+ firstChild &&
+ firstChild.nodeName === 'PRE'
+ )
+ },
+ replacement: function (content, node, options) {
+ var className = node.className || ''
+ var language = (className.match(highlightRegExp) || [null, ''])[1]
+
+ return (
+ '\n\n' + options.fence + language + '\n' +
+ node.firstChild.textContent +
+ '\n' + options.fence + '\n\n'
+ )
+ }
+ })
+}
diff --git a/test/index.html b/test/index.html
index 659e1d0ee3..885f738f03 100644
--- a/test/index.html
+++ b/test/index.html
@@ -273,6 +273,28 @@
| --- |</pre>
</div>
+<div class="case" data-name="highlighted code block with html">
+ <div class="input">
+ <div class="highlight highlight-text-html-basic">
+ <pre>&lt;<span class="pl-ent">p</span>&gt;Hello world&lt;/<span class="pl-ent">p</span>&gt;</pre>
+ </div>
+ </div>
+ <pre class="expected">```html
+&lt;p&gt;Hello world&lt;/p&gt;
+```</pre>
+</div>
+
+<div class="case" data-name="highlighted code block with js">
+ <div class="input">
+ <div class="highlight highlight-source-js">
+ <pre>;(<span class="pl-k">function</span> () {})()</pre>
+ </div>
+ </div>
+ <pre class="expected">```js
+;(function () {})()
+```</pre>
+</div>
+
<!-- /TEST CASES -->
<script src="turndown-plugin-gfm-test.browser.js"></script>