Compare commits

...

23 Commits
1.0.1 ... main

Author SHA1 Message Date
66d07bb2a5 bump version 2024-11-13 17:56:20 +08:00
28035a8513 更换 action 2024-11-13 17:53:31 +08:00
98ff7de56a 修复单主题时的 BUG 2024-11-13 17:41:38 +08:00
280c69586f Refine build configuration to exclude hexo from bundle. 2024-11-09 12:16:26 +08:00
HPCesia
68115abd81 chore: Update READMEs to specify Hexo dependency
- Added link to Hexo repository
- Clarified comment on `original_lang_name` in English version
2024-10-29 14:14:06 +08:00
HPCesia
c111ee0243 chore: bump package.json version 2024-10-29 13:54:55 +08:00
HPCesia
2a267a8651 feat: can specify some languages individually in original_lang_name to not convert or only convert certain languages 2024-10-29 13:51:55 +08:00
HPCesia
e1d2442f7c feat: support to show the original name of language in the class of figure tag 2024-10-24 16:11:45 +08:00
HPCesia
6788dc4839 update version to 1.1.1 2024-10-24 16:03:50 +08:00
HPCesia
57554f36a9 fix bug of language alias 2024-10-24 16:03:03 +08:00
HPCesia
4ffdd0ea92 modify workflow 2024-10-21 22:48:41 +08:00
HPCesia
679a11a0d6 delete chinese readme in package. 2024-10-21 22:47:52 +08:00
HPCesia
1fc03405c3 Update readme 2024-10-21 22:44:35 +08:00
HPCesia
24afc3cc89 track lock.json 2024-10-21 22:43:28 +08:00
HPCesia
0a8d8e5b0b update readme 2024-10-21 22:31:44 +08:00
HPCesia
c5f26c2248 Update readme 2024-10-21 19:41:58 +08:00
Derek.H
080e929518
Update npm-publish.yml 2024-10-21 19:28:39 +08:00
Derek.H
d542402aad
Update npm-publish.yml 2024-10-21 19:28:10 +08:00
HPCesia
346e22e086 Merge branch 'main' of https://github.com/HPCesia/hexo-highlighter-shiki 2024-10-21 18:52:10 +08:00
HPCesia
80451d29e5 feat: Update version to 1.1.0 2024-10-21 18:04:47 +08:00
HPCesia
2635edc901 feat: Support to use transformers in https://shiki.style/packages/transformers 2024-10-21 18:03:37 +08:00
HPCesia
c03510a8a7 feat: support custom theme.
feat: support to set default theme color and css variable prefix options.
2024-10-21 16:40:34 +08:00
Derek.H
ff8d060c8a
Create npm-publish.yml 2024-10-20 21:34:37 +08:00
8 changed files with 2436 additions and 40 deletions

26
.github/workflows/npm-publish.yml vendored Normal file
View File

@ -0,0 +1,26 @@
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
name: Node.js Package
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Publish package to npm
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.npm_token }}

1
.gitignore vendored
View File

@ -8,5 +8,4 @@ dist
*.log
# Node
package-lock.json
node_modules

100
README.md
View File

