forked from camelaissani/markdown-it-include
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
41 lines (32 loc) · 1.3 KB
/
index.js
File metadata and controls
41 lines (32 loc) · 1.3 KB
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
'use strict';
var path = require('path'),
fs = require('fs');
var INCLUDE_RE = /\!{3}\s*include\s*\(\s*(.+?)\s*\)\s*\!{3}/i;
module.exports = function include_plugin(md, basedir) {
var filesProcessed;
function _replaceIncludeByContent(src, rootdir, parentFilePath) {
var cap, filePath, mdSrc, indexOfCircularRef;
// store parent file path to check circular references
if (parentFilePath) {
filesProcessed.push(parentFilePath);
}
while ((cap = INCLUDE_RE.exec(src))) {
filePath = path.resolve(rootdir, cap[1]);
// check if circular reference
indexOfCircularRef = filesProcessed.indexOf(filePath);
if (indexOfCircularRef !== -1) {
throw new Error('Circular reference between ' + filePath + ' and ' + filesProcessed[indexOfCircularRef]);
}
// replace include by file content
mdSrc = _replaceIncludeByContent(fs.readFileSync(filePath, 'utf8'), path.dirname(filePath), filePath).trim();
src = src.slice(0, cap.index) + mdSrc + src.slice(cap.index + cap[0].length, src.length);
}
return src;
}
function _includeFileParts(state) {
var rootdir = basedir || '.';
filesProcessed = [];
state.src = _replaceIncludeByContent(state.src, rootdir);
}
md.core.ruler.before('normalize', 'include', _includeFileParts);
};