-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
highlight-code.js
81 lines (73 loc) · 2.47 KB
/
highlight-code.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const Prism = require(`prismjs`)
const loadPrismLanguage = require(`./load-prism-language`)
const handleDirectives = require(`./directives`)
const escapeHTML = require(`./escape-html`)
const unsupportedLanguages = new Set()
require(`prismjs/components/prism-diff`)
require(`prismjs/plugins/diff-highlight/prism-diff-highlight`)
module.exports = (
language,
code,
additionalEscapeCharacters = {},
lineNumbersHighlight = [],
noInlineHighlight = false,
diffLanguage = null
) => {
// (Try to) load languages on demand.
if (!Prism.languages[language]) {
try {
loadPrismLanguage(language)
} catch (e) {
// Language wasn't loaded so let's bail.
let message = null
switch (language) {
case `none`:
return code // Don't escape if set to none.
case `text`:
message = noInlineHighlight
? `code block language not specified in markdown.`
: `code block or inline code language not specified in markdown.`
break
default:
message = `unable to find prism language '${language}' for highlighting.`
}
const lang = language.toLowerCase()
if (!unsupportedLanguages.has(lang)) {
console.warn(message, `applying generic code block`)
unsupportedLanguages.add(lang)
}
return escapeHTML(code, additionalEscapeCharacters)
}
}
// (Try to) load diffLanguage on demand.
if (diffLanguage && !Prism.languages[diffLanguage]) {
try {
loadPrismLanguage(diffLanguage)
} catch (e) {
const message = `unable to find prism language '${diffLanguage}' for highlighting.`
const lang = diffLanguage.toLowerCase()
if (!unsupportedLanguages.has(lang)) {
console.warn(message, `applying generic code block`)
unsupportedLanguages.add(lang)
}
// Ignore diffLanguage when it does not exist.
diffLanguage = null
}
}
const grammar = Prism.languages[language]
const highlighted = Prism.highlight(
code,
grammar,
diffLanguage ? `${language}-${diffLanguage}` : language
)
const codeSplits = handleDirectives(highlighted, lineNumbersHighlight)
let finalCode = ``
const lastIdx = codeSplits.length - 1 // Don't add back the new line character after highlighted lines
// as they need to be display: block and full-width.
codeSplits.forEach((split, idx) => {
finalCode += split.highlight
? split.code
: `${split.code}${idx == lastIdx ? `` : `\n`}`
})
return finalCode
}