-
Notifications
You must be signed in to change notification settings - Fork 30
/
index.js
45 lines (36 loc) · 1.05 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const hljs = require('highlight.js')
const maybe = f => {
try {
return f()
} catch (e) {
return false
}
}
// Highlight with given language.
const highlight = (code, lang) =>
maybe(() => hljs.highlight(lang, code, true).value) || ''
// Highlight with given language or automatically.
const highlightAuto = (code, lang) =>
lang
? highlight(code, lang)
: maybe(() => hljs.highlightAuto(code).value) || ''
// Wrap a render function to add `hljs` class to code blocks.
const wrap = render =>
function (...args) {
return render.apply(this, args)
.replace('<code class="', '<code class="hljs ')
.replace('<code>', '<code class="hljs">')
}
const highlightjs = (md, opts) => {
opts = Object.assign({}, highlightjs.defaults, opts)
md.options.highlight = opts.auto ? highlightAuto : highlight
md.renderer.rules.fence = wrap(md.renderer.rules.fence)
if (opts.code) {
md.renderer.rules.code_block = wrap(md.renderer.rules.code_block)
}
}
highlightjs.defaults = {
auto: true,
code: true
}
module.exports = highlightjs