mirror of
https://github.com/wahyd4/vuepress.git
synced 2026-08-13 15:25:51 +10:00
40 lines
1011 B
JavaScript
40 lines
1011 B
JavaScript
const chalk = require('chalk')
|
|
const prism = require('prismjs')
|
|
const loadLanguages = require('prismjs/components/index')
|
|
const escapeHtml = require('escape-html')
|
|
|
|
// required to make embedded highlighting work...
|
|
loadLanguages(['markup', 'css', 'javascript'])
|
|
|
|
function wrap (code, lang) {
|
|
if (lang === 'text') {
|
|
code = escapeHtml(code)
|
|
}
|
|
return `<pre v-pre class="language-${lang}"><code>${code}</code></pre>`
|
|
}
|
|
|
|
module.exports = (str, lang) => {
|
|
if (!lang) {
|
|
return wrap(str, 'text')
|
|
}
|
|
const rawLang = lang
|
|
if (lang === 'vue' || lang === 'html') {
|
|
lang = 'markup'
|
|
}
|
|
if (lang === 'md') {
|
|
lang = 'markdown'
|
|
}
|
|
if (!prism.languages[lang]) {
|
|
try {
|
|
loadLanguages([lang])
|
|
} catch (e) {
|
|
console.log(chalk.yellow(`[vuepress] Syntax highlight for language "${lang}" is not supported.`))
|
|
}
|
|
}
|
|
if (prism.languages[lang]) {
|
|
const code = prism.highlight(str, prism.languages[lang], lang)
|
|
return wrap(code, rawLang)
|
|
}
|
|
return wrap(str, 'text')
|
|
}
|