|
| 1 | +const fs = require('fs') |
| 2 | + |
| 3 | +module.exports = function snippet (md, options = {}) { |
| 4 | + const root = options.root || process.cwd() |
| 5 | + function parser (state, startLine, endLine, silent) { |
| 6 | + const CH = '<'.charCodeAt(0) |
| 7 | + const pos = state.bMarks[startLine] + state.tShift[startLine] |
| 8 | + const max = state.eMarks[startLine] |
| 9 | + |
| 10 | + // if it's indented more than 3 spaces, it should be a code block |
| 11 | + if (state.sCount[startLine] - state.blkIndent >= 4) { |
| 12 | + return false |
| 13 | + } |
| 14 | + |
| 15 | + for (let i = 0; i < 3; ++i) { |
| 16 | + const ch = state.src.charCodeAt(pos + i) |
| 17 | + if (ch !== CH || pos + i >= max) return false |
| 18 | + } |
| 19 | + |
| 20 | + if (silent) { |
| 21 | + return true |
| 22 | + } |
| 23 | + |
| 24 | + const start = pos + 3 |
| 25 | + const end = state.skipSpacesBack(max, pos) |
| 26 | + const rawPath = state.src.slice(start, end).trim().replace(/^@/, root) |
| 27 | + const filename = rawPath.split(/[{:\s]/).shift() |
| 28 | + const content = fs.existsSync(filename) ? fs.readFileSync(filename).toString() : 'Not found: ' + filename |
| 29 | + const meta = rawPath.replace(filename, '') |
| 30 | + |
| 31 | + state.line = startLine + 1 |
| 32 | + |
| 33 | + const token = state.push('fence', 'code', 0) |
| 34 | + token.info = filename.split('.').pop() + meta |
| 35 | + token.content = content |
| 36 | + token.markup = '```' |
| 37 | + token.map = [startLine, startLine + 1] |
| 38 | + |
| 39 | + return true |
| 40 | + } |
| 41 | + |
| 42 | + md.block.ruler.before('fence', 'snippet', parser) |
| 43 | +} |
0 commit comments