import marked from 'marked' import Prism from 'prismjs' import { helper as helperTpl } from './tpl' import { slugify, clearSlugCache } from './slugify' import { emojify } from './emojify' import { toURL } from '../route/hash' import { isFn, merge, cached } from '../util/core' let markdownCompiler = marked let contentBase = '' let renderer = new marked.Renderer() const toc = [] /** * Compile markdown content */ export const markdown = cached(text => { let html = '' if (!text) return text html = markdownCompiler(text) html = emojify(html) clearSlugCache() return html }) markdown.renderer = renderer markdown.init = function (config = {}, context = window.location.pathname) { contentBase = context if (isFn(config)) { markdownCompiler = config(marked, renderer) } else { renderer = merge(renderer, config.renderer) marked.setOptions(merge(config, { renderer })) } } /** * render anchor tag * @link https://github.com/chjj/marked#overriding-renderer-methods */ renderer.heading = function (text, level) { const slug = slugify(text) const url = toURL(contentBase, { id: slug }) toc.push({ level, slug: url, title: text }) return `${text}` } // highlight code renderer.code = function (code, lang = '') { const hl = Prism.highlight(code, Prism.languages[lang] || Prism.languages.markup) return `
${hl}
` } renderer.link = function (href, title, text) { if (!/:|(\/{2})/.test(href)) { // TODO href = `#/${href}`.replace(/\/+/g, '/') } return `${text}` } renderer.paragraph = function (text) { if (/^!>/.test(text)) { return helperTpl('tip', text) } else if (/^\?>/.test(text)) { return helperTpl('warn', text) } return `

${text}

` } renderer.image = function (href, title, text) { // TODO // get base path // const url = /:|(\/{2})/.test(href) ? href : ($docsify.basePath + href).replace(/\/+/g, '/') // const titleHTML = title ? ` title="${title}"` : '' // return `${text}` } /** * Compile sidebar */ export function sidebar (text) { }