2017-07-14 08:27:28 -04:00
|
|
|
// we need a custom renderer for code blocks cause we have a slightly non compliant
|
|
|
|
// format with special handling for text and so on
|
2016-06-14 14:31:51 -04:00
|
|
|
|
|
|
|
const TEXT_CODE_CLASSES = ["text", "pre", "plain"];
|
|
|
|
|
2017-07-14 08:27:28 -04:00
|
|
|
function render(tokens, idx, options, env, slf, md) {
|
|
|
|
let token = tokens[idx],
|
|
|
|
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-21 13:20:45 -04:00
|
|
|
info = info.trim().split(/\s+/g)[0];
|
2017-07-14 08:27:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
const acceptableCodeClasses = md.options.discourse.acceptableCodeClasses;
|
|
|
|
if (
|
|
|
|
acceptableCodeClasses &&
|
|
|
|
info &&
|
|
|
|
acceptableCodeClasses.indexOf(info) !== -1
|
|
|
|
) {
|
|
|
|
langName = info;
|
|
|
|
}
|
|
|
|
|
|
|
|
className =
|
|
|
|
TEXT_CODE_CLASSES.indexOf(info) !== -1
|
|
|
|
? "lang-nohighlight"
|
|
|
|
: "lang-" + langName;
|
|
|
|
|
2017-07-21 13:20:45 -04:00
|
|
|
return `<pre><code class="${className}">${escapedContent}</code></pre>\n`;
|
2017-07-14 08:27:28 -04:00
|
|
|
}
|
2017-07-12 18:10:51 -04:00
|
|
|
|
2016-06-14 14:31:51 -04:00
|
|
|
export function setup(helper) {
|
2017-07-14 08:27:28 -04:00
|
|
|
helper.registerOptions((opts, siteSettings) => {
|
|
|
|
opts.defaultCodeLang = siteSettings.default_code_lang;
|
|
|
|
opts.acceptableCodeClasses = (siteSettings.highlighted_languages || "")
|
|
|
|
.split("|")
|
2020-09-29 08:34:46 -04:00
|
|
|
.filter(Boolean)
|
2017-07-14 08:27:28 -04:00
|
|
|
.concat(["auto", "nohighlight"]);
|
|
|
|
});
|
2017-06-08 18:02:30 -04:00
|
|
|
|
2020-10-27 22:22:06 -04:00
|
|
|
helper.allowList({
|
2016-06-14 14:31:51 -04:00
|
|
|
custom(tag, name, value) {
|
|
|
|
if (tag === "code" && name === "class") {
|
|
|
|
const m = /^lang\-(.+)$/.exec(value);
|
|
|
|
if (m) {
|
|
|
|
return helper.getOptions().acceptableCodeClasses.indexOf(m[1]) !== -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2017-07-14 08:27:28 -04:00
|
|
|
helper.registerPlugin((md) => {
|
|
|
|
md.renderer.rules.fence = (tokens, idx, options, env, slf) =>
|
|
|
|
render(tokens, idx, options, env, slf, md);
|
2016-06-14 14:31:51 -04:00
|
|
|
});
|
|
|
|
}
|