Skip to content

Commit 29978bf

Browse files
committed
feat: Add support to import files as code fence
1 parent 637f634 commit 29978bf

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

lib/markdown/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const component = require('./component')
66
const hoistScriptStyle = require('./hoist')
77
const convertRouterLink = require('./link')
88
const containers = require('./containers')
9+
const snippet = require('./snippet')
910
const emoji = require('markdown-it-emoji')
1011
const anchor = require('markdown-it-anchor')
1112
const toc = require('markdown-it-table-of-contents')
@@ -24,6 +25,7 @@ module.exports = ({ markdown = {}} = {}) => {
2425
.use(component)
2526
.use(highlightLines)
2627
.use(preWrapper)
28+
.use(snippet)
2729
.use(convertRouterLink, Object.assign({
2830
target: '_blank',
2931
rel: 'noopener noreferrer'

lib/markdown/snippet.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
const fs = require('fs')
2+
3+
module.exports = function codeFrame(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+
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', 'code-frame', parser)
43+
}

0 commit comments

Comments
 (0)