discourse/app/assets/javascripts/pretty-text/engines/discourse-markdown/code.js.es6

59 lines
1.6 KiB
Plaintext
Raw Normal View History

// we need a custom renderer for code blocks cause we have a slightly non compliant
// format with special handling for text and so on
const TEXT_CODE_CLASSES = ["text", "pre", "plain"];
function render(tokens, idx, options, env, slf, md) {
let token = tokens[idx],
2018-06-15 23:03:24 +08:00
info = token.info ? md.utils.unescapeAll(token.info) : "",
langName = md.options.discourse.defaultCodeLang,
className,
escapedContent = md.utils.escapeHtml(token.content);
if (info) {
// strip off any additional languages
2017-07-22 01:20:45 +08:00
info = info.trim().split(/\s+/g)[0];
}
const acceptableCodeClasses = md.options.discourse.acceptableCodeClasses;
2018-06-15 23:03:24 +08:00
if (
acceptableCodeClasses &&
info &&
acceptableCodeClasses.indexOf(info) !== -1
) {
langName = info;
}
2018-06-15 23:03:24 +08:00
className =
TEXT_CODE_CLASSES.indexOf(info) !== -1
? "lang-nohighlight"
: "lang-" + langName;
2017-07-22 01:20:45 +08:00
return `<pre><code class="${className}">${escapedContent}</code></pre>\n`;
}
export function setup(helper) {
helper.registerOptions((opts, siteSettings) => {
opts.defaultCodeLang = siteSettings.default_code_lang;
2018-06-15 23:03:24 +08:00
opts.acceptableCodeClasses = (siteSettings.highlighted_languages || "")
.split("|")
.concat(["auto", "nohighlight"]);
});
helper.whiteList({
custom(tag, name, value) {
2018-06-15 23:03:24 +08:00
if (tag === "code" && name === "class") {
const m = /^lang\-(.+)$/.exec(value);
if (m) {
return helper.getOptions().acceptableCodeClasses.indexOf(m[1]) !== -1;
}
}
}
});
2018-06-15 23:03:24 +08:00
helper.registerPlugin(md => {
md.renderer.rules.fence = (tokens, idx, options, env, slf) =>
render(tokens, idx, options, env, slf, md);
});
}