-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
highlightLines.ts
74 lines (57 loc) · 1.9 KB
/
highlightLines.ts
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
// Modified from https://github.com/egoist/markdown-it-highlight-lines
import MarkdownIt from 'markdown-it'
const RE = /{([\d,-]+)}/
const wrapperRE = /^<pre .*?><code>/
export const highlightLinePlugin = (md: MarkdownIt) => {
const fence = md.renderer.rules.fence!
md.renderer.rules.fence = (...args) => {
const [tokens, idx, options] = args
const token = tokens[idx]
// due to use of markdown-it-attrs, the {0} syntax would have been
// converted to attrs on the token
const attr = token.attrs && token.attrs[0]
let lines = null
if (!attr) {
// markdown-it-attrs maybe disabled
const rawInfo = token.info
if (!rawInfo || !RE.test(rawInfo)) {
return fence(...args)
}
const langName = rawInfo.replace(RE, '').trim()
// ensure the next plugin get the correct lang
token.info = langName
lines = RE.exec(rawInfo)![1]
}
if (!lines) {
lines = attr![0]
if (!lines || !/[\d,-]+/.test(lines)) {
return fence(...args)
}
}
const lineNumbers = lines
.split(',')
.map((v) => v.split('-').map((v) => parseInt(v, 10)))
const code = options.highlight
? options.highlight(token.content, token.info, '')
: token.content
const rawCode = code.replace(wrapperRE, '')
const highlightLinesCode = rawCode
.split('\n')
.map((split, index) => {
const lineNumber = index + 1
const inRange = lineNumbers.some(([start, end]) => {
if (start && end) {
return lineNumber >= start && lineNumber <= end
}
return lineNumber === start
})
if (inRange) {
return `<div class="highlighted"> </div>`
}
return '<br>'
})
.join('')
const highlightLinesWrapperCode = `<div class="highlight-lines">${highlightLinesCode}</div>`
return highlightLinesWrapperCode + code
}
}