正文
增加 70 行删除 73 行
2 行未改动3456789101179 行未改动919293949596979899186 行未改动全部展开28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545610 行未改动2 行未改动:::info[Tip:]{open}可以**在[我的博客](https://blog.rusin7.com/article/3935900)观看以获得更好的阅读体验**哦!:::OIer 都知道,洛谷中有个 [Markdown 插件](https://www.luogu.com.cn/article/70w8j2pj "插件 README"),非常好用,效果如下::::info[这是一个提示]我是提示内容。:::79 行未改动```还有更多……尽管 [安知鱼主题](https://docs.anheyu.com) 自带很多 [标签外挂](https://hexo.anheyu.com/posts/d50a.html),但仍然无法满足~~复制洛谷文章到博客~~编写习惯性的需求,于是,我**全网首发**了在 Hexo 中使用洛谷 Md 插件教程。:::info[闲话]由于~~不良~~习惯,我的所有 Markdown 文章编写均遵循洛谷的 [专栏全站推荐规范](https://help.luogu.com.cn/rules/academic/article-standard)、[洛谷主题库题解规范](https://help.luogu.com.cn/rules/academic/solution-standard)和[如何用 Markdown 和 LaTeX 写一篇排版整齐的题解?](https://help.luogu.com.cn/rules/academic/guide/solution)。:::186 行未改动全部展开然后直接在 `~/themes/···(主题名称)/scripts` 中新建 custom_marked.js(也可以是别的名字),粘贴以下代码即可,**不用引入**。:::success[代码]```javascript line-numbersconst allowedFoldableTypes = new Set(['info', 'warning', 'success', 'error', 'bug', 'flask']);function renderMarkdown(content) {return hexo.render.renderSync({ text: content.trim(), engine: 'markdown' });}function renderCustomBlock(blockType, title, opt, body) {const type = blockType.toLowerCase();const content = renderMarkdown(body.trim());if (type === 'align') {const dir = title ? title.trim() : 'left';return `\n<div class="align-${dir}">\n${content}\n</div>\n`;}if (type === 'epigraph') {const author = title ? `<p class="epigraph-author">${title}</p>` : '';return `\n<div class="epigraph">\n${content}${author}\n</div>\n`;}if (allowedFoldableTypes.has(type)) {const openAttr = opt && opt.includes('open') ? ' open' : '';const summary = title ? title.trim() : '详情';return `\n<details class="foldable ${type}"${openAttr}>\n <summary>${summary}</summary>\n <div>\n${content}\n </div>\n</details>\n`;}return null;}function parseCustomBlocks(content) {const lines = content.split(/\r?\n/);const root = { type: 'root', children: [] };const stack = [root];let codeFence = null;const openRule = /^\s*(:{3,})([a-zA-Z]\w*)(?:\s*\[([^\]]*)\])?(?:\s*\{([^}]*)\})?\s*$/;const closeRule = /^\s*(:{3,})\s*$/;for (const line of lines) {const fenceMatch = line.match(/^\s*(`{3,}|~{3,})/);if (fenceMatch) {const fence = fenceMatch[1];if (!codeFence) {codeFence = fence;} else if (codeFence === fence) {codeFence = null;}stack[stack.length - 1].children.push({ type: 'text', value: line });continue;}if (codeFence) {stack[stack.length - 1].children.push({ type: 'text', value: line });continue;}const openMatch = line.match(openRule);if (openMatch) {const level = openMatch[1].length;const blockType = openMatch[2].toLowerCase();const title = openMatch[3] || '';const opt = openMatch[4] || '';const node = { type: 'block', level, blockType, title, opt, children: [] };stack[stack.length - 1].children.push(node);stack.push(node);continue;}const closeMatch = line.match(closeRule);if (closeMatch) {const level = closeMatch[1].length;if (stack.length > 1 && stack[stack.length - 1].level === level) {stack.pop();continue;}}stack[stack.length - 1].children.push({ type: 'text', value: line });}return renderNode(root);}function renderNode(node) {if (node.type === 'root') {return node.children.map(renderNode).join('\n');}if (node.type === 'text') {return node.value;}if (node.type === 'block') {const inner = node.children.map(renderNode).join('\n');const customHtml = renderCustomBlock(node.blockType, node.title, node.opt, inner);if (customHtml !== null) {return customHtml;}const start = `${':'.repeat(node.level)}${node.blockType}${node.title ? `[${node.title}]` : ''}${node.opt ? `{${node.opt}}` : ''}`;const end = ':'.repeat(node.level);return `${start}\n${inner}\n${end}`;}return '';}hexo.extend.filter.register('before_post_render', data => {if (typeof data.content !== 'string') return data;hexo.log.debug('custom_marked before_post_render', data.source || data.path || data.title || 'unknown');data.content = parseCustomBlocks(data.content);return data;});```:::### 代码解释- **第 1 行**,初始化一个 `Set` 集合,存储允许使用的折叠容器类型(如 `info`、`warning` 等)。- **第 3-5 行**,定义 `renderMarkdown` 函数,使用 Hexo 的同步渲染接口将处理后的文本渲染为 Markdown 格式。- **第 7-27 行**,定义 `renderCustomBlock` 函数,根据传入的块类型生成对应的 HTML 结构:- **第 8 行**,将块类型统一转换为小写。- **第 9 行**,调用渲染函数处理块内的 Markdown 内容。- **第 11-14 行**,如果是 `align` 类型,生成用于文本对齐的 `div` 标签。- **第 16-18 行**,如果是 `epigraph` 类型,生成样式的 `div` 标签。- **第 20-24 行**,如果是允许的折叠类型,生成 `<details>` 和 `<summary>` 标签,并根据 `opt` 参数判断是否默认展开。- **第 30-81 行**,定义 `parseCustomBlocks` 函数,这是解析自定义块的核心逻辑:- **第 30 行**,将文章内容按行分割成数组。- **第 31 行**,创建一个根节点对象,构建 AST(抽象语法树)的基础。- **第 32 行**,初始化一个栈结构,用于处理嵌套的块结构。- **第 34 行**,定义 `codeFence` 变量,用于标记当前是否处于代码块中。- **第 35 行**,定义 `openRule` 正则表达式,用于匹配形如 `:::type[title]{opt}` 的块开始标记。- **第 36 行**,定义 `closeRule` 正则表达式,用于匹配形如 `:::` 的块结束标记。- **第 39-49 行**,处理**代码块**的逻辑:- **第 39 行**,使用正则匹配代码块标记(如 ```)。- **第 40-49 行**,如果匹配成功,切换 `codeFence` 状态(开启或关闭),并将当前行作为文本压入栈中。- **第 51-54 行**,如果当前处于代码块内,直接将内容作为纯文本处理,跳过后续解析。- **第 56-66 行**,处理**自定义容器开始标记**:- **第 56 行**,尝试匹配块的开始标记。- **第 58 行**,提取冒号数量作为层级。- **第 59-61 行**,提取块类型、标题和选项。- **第 62 行**,创建一个新的块节点。- **第 63 行**,将新节点加入父节点,并压入栈顶,成为当前的上下文。- **第 68-75 行**,处理**自定义容器结束标记**:- **第 68 行**,尝试匹配块的结束标记。- **第 70 行**,获取结束标记的层级。- **第 71-74 行**,如果结束标记的层级与栈顶节点一致,弹出栈顶节点,结束当前块的解析。- **第 77 行**,处理**普通文本**,将其作为子节点添加到当前的上下文中。- **第 80 行**,调用 `renderNode` 递归解析生成的树结构,并返回最终的 HTML 字符串。- **第 83-101 行**,定义 `renderNode` 函数,执行递归渲染:- **第 84-86 行**,如果是根节点,遍历并渲染所有子节点。- **第 87-89 行**,如果是文本节点,直接返回文本内容。- **第 90-99 行**,如果是块节点,先递归渲染内部内容,再包裹对应的 HTML 标签。- **第 103-108 行**,注册 Hexo 过滤器:- **第 103 行**,监听 `before_post_render` 事件。- **第 104 行**,检查内容是否为字符串。- **第 105 行**,输出调试日志。- **第 106 行**,调用 `parseCustomBlocks` 处理文章内容。- **第 107 行**,返回处理后的数据。*本图片使用* [*Drawnix*](https://board.rusin7.com) *生成*。AI 声明:**代码解释**大部分内容使用智谱清言 GLM-5.2 大模型进行修改和润色。:::info[为什么不用引入?]{open}与前面引入的 Css 不同的是,任意主题的目录 `~/themes/···(主题名称)/scripts` 功能都都一样,Hexo 解析时都会运行此目录下的**所有** Javascript 文件。::::::error[可能的错误]一不小心放到了 `~/themes/anzhiyu/source/js/custom_marked.js` 里。~~唐~~10 行未改动2 行未改动3456789101179 行未改动919293949596979899186 行未改动全部展开28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245310 行未改动2 行未改动:::info[Tip:]{open}可以**在[我的博客](https://blog.rusin7.com/article/3935900)观看以获得更好的阅读体验**哦!:::OIer 都知道,洛谷中有个 [Markdown 插件](https://www.luogu.com.cn/article/70w8j2pj "插件"),非常好用,效果如下::::info[这是一个提示]我是提示内容。:::79 行未改动```还有更多……尽管[安知鱼主题](https://docs.anheyu.com)自带很多[标签外挂](https://hexo.anheyu.com/posts/d50a.html),但仍然无法满足~~复制洛谷文章到博客~~编写习惯性的需求,于是,我**全网首发**了在 Hexo 中使用洛谷 Md 插件教程。:::info[闲话]由于~~不良~~习惯,我的所有 Markdown 文章编写均遵循洛谷的 [专栏全站推荐规范](https://help.luogu.com.cn/rules/academic/article-standard)、[洛谷主题库题解规范](https://help.luogu.com.cn/rules/academic/solution-standard)和[如何用 Markdown 和 LaTeX 写一篇排版整齐的题解?](https://help.luogu.com.cn/rules/academic/guide/solution)。:::186 行未改动全部展开然后直接在 `~/themes/···(主题名称)/scripts` 中新建 custom_marked.js(也可以是别的名字),粘贴以下代码即可,**不用引入**。:::success[代码]```javascript line-numbers// 允许使用的折叠容器类型集合const allowedFoldableTypes = new Set(['info', 'warning', 'success', 'error', 'bug', 'flask']);/*** 使用 Hexo 同步渲染接口将文本渲染为 Markdown 格式* @param {string} content 待渲染的文本内容* @returns {string} 渲染后的 HTML 内容*/function renderMarkdown(content) {return hexo.render.renderSync({ text: content.trim(), engine: 'markdown' });}/*** 根据块类型生成对应的自定义 HTML 结构* @param {string} blockType 块类型* @param {string} title 块标题* @param {string} opt 块配置选项* @param {string} body 块内部内容* @returns {string|null} 生成的 HTML 字符串,未知类型返回 null*/function renderCustomBlock(blockType, title, opt, body) {const type = blockType.toLowerCase(); // 统一转换为小写,兼容大小写写法const content = renderMarkdown(body.trim()); // 渲染块内的 Markdown 内容// 文本对齐块:生成带对齐类名的 div 容器if (type === 'align') {const dir = title ? title.trim() : 'left'; // 未指定方向时默认左对齐return `\n<div class="align-${dir}">\n${content}\n</div>\n`;}// 题记/引语块:生成带作者信息的引语容器if (type === 'epigraph') {const author = title ? `<p class="epigraph-author">${title}</p>` : ''; // 标题作为作者信息return `\n<div class="epigraph">\n${content}${author}\n</div>\n`;}// 可折叠容器:生成 details/summary 结构if (allowedFoldableTypes.has(type)) {const openAttr = opt && opt.includes('open') ? ' open' : ''; // 包含 open 选项则默认展开const summary = title ? title.trim() : '详情'; // 未指定标题时默认显示"详情"return `\n<details class="foldable ${type}"${openAttr}>\n <summary>${summary}</summary>\n <div>\n${content}\n </div>\n</details>\n`;}return null; // 未知类型返回 null,保留原始标记}/*** 解析 Markdown 内容中的自定义块语法,构建 AST 并渲染为最终 HTML* @param {string} content 原始 Markdown 内容* @returns {string} 处理后的 HTML 内容*/function parseCustomBlocks(content) {const lines = content.split(/\r?\n/); // 按行分割内容,兼容 Windows/Unix 换行符const root = { type: 'root', children: [] }; // 抽象语法树根节点const stack = [root]; // 栈结构,用于处理嵌套的块层级let codeFence = null; // 代码块标记,记录当前是否处于代码块内及围栏字符// 自定义块开始标记正则:匹配 :::type[title]{opt} 格式const openRule = /^\s*(:{3,})([a-zA-Z]\w*)(?:\s*\[([^\]]*)\])?(?:\s*\{([^}]*)\})?\s*$/;// 自定义块结束标记正则:匹配 ::: 格式const closeRule = /^\s*(:{3,})\s*$/;for (const line of lines) {// ---------- 代码块处理逻辑 ----------const fenceMatch = line.match(/^\s*(`{3,}|~{3,})/);if (fenceMatch) {const fence = fenceMatch[1];if (!codeFence) {codeFence = fence; // 进入代码块,记录围栏字符} else if (codeFence === fence) {codeFence = null; // 退出代码块,清空标记}// 代码块标记行直接作为文本保留stack[stack.length - 1].children.push({ type: 'text', value: line });continue;}// 当前处于代码块内时,所有行均作为纯文本处理,不解析自定义块if (codeFence) {stack[stack.length - 1].children.push({ type: 'text', value: line });continue;}// ---------- 自定义块开始标记处理 ----------const openMatch = line.match(openRule);if (openMatch) {const level = openMatch[1].length; // 冒号数量代表块的嵌套层级const blockType = openMatch[2].toLowerCase(); // 块类型const title = openMatch[3] || ''; // 块标题(方括号内内容)const opt = openMatch[4] || ''; // 块配置选项(大括号内内容)// 创建块节点并加入语法树const node = { type: 'block', level, blockType, title, opt, children: [] };stack[stack.length - 1].children.push(node);stack.push(node); // 压入栈顶,成为当前作用域continue;}// ---------- 自定义块结束标记处理 ----------const closeMatch = line.match(closeRule);if (closeMatch) {const level = closeMatch[1].length;// 结束标记层级与栈顶块层级一致时,弹出栈顶,闭合当前块if (stack.length > 1 && stack[stack.length - 1].level === level) {stack.pop();continue;}}// ---------- 普通文本行处理 ----------stack[stack.length - 1].children.push({ type: 'text', value: line });}return renderNode(root); // 递归渲染语法树,生成最终 HTML}/*** 递归渲染语法树节点,生成最终 HTML 字符串* @param {object} node 语法树节点* @returns {string} 渲染后的文本内容*/function renderNode(node) {// 根节点:遍历渲染所有子节点并拼接if (node.type === 'root') {return node.children.map(renderNode).join('\n');}// 文本节点:直接返回原始文本if (node.type === 'text') {return node.value;}// 块节点:先递归渲染内部内容,再包裹对应 HTML 结构if (node.type === 'block') {const inner = node.children.map(renderNode).join('\n');const customHtml = renderCustomBlock(node.blockType, node.title, node.opt, inner);// 已知类型返回自定义 HTML,未知类型保留原始标记if (customHtml !== null) {return customHtml;}// 未知块类型:还原原始的自定义标记语法const start = `${':'.repeat(node.level)}${node.blockType}${node.title ? `[${node.title}]` : ''}${node.opt ? `{${node.opt}}` : ''}`;const end = ':'.repeat(node.level);return `${start}\n${inner}\n${end}`;}return '';}// 注册 Hexo 前置渲染过滤器,在 Markdown 渲染前处理自定义块hexo.extend.filter.register('before_post_render', data => {if (typeof data.content !== 'string') return data; // 非字符串内容跳过处理// 输出调试日志,标记当前处理的文章hexo.log.debug('custom_marked before_post_render', data.source || data.path || data.title || 'unknown');data.content = parseCustomBlocks(data.content); // 执行自定义块解析与渲染return data;});```:::AI 声明:**代码注释**使用智谱清言 GLM-5.2 大模型进行修改和润色。:::info[为什么不用引入?]{open}与前面引入的 Css 不同的是,任意主题的目录 `~/themes/···(主题名称)/scripts` 功能都一样,Hexo 解析时都会运行此目录下的**所有** Javascript 文件。::::::error[可能的错误]一不小心放到了 `~/themes/anzhiyu/source/js/custom_marked.js` 里。~~唐~~10 行未改动