Commit ebd0a3a
Changed files (1)
src
src/main.ts
@@ -12,6 +12,7 @@ export async function init(hexo: Hexo) {
line_number: false,
strip_indent: true,
tab_replace: " ",
+ pre_style: true,
additional: {
langs: [],
lang_alias: {},
@@ -47,10 +48,14 @@ export async function init(hexo: Hexo) {
const hexoHighlighter = (code: string, options: HighlightOptions) => {
var code = config.strip_indent ? (stripIndent(code) as string) : code;
code = config.tab_replace ? code.replace(/\t/g, config.tab_replace) : code;
+
+ // 处理代码语言
let lang = options.lang;
if (!lang || !supportedLanguages[lang]) {
lang = "text";
}
+
+ // 处理代码块语法高亮
let pre = "";
const transformer = (): ShikiTransformer => {
return {
@@ -74,31 +79,49 @@ export async function init(hexo: Hexo) {
themes: config.theme,
transformers: [transformer()],
});
- pre = pre.replace(/<pre[^>]*>/, "<pre>");
+ // 删除多余内容
+ pre = pre.replace(/<pre[^>]*>/, (match) => {
+ if (config.pre_style) return match.replace(/\s*tabindex="0"/, "");
+ return match.replace(/\s*style\s*=\s*"[^"]*"\s*tabindex="0"/, "");
+ });
pre = pre.replace(/<\/?code>/, "");
} catch (error) {
console.warn(error);
pre = htmlTag("pre", {}, code);
}
+ // 处理行号
let numbers = "";
- if (config.line_number) {
- for (let i = 0, len = code.split("\n").length; i < len; i++) {
- numbers += htmlTag("span", { class: "line" }, `${1 + i}`, false) + "<br>";
+ const show_line_number =
+ config.line_number && // 设置中显示行号
+ (options.line_number || true) && // 代码块中未设置不显示行号
+ (options.line_threshold || 0) < options.lines_length; // 代码行数超过阈值
+ if (show_line_number) {
+ const firstLine = options.firstLine || 1
+ for (let i = firstLine, len = code.split("\n").length + firstLine; i < len; i++) {
+ numbers += htmlTag("span", { class: "line" }, `${i}`, false) + "<br>";
}
numbers = htmlTag("pre", {}, numbers, false);
}
+
+ // 处理标题与链接
+ const caption = options.caption ? htmlTag("figcaption", {}, options.caption, false) : "";
+
+ // 处理包裹标签
const td_code = htmlTag("td", { class: "code" }, pre, false);
- const td_gutter = htmlTag("td", { class: "gutter" }, numbers, false);
+ const td_gutter = numbers.length > 0 ? htmlTag("td", { class: "gutter" }, numbers, false) : "";
+
+ // 合并标签
const html = htmlTag(
"figure",
{ class: `highlight ${lang}` },
- htmlTag(
- "table",
- {},
- htmlTag("tbody", {}, htmlTag("tr", {}, td_gutter + td_code, false), false),
- false
- ),
+ caption +
+ htmlTag(
+ "table",
+ {},
+ htmlTag("tbody", {}, htmlTag("tr", {}, td_gutter + td_code, false), false),
+ false
+ ),
false
);
return html;