UNPKG

markdown-it-prism

Version:

Highlights code blocks in markdown-it using Prism.

304 lines (289 loc) 15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = markdownItPrism; var _prismjs = _interopRequireDefault(require("prismjs")); var _components = _interopRequireDefault(require("prismjs/components/")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } const SPECIFIED_LANGUAGE_META_KEY = 'de.joshuagleitze.markdown-it-prism.specifiedLanguage'; const DEFAULTS = { highlightInlineCode: false, plugins: [], init: () => { // do nothing by default }, defaultLanguageForUnknown: undefined, defaultLanguageForUnspecified: undefined, defaultLanguage: undefined }; /** * Loads the provided `lang` into prism. * * @param lang * Code of the language to load. * @return The Prism language object for the provided {@code lang} code. {@code undefined} if the language is not known to Prism. */ function loadPrismLang(lang) { if (!lang) return undefined; let langObject = _prismjs.default.languages[lang]; if (langObject === undefined) { (0, _components.default)([lang]); langObject = _prismjs.default.languages[lang]; } return langObject; } /** * Loads the provided Prism plugin. * @param name * Name of the plugin to load. * @throws {Error} If there is no plugin with the provided `name`. */ function loadPrismPlugin(name) { try { // eslint-disable-next-line @typescript-eslint/no-require-imports require(`prismjs/plugins/${name}/prism-${name}`); } catch (cause) { throw new Error(`Cannot load Prism plugin "${name}". Please check the spelling.`, { cause }); } } /** * Select the language to use for highlighting, based on the provided options and the specified language. * * @param options * The options that were used to initialise the plugin. * @param lang * Code of the language to highlight the text in. * @return The name of the language to use and the Prism language object for that language. */ function selectLanguage(options, lang) { let langToUse = lang; if (langToUse === '' && options.defaultLanguageForUnspecified !== undefined) { langToUse = options.defaultLanguageForUnspecified; } let prismLang = loadPrismLang(langToUse); if (prismLang === undefined && options.defaultLanguageForUnknown !== undefined) { langToUse = options.defaultLanguageForUnknown; prismLang = loadPrismLang(langToUse); } return [langToUse, prismLang]; } /** * Highlights the provided text using Prism. * * @param markdownit * The markdown-it instance. * @param options * The options that have been used to initialise the plugin. * @param text * The text to highlight. * @param lang * Code of the language to highlight the text in. * @return If Prism knows the language that {@link selectLanguage} returns for `lang`, the `text` highlighted for that language. Otherwise, `text` * html-escaped. */ function highlight(markdownit, options, text, lang) { return highlightWithSelectedLanguage(markdownit, options, text, selectLanguage(options, lang)); } /** * Highlights the provided text using Prism. * * @param markdownit * The markdown-it instance. * @param options * The options that have been used to initialise the plugin. * @param text * The text to highlight. * @param lang * The selected Prism language to use for highlighting. * @return If Prism knows the language that {@link selectLanguage} returns for `lang`, the `text` highlighted for that language. Otherwise, `text` * html-escaped. */ function highlightWithSelectedLanguage(markdownit, options, text, [langToUse, prismLang]) { return prismLang ? _prismjs.default.highlight(text, prismLang, langToUse) : markdownit.utils.escapeHtml(text); } /** * Construct the class name for the provided `lang`. * * @param markdownit * The markdown-it instance. * @param lang * The selected language. * @return the class to use for `lang`. */ function languageClass(markdownit, lang) { return markdownit.options.langPrefix + lang; } /** * A {@link RuleCore} that searches for and extracts language specifications on inline code tokens. */ function inlineCodeLanguageRule(state) { var _iterator = _createForOfIteratorHelper(state.tokens), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { const inlineToken = _step.value; if (inlineToken.type === 'inline' && inlineToken.children !== null) { var _iterator2 = _createForOfIteratorHelper(inlineToken.children.entries()), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { const _step2$value = _slicedToArray(_step2.value, 2), index = _step2$value[0], token = _step2$value[1]; if (token.type === 'code_inline' && index + 1 < inlineToken.children.length) { extractInlineCodeSpecifiedLanguage(token, inlineToken.children[index + 1]); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } /** * Searches for a language specification after an inline code token (e.g. ``{language=cpp}). If present, extracts the language, sets * it on `inlineCodeToken`’s meta, and removes the specification. * * @param inlineCodeToken * The inline code token for which to extract the language. * @param followingToken * The token immediately following the `inlineCodeToken`. */ function extractInlineCodeSpecifiedLanguage(inlineCodeToken, followingToken) { const languageSpecificationMatch = followingToken.content.match(/^\{((?:[^\s}]+\s)*)language=([^\s}]+)((?:\s[^\s}]+)*)}/); if (languageSpecificationMatch !== null) { inlineCodeToken.meta = _objectSpread(_objectSpread({}, inlineCodeToken.meta), {}, { [SPECIFIED_LANGUAGE_META_KEY]: languageSpecificationMatch[2] }); followingToken.content = followingToken.content.slice(languageSpecificationMatch[0].length); if (languageSpecificationMatch[1] || languageSpecificationMatch[3]) { followingToken.content = `{${languageSpecificationMatch[1] || ''}${(languageSpecificationMatch[3] || ' ').slice(1)}}${followingToken.content}`; } } } /** * Patch the `<pre>` and `<code>` tags produced by the `existingRule` for fenced code blocks. * * @param markdownit * The markdown-it instance. * @param options * The options that have been used to initialise the plugin. * @param existingRule * The previously configured render rule for fenced code blocks. */ function applyCodeAttributes(markdownit, options, existingRule) { return (tokens, idx, renderOptions, env, self) => { const fenceToken = tokens[idx]; const info = fenceToken.info ? markdownit.utils.unescapeAll(fenceToken.info).trim() : ''; const lang = info.split(/(\s+)/g)[0]; const _selectLanguage = selectLanguage(options, lang), _selectLanguage2 = _slicedToArray(_selectLanguage, 1), langToUse = _selectLanguage2[0]; if (!langToUse) { return existingRule(tokens, idx, renderOptions, env, self); } else { fenceToken.info = langToUse; const existingResult = existingRule(tokens, idx, renderOptions, env, self); const langClass = languageClass(markdownit, markdownit.utils.escapeHtml(langToUse)); return existingResult.replace(/<((?:pre|code)[^>]*?)(?:\s+class="([^"]*)"([^>]*))?>/g, (match, tagStart, existingClasses, tagEnd) => existingClasses !== null && existingClasses !== void 0 && existingClasses.includes(langClass) ? match : `<${tagStart} class="${existingClasses ? `${existingClasses} ` : ''}${langClass}"${tagEnd || ''}>`); } }; } /** * Renders inline code tokens by highlighting them with Prism. * * @param markdownit * The markdown-it instance. * @param options * The options that have been used to initialise the plugin. * @param existingRule * The previously configured render rule for inline code. */ function renderInlineCode(markdownit, options, existingRule) { return (tokens, idx, renderOptions, env, self) => { const inlineCodeToken = tokens[idx]; const specifiedLanguage = inlineCodeToken.meta ? inlineCodeToken.meta[SPECIFIED_LANGUAGE_META_KEY] || '' : ''; const _selectLanguage3 = selectLanguage(options, specifiedLanguage), _selectLanguage4 = _slicedToArray(_selectLanguage3, 2), langToUse = _selectLanguage4[0], prismLang = _selectLanguage4[1]; if (!langToUse) { return existingRule(tokens, idx, renderOptions, env, self); } else { const highlighted = highlightWithSelectedLanguage(markdownit, options, inlineCodeToken.content, [langToUse, prismLang]); inlineCodeToken.attrJoin('class', languageClass(markdownit, langToUse)); return `<code${self.renderAttrs(inlineCodeToken)}>${highlighted}</code>`; } }; } /** * Checks whether an option represents a valid Prism language * * @param options * The options that have been used to initialise the plugin. * @param optionName * The key of the option inside {@code options} that shall be checked. * @throws {Error} If the option is not set to a valid Prism language. */ function checkLanguageOption(options, optionName) { const language = options[optionName]; if (language !== undefined && loadPrismLang(language) === undefined) { throw new Error(`Bad option ${optionName}: There is no Prism language '${language}'.`); } } /** * ‘the most basic rule to render a token’ (https://github.com/markdown-it/markdown-it/blob/master/docs/examples/renderer_rules.md) */ function renderFallback(tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); } /** * Initialisation function of the plugin. This function is not called directly by clients, but is rather provided * to MarkdownIt’s {@link MarkdownIt.use} function. * * @param markdownit * The markdown it instance the plugin is being registered to. * @param useroptions * The options this plugin is being initialised with. */ function markdownItPrism(markdownit, useroptions) { const options = Object.assign({}, DEFAULTS, useroptions); checkLanguageOption(options, 'defaultLanguage'); checkLanguageOption(options, 'defaultLanguageForUnknown'); checkLanguageOption(options, 'defaultLanguageForUnspecified'); options.defaultLanguageForUnknown = options.defaultLanguageForUnknown || options.defaultLanguage; options.defaultLanguageForUnspecified = options.defaultLanguageForUnspecified || options.defaultLanguage; options.plugins.forEach(loadPrismPlugin); options.init(_prismjs.default); // register ourselves as highlighter markdownit.options.highlight = (text, lang) => highlight(markdownit, options, text, lang); markdownit.renderer.rules.fence = applyCodeAttributes(markdownit, options, markdownit.renderer.rules.fence || renderFallback); if (options.highlightInlineCode) { markdownit.core.ruler.after('inline', 'prism_inline_code_language', inlineCodeLanguageRule); markdownit.renderer.rules.code_inline = renderInlineCode(markdownit, options, markdownit.renderer.rules.code_inline || renderFallback); } } module.exports = exports.default; module.exports.default = exports.default;