Skip to content

Commit

Permalink
fix: fix preWrapper plugin (#157)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mister-Hope authored May 27, 2024
1 parent c3d22eb commit 28359b9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const preWrapperPlugin = (
md.renderer.rules.fence = (...args) => {
const result = rawFence(...args)

if (!preWrapper) {
if (!preWrapper || !result.startsWith('<pre')) {
return result
}

Expand Down
25 changes: 21 additions & 4 deletions plugins/plugin-shiki/src/node/markdown/preWrapperPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,42 @@ export const preWrapperPlugin = (
const rawFence = md.renderer.rules.fence!

md.renderer.rules.fence = (...args) => {
let result = rawFence(...args)

if (!result.startsWith('<pre')) {
return result
}

const [tokens, idx, options] = args
const token = tokens[idx]

// get token info
const info = token.info ? md.utils.unescapeAll(token.info).trim() : ''

const lang = resolveLanguage(info)
const title = resolveAttr(info, 'title') || lang
const languageClass = `${options.langPrefix}${lang}`

let result = rawFence(...args)

if (!preWrapper) {
// remove `<code>` attributes
/**
* remove `<code>` attributes
*
* In the source code of `markdown-it fence line 71, line 74`,
* `fence` writes `class="language-*"` onto the `code` element,
* whereas in past versions, `vuepress` wrote it on the `pre` element.
* Therefore, this behavior needs to be reset.
*
* Even though `shiki` directly returns the contents within `<pre>`
* at `line 48` of `markdown-it`, I believe it is still prudent to make this adjustment.
*
* @see https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.mjs
*/
result = result.replace(/<code[^]*?>/, '<code>')
result = `<pre class="${languageClass}"${result.slice('<pre'.length)}`
return result
}

const title = resolveAttr(info, 'title') || lang

return `<div class="${languageClass}" data-ext="${lang}" data-title="${title}">${result}</div>`
}
}

0 comments on commit 28359b9

Please sign in to comment.