-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
89 lines (71 loc) · 2.17 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
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
82
83
84
85
86
87
88
89
var VFile = require('vfile')
var path = require('path')
var fs = require('fs')
var parseInclude = /^@include (.*)(\n|$)/
module.exports = function (options) {
var proc = this;
options = options || {}
var cwd = options.cwd || process.cwd()
var prt = proc.Parser.prototype
prt.blockTokenizers.include = tokenizer
prt.blockMethods.unshift('include')
return function transformer(ast, file) {
var children = ast.children
for (var i = 0; i < children.length; i++) {
var child = children[i]
if (child.type === 'include') {
// Load file and create VFile
// console.log(cwd, file)
// var file = toFile(path.join(file.dirname || cwd, child.value))
// Parse vfile contents
// var parser = new processor.Parser(file, null, processor)
var root = proc.runSync(proc.parse(
toFile(path.join(child.source.dirname || cwd, child.value))
))
// Split and merge the head and tail around the new children
var head = children.slice(0, i)
var tail = children.slice(i + 1)
children = head.concat(root.children).concat(tail)
// Remember to update the offset!
i += root.children.length - 1
}
}
ast.children = children
}
}
function tokenizer (eat, value, silent) {
var self = this
var settings = self.options
var length = value.length + 1
var index = -1
var now = eat.now()
var node
if (silent && parseInclude.test(value)) {
return true
}
// Replace all lines beginning with @include
while (parseInclude.test(value)) {
var file = value.match(parseInclude)[1]
var frag = '@include ' + file
value = value.slice(frag.length)
eat(frag)({
type: 'include',
source: this.file,
value: file
})
}
return node
}
function toFile(full) {
return new VFile({path: full, contents: loadContent(full).toString('utf8')})
}
function loadContent(file) {
// console.log('loading', file)
try { return fs.readFileSync(file) }
catch (e) {}
try { return fs.readFileSync(file + '.md') }
catch (e) {}
try { return fs.readFileSync(file + '.markdown') }
catch (e) {}
throw new Error('Unable to include ' + file)
}