@ -1,14 +1,18 @@
# Hexo-Highlight-Shiki
[![NPM Version](https://img.shields.io/npm/v/hexo-highlighter-shiki?style=flat)](https://www.npmjs.com/package/hexo-highlighter-shiki)
English丨[简体中文](README_zh-CN.md)
A hexo plugin to use [Shiki](https://github.com/shikijs/shiki) as code block highlighter.
Hexo v7.0.0+ is required.
[Hexo](https://github.com/hexojs/hexo) v7.0.0+ is required.
## Features
- Render code block with Shiki like Hexo default highlighter.
- Support dual or more themes.
- Use [Shiki](https://github.com/shikijs/shiki) to render code blocks, and the format is similar to Hexo's default code highlighting (so you don't need to make significant changes to the theme you are currently using).
- Support switching between multiple themes (you need to write the corresponding styles and scripts yourself).
- Support custom language.
- Support custom theme.
- Support transformers in [@shikijs/transformers](https://shiki.style/packages/transformers).
## Installation and Configuration
First, install the plugin:
@ -27,17 +31,45 @@ shiki:
theme: github-dark # default: one-dark-pro
line_number: true # default: false
```
and use
```shell
hexo clean && hexo generate
```
to enjoy code highlighting powered by Shiki.
## Configuration Options
The complete configuration is as follows:
```yaml
shiki:
theme: one-dark-pro # see https://shiki.style/themes for supported themes.
line_number: false
strip_indent: true
tab_replace: " "
pre_style: true # Preserve the style of the <pre> tag, i.e., the theme's `background-color`.
theme: one-dark-pro # Please refer to https://shiki.style/themes for supported themes.
line_number: false # default: false
strip_indent: true # default: true
tab_replace: " " # default: " "
# Use the original language name in the figure tag
# For example, when the language of code block is 'js':
# original_lang_name: false => <figure class="highlighter js">
# original_lang_name: true => <figure class="highlighter javascript">
original_lang_name: false
pre_style: true # Preserve the style of the <pre> tag. default: true
default_color: light # Only take effect when using multiple themes. default: light
css_variable_prefix: --shiki- # Only take effect when using multiple themes. default: --shiki-
# List of transformers to be enabled.
# Please refer to https://shiki.style/packages/transformers for the list of supported transformers.
transformers:
# You can omit `name` and `option` when no options are required, directly using the string.
- "example1"
# When additional option are required, please explicitly set name and option.
- name: example2
# Options for the transformer.
# Please check the @shikijs/transformer's source code to get the list of supported options
# Source code of @shikijs/transformer:
# https://github.com/shikijs/shiki/tree/main/packages/transformers/src/transformers
option:
exampleOption1: exampleValue1
exampleOption2: exampleValue2
additional:
themes: # List of the TextMate theme json to be added.
- path/to/theme.json
langs: # List of the TextMate grammar json of languages to be added.
- path/to/lang_grammar.json
lang_alias: # List of the alias of languages.
@ -55,16 +87,62 @@ shiki:
```
See [Dual Themes](https://shiki.style/guide/dual-themes) for how to switch between multiple themes.
You can also specify some languages individually in `original_lang_name` to not convert or only convert them:
```yaml
original_lang_name:
# Set to true to exclude the languages listed in `langs`,
# otherwise only convert the languages in `langs`.
exclude: true
# Must be an array
langs:
- shell
- bash
- zsh
# Change the original language name
change_origin:
fortran-free-form: fortran
```
Refer to [Languages | Shiki](https://shiki.style/languages) to view the original names (IDs) of languages.
### Example of Using Transformers
if you want to mark some lines, you can use Hexo's code block tag plugin (which has been adapted by this plugin):
```markdown
{% codeblock lang:rust mark:2 %}
fn main() {
println!("Hello, world!");
}
{% endcodeblock %}
```
But if you want to mark some lines in backtick code blocks, you can use transformer:
```yaml
transformers:
- name: transformerNotationHighlight
option:
classActiveLine: marked # same to Hexo's code block tag, default: highlighted
classActivePre: "" # default: has-highlighted
```
and add some comment to your code block:
````markdown
```rust
fn main() {
println!("Hello, world!"); // [!code highlight]
}
```
````
The result is the same as the Hexo code block tag plugin.
## Bugs
### mathjax
If you are using [hexo-filter-mathjax](https://github.com/next-theme/hexo-filter-mathjax) or any other plugin that uses mathjax to render mathematical formulas locally, you may encounter an `Error: Can't find handler for document` when rendering articles that include code blocks and have mathjax rendering enabled. This is a problem with mathjax, as its LiteDOM adaptor cannot parse complex HTML fragments.
#### Solution
For example, if you are using the hexo-filter-mathjax plugin, modify the [this line](https://github.com/next-theme/hexo-filter-mathjax/blob/20dc61352f8cf4d19425ad1833eb72b467c212ef/index.js#L20C3-L20C40) in the source code:
```js
```diff
- data.content = mathjax(data.content);
+ data.content = data.content.replace(/<span\s+class="math\s+[^"]*">\\[\(\[].*?\\[\)\]]<\/span>/gs, mathjax);
+ data.content = data.content.replace(
+ /<span\s+class="math\s+[^"]*">\\[\(\[].*?\\[\)\]]<\/span>/gs,
+ mathjax);
```
This will prevent rendering errors for complex HTML fragments that result in `Can't find handler for document`.

View File

@ -1,14 +1,18 @@
# Hexo-Highlight-Shiki
[![NPM Version](https://img.shields.io/npm/v/hexo-highlighter-shiki?style=flat)](https://www.npmjs.com/package/hexo-highlighter-shiki)
[English](README.md)丨简体中文
一个使用 [Shiki](https://github.com/shikijs/shiki) 作为代码块高亮器的 Hexo 插件。
需要 Hexo v7.0.0+。
需要 [Hexo](https://github.com/hexojs/hexo) v7.0.0+。
## 功能
- 使用 Shiki 渲染代码块,类似于 Hexo 默认的高亮器
- 支持双主题或更多主题。
- 使用 [Shiki](https://github.com/shikijs/shiki) 渲染代码块,且与 Hexo 默认的代码高亮渲染的格式相似(因此你不需要对你现在使用的主题做很大的修改)
- 支持多主题切换(需要自行编写对应的样式与脚本)
- 支持自定义语言。
- 支持自定义主题。
- 支持 [@shikijs/transformers](https://shiki.style/packages/transformers) 中的转换器。
## 安装与配置
首先,安装本插件:
@ -26,20 +30,45 @@ syntax_highlighter: shiki
shiki:
theme: one-dark-pro
```
并使用
```shell
hexo clean && hexo generate
```
来享受由 Shiki 提供的代码高亮功能。
## 配置项
完整配置如下:
```yaml
shiki:
theme: "one-dark-pro" # Theme, see https://shiki.style/themes for supported themes.
theme: "one-dark-pro" # 主题,请参阅 https://shiki.style/themes 以获取支持的主题列表。
line_number: false
strip_indent: true
tab_replace: " "
pre_style: true # Preserve the style of the <pre> tag, i.e., the theme's `background-color`.
# 在 figure 标签中类名使用语言原名
# 例如代码块语言为 'js' 时:
# original_lang_name: false => <figure class="highlighter js">
# original_lang_name: true => <figure class="highlighter javascript">
original_lang_name: false
pre_style: true # 保留 <pre> 标签的样式,即主题的 `background-color`
default_color: light # 仅在同时使用多个主题时生效。默认值light
css_variable_prefix: --shiki- # 仅在同时使用多个主题时生效。默认值:--shiki-
# 需要启用的转换器列表。请参阅 https://shiki.style/packages/transformers 以获取支持的转换器列表。
transformers:
# 不需要设置选项时,可省略 `name``option`,直接使用字符串。
- "example1"
# 需要设置选项时,请显式设置 name 与 option。
- name: example2
# 转换器的选项,请查看转换器的源码以获取支持的选项列表
# 转换器源码https://github.com/shikijs/shiki/tree/main/packages/transformers/src/transformers
option:
exampleOption1: exampleValue1
exampleOption2: exampleValue2
additional:
langs: # List of the TextMate grammar json of languages to be added.
themes: # 要添加的主题的 TextMate 主题 json 列表。
- path/to/theme.json
langs: # 要添加的语言的 TextMate 语法 json 列表。
- path/to/lang_grammar.json
lang_alias: # List of the alias of languages.
lang_alias: # 语言的别名列表。
your_alias1: lang_name1
your_alias2: lang_name2
```
@ -52,24 +81,69 @@ shiki:
dark: one-dark-pro
# ...
```
在 [Dual Themes](https://shiki.style/guide/dual-themes) 中查看如何切换多个主题。
在 [Dual Themes](https://shiki.style/guide/dual-themes) 中查看如何切换多个主题。
同时你还可以在 `original_lang_name` 中单独指定一些语言进行或不进行转换:
```yaml
original_lang_name:
# 为真时将不转换 langs 内的语言,反之则只转换 langs 内的语言
exclude: true
# 必须为数组
langs:
- shell
- bash
- zsh
# 改变语言原名
change_origin:
fortran-free-form: fortran
```
参阅 [Languages | Shiki](https://shiki.style/languages) 查看语言的原名ID
### 转换器使用示例
如果你想标记某些行,你可以使用 Hexo 的代码块标签插件(本插件对其做了适配):
```markdown
{% codeblock lang:rust mark:2 %}
fn main() {
println!("Hello, world!");
}
{% endcodeblock %}
```
但是,如果你想在反引号代码块中标记某些行,你可以使用转换器:
```yaml
transformers:
- name: transformerNotationHighlight
option:
classActiveLine: marked # 与 Hexo 的代码块标签标记行的类相同默认值highlighted
classActivePre: "" # 默认值has-highlighted
```
并在你的代码块中添加一些注释:
````markdown
```rust
fn main() {
println!("Hello, world!"); // [!code highlight]
}
```
````
结果与 Hexo 的代码块标签插件相同。
## Bugs
### mathjax
如果你正在使用 [hexo-filter-mathjax](https://github.com/next-theme/hexo-filter-mathjax) 或其他任意在本地使用 mathjax 渲染数学公式的插件,在渲染包含代码块且开启 mathjax 渲染的文章时可能会出现 `Error: Can't find handler for document`。这是 mathjax 的问题mathjax 的 LiteDOM adaptor 无法解析复杂的 HTML 片段。
#### 解决方法
以 hexo-filter-mathjax 插件为例,修改源代码中的[这一行](https://github.com/next-theme/hexo-filter-mathjax/blob/20dc61352f8cf4d19425ad1833eb72b467c212ef/index.js#L20C3-L20C40):
```js
```diff
- data.content = mathjax(data.content);
+ data.content = data.content.replace(/<span\s+class="math\s+[^"]*">\\[\(\[].*?\\[\)\]]<\/span>/gs, mathjax);
+ data.content = data.content.replace(
+ /<span\s+class="math\s+[^"]*">\\[\(\[].*?\\[\)\]]<\/span>/gs,
+ mathjax);
```
这可以避免对那些复杂的 HTML 片段进行渲染导致的 `Can't find handler for document` 错误。
#### 相关 Issues
- [Error in applying html the markdown file #26](https://github.com/next-theme/hexo-filter-mathjax/issues/26)
- [ Can't find handler for document #265 ](https://github.com/mathjax/MathJax-src/issues/265)
- [Can't find handler for document #265](https://github.com/mathjax/MathJax-src/issues/265)
## 感谢
本插件基于

View File

@ -4,6 +4,10 @@ import { promises as fs } from 'fs';
await build({
entryPoints: ['src/main.ts'],
bundle: true,
external:[
'hexo-util',
'hexo'
],
outdir: 'dist',
platform: 'node',
sourcemap: false,

2125
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,12 @@
{
"name": "hexo-highlighter-shiki",
"version": "1.0.1",
"version": "1.2.2",
"description": "A package for Hexo which use Shiki to render code highlight.",
"main": "dist/index.js",
"files": [
"dist",
"LICENSE",
"README.md",
"README_zh-CN.md",
"package.json"
],
"scripts": {
@ -30,12 +29,14 @@
"author": "HPCesia",
"license": "MIT",
"devDependencies": {
"@shikijs/transformers": "^1.22.0",
"@types/node": "^22.7.6",
"esbuild": "^0.24.0",
"typescript": "^5.6.3",
"shiki": "^1.22.0"
"shiki": "^1.22.0",
"typescript": "^5.6.3"
},
"peerDependencies": {
"hexo": "^7.0.0"
"hexo": "^7.0.0",
"hexo-util": "^3.3.0"
}
}

View File

@ -1,9 +1,36 @@
"use strict";
import { bundledLanguages, createHighlighter, ShikiTransformer } from "shiki";
import { bundledLanguages, bundledThemes, createHighlighter, ShikiTransformer } from "shiki";
import type Hexo from "hexo";
import { HighlightOptions } from "hexo/dist/extend/syntax_highlight";
import { stripIndent, htmlTag } from "hexo-util";
import { readFileSync } from "fs";
import {
transformerCompactLineOptions,
transformerMetaHighlight,
transformerMetaWordHighlight,
transformerNotationDiff,
transformerNotationErrorLevel,
transformerNotationFocus,
transformerNotationHighlight,
transformerNotationWordHighlight,
transformerRemoveLineBreak,
transformerRemoveNotationEscape,
transformerRenderWhitespace,
} from "@shikijs/transformers";
const supported_transformers = {
transformerCompactLineOptions,
transformerMetaHighlight,
transformerMetaWordHighlight,
transformerNotationDiff,
transformerNotationErrorLevel,
transformerNotationFocus,
transformerNotationHighlight,
transformerNotationWordHighlight,
transformerRemoveLineBreak,
transformerRemoveNotationEscape,
transformerRenderWhitespace,
};
export async function init(hexo: Hexo) {
const config = Object.assign(
@ -12,29 +39,69 @@ export async function init(hexo: Hexo) {
line_number: false,
strip_indent: true,
tab_replace: " ",
original_lang_name: false,
pre_style: true,
default_color: "light",
css_variable_prefix: "--shiki-",
transformers: [],
// TODO: 增加 `wrap` 选项,与 Hexo 的 highlight.js 渲染行为一致
// TODO: 增加 `beautify` 选项以适配更多主题
additional: {
themes: [],
langs: [],
lang_alias: {},
},
},
hexo.config.shiki || {}
);
// 处理自定义语言 json
let additional_langs = [];
if (config.additional.langs)
for (const extra_lang of [].concat(config.additional.langs)) {
additional_langs.push(JSON.parse(readFileSync(extra_lang, "utf8")));
}
const langs = [...Object.keys(bundledLanguages), ...additional_langs];
// 处理自定义主题 json
let additional_themes = [];
if (config.additional.themes)
for (const extra_theme of [].concat(config.additional.themes)) {
additional_themes.push(JSON.parse(readFileSync(extra_theme, "utf8")));
}
// 处理主题
const themes = additional_themes.concat(
(typeof config.theme === "string" ? [config.theme] : Object.values(config.theme)).filter(
(theme) => theme in bundledThemes
)
);
// 处理 transformers
const transformers = config.transformers
.map((transformer) => {
if (typeof transformer === "string") {
let tfm = supported_transformers[transformer];
if (!tfm) return null;
return tfm();
}
let tfm = supported_transformers[transformer["name"]];
if (!tfm) return null;
let option = transformer["option"];
if (!option) return tfm();
return tfm(option);
})
.filter((tfm) => tfm !== null);
// 创建 highlighter
let highlighter_options = {
langs: langs,
themes: typeof config.theme === "string" ? [config.theme] : Object.values(config.theme),
themes: themes,
};
if (config.additional.lang_alias && Object.keys(config.additional.lang_alias).length > 0) {
highlighter_options["langAliases"] = config.additional.lang_alias;
highlighter_options["langAlias"] = config.additional.lang_alias;
}
const highlighter = await createHighlighter(highlighter_options);
const supportedLanguages = highlighter.getLoadedLanguages().reduce(
const supported_languages = highlighter.getLoadedLanguages().reduce(
(acc, lang) => {
acc[lang] = true;
return acc;
@ -45,19 +112,37 @@ export async function init(hexo: Hexo) {
ansi: true,
}
);
// 处理语言转换原名
const useOringinalLangName = (lang) => {
if (lang === "text") return false;
if (typeof config.original_lang_name === "boolean") return config.original_lang_name;
const exclude = config.original_lang_name.exclude || false;
const langs = config.original_lang_name.langs || [];
return exclude ? !langs.includes(lang) : langs.includes(lang);
};
const originalLangName = (lang) => {
const name = highlighter.getLanguage(lang).name;
if (typeof config.original_lang_name === "boolean") return name;
const origin = config.original_lang_name.change_origin || {};
if (name in origin) return origin[name];
return name;
};
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]) {
if (!lang || !supported_languages[lang]) {
lang = "text";
}
// 处理代码块语法高亮
let pre = "";
const transformer = (): ShikiTransformer => {
const transformerMarkedLine = (): ShikiTransformer => {
return {
line(node, line) {
if (options.mark && options.mark.includes(line)) {
@ -67,17 +152,19 @@ export async function init(hexo: Hexo) {
};
};
try {
if (config.theme === "string")
if (typeof config.theme === "string")
pre = highlighter.codeToHtml(code, {
lang,
theme: config.theme,
transformers: [transformer()],
transformers: [transformerMarkedLine()].concat(transformers),
});
else
pre = highlighter.codeToHtml(code, {
lang,
themes: config.theme,
transformers: [transformer()],
transformers: [transformerMarkedLine()].concat(transformers),
defaultColor: config.default_color,
cssVariablePrefix: config.css_variable_prefix,
});
// 删除多余内容
pre = pre.replace(/<pre[^>]*>/, (match) => {
@ -97,7 +184,7 @@ export async function init(hexo: Hexo) {
(options.line_number || true) && // 代码块中未设置不显示行号
(options.line_threshold || 0) < options.lines_length; // 代码行数超过阈值
if (show_line_number) {
const firstLine = options.firstLine || 1
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>";
}
@ -114,7 +201,9 @@ export async function init(hexo: Hexo) {
// 合并标签
const html = htmlTag(
"figure",
{ class: `highlight ${lang}` },
{
class: `highlight ${useOringinalLangName(lang) ? originalLangName(lang) : lang}`,
},
caption +
htmlTag(
"table",