-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (36 loc) · 1.07 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
46
47
48
/**
* The remark plugin for supporting numbered headings ids
* @author iloveip
*/
var visit = require('unist-util-visit')
module.exports = autoHeadingIds
var deafultPrefix = 'id'
function autoHeadingIds(options) {
var settings = options || {}
var prefix = settings.prefix || deafultPrefix
return transformer
function transformer(ast) {
var count = 1
visit(ast, 'heading', visitor)
function visitor(node) {
var data = node.data || (node.data = {})
var props = data.hProperties || (data.hProperties = {})
let lastChild = node.children[node.children.length - 1]
if (lastChild && lastChild.type === 'text') {
let string = lastChild.value.replace(/ +$/, '')
let matched = string.match(/ {#([^]+?)}$/)
if (matched) {
let id = matched[1]
if (id.length) {
props.id = id
string = string.substring(0, matched.index)
lastChild.value = string
}
} else {
props.id = prefix + String(count)
count++
}
}
}
}
}