aboutsummaryrefslogtreecommitdiff
path: root/node_modules/vuepress/lib/markdown/snippet.js
blob: a677e12f77ef2c769c0ab3aa2ecce3e2d3915906 (plain)
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
const fs = require('fs')

module.exports = function snippet (md, options = {}) {
  const root = options.root || process.cwd()
  function parser (state, startLine, endLine, silent) {
    const CH = '<'.charCodeAt(0)
    const pos = state.bMarks[startLine] + state.tShift[startLine]
    const max = state.eMarks[startLine]

    // if it's indented more than 3 spaces, it should be a code block
    if (state.sCount[startLine] - state.blkIndent >= 4) {
      return false
    }

    for (let i = 0; i < 3; ++i) {
      const ch = state.src.charCodeAt(pos + i)
      if (ch !== CH || pos + i >= max) return false
    }

    if (silent) {
      return true
    }

    const start = pos + 3
    const end = state.skipSpacesBack(max, pos)
    const rawPath = state.src.slice(start, end).trim().replace(/^@/, root)
    const filename = rawPath.split(/[{:\s]/).shift()
    const content = fs.existsSync(filename) ? fs.readFileSync(filename).toString() : 'Not found: ' + filename
    const meta = rawPath.replace(filename, '')

    state.line = startLine + 1

    const token = state.push('fence', 'code', 0)
    token.info = filename.split('.').pop() + meta
    token.content = content
    token.markup = '```'
    token.map = [startLine, startLine + 1]

    return true
  }

  md.block.ruler.before('fence', 'snippet', parser)
}