Skip to content

Commit

Permalink
refactor: hoist pre wrapper as a standalone plugin.
Browse files Browse the repository at this point in the history
  • Loading branch information
ulivz committed May 13, 2018
1 parent 1b9012e commit 45a3df5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
14 changes: 9 additions & 5 deletions lib/markdown/highlightLines.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@ module.exports = md => {
md.renderer.rules.fence = (...args) => {
const [tokens, idx, options] = args
const token = tokens[idx]
const langName = token.info.replace(RE, '').trim()

if (!token.info || !RE.test(token.info)) {
return `<div class="language-${langName}">${fence(...args)}</div>`
const rawInfo = token.info
if (!rawInfo || !RE.test(rawInfo)) {
return fence(...args)
}

const lineNumbers = RE.exec(token.info)[1]
const langName = rawInfo.replace(RE, '').trim()
// ensure the next plugin get the correct lang.
token.info = langName

const lineNumbers = RE.exec(rawInfo)[1]
.split(',')
.map(v => v.split('-').map(v => parseInt(v, 10)))

Expand Down Expand Up @@ -51,6 +55,6 @@ module.exports = md => {
highlightedCode += `${split.code}\n`
}
})
return `<div class="language-${langName}">${highlightedCode}</div>`
return highlightedCode
}
}
2 changes: 2 additions & 0 deletions lib/markdown/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const highlight = require('./highlight')
const highlightLines = require('./highlightLines')
const preWrapper = require('./preWrapper')
const component = require('./component')
const hoistScriptStyle = require('./hoist')
const convertRouterLink = require('./link')
Expand All @@ -21,6 +22,7 @@ module.exports = ({ markdown = {}} = {}) => {
// custom plugins
.use(component)
.use(highlightLines)
.use(preWrapper)
.use(convertRouterLink, Object.assign({
target: '_blank',
rel: 'noopener noreferrer'
Expand Down
11 changes: 11 additions & 0 deletions lib/markdown/preWrapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// markdown-it plugin for wrapping <pre> ... </pre>.

module.exports = md => {
const fence = md.renderer.rules.fence
md.renderer.rules.fence = (...args) => {
const [tokens, idx] = args
const token = tokens[idx]
const rawCode = fence(...args)
return `<!--beforebegin--><div class="language-${token.info.trim()}"><!--afterbegin-->${rawCode}<!--beforeend--></div><!--afterend-->`
}
}

0 comments on commit 45a3df5

Please sign in to comment.