Fixing Broken Bold Syntax Near Chinese Punctuation in Hexo
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Most of this article was generated with AIGC and then manually polished.
The Problem
Hexo's default markdown rendering has always had the problem described in the title:
A typical example is this:
**Java 字符串的一个重要特点就是字符串不可变。**这种不可变性是通过内部字段实现的。It should be rendered as:
<strong>Java 字符串的一个重要特点就是字符串不可变。</strong>这种不可变性是通过内部字段实现的。But in the actually generated HTML, the ** remains in the body text as-is:
<p>**Java 字符串的一个重要特点就是字符串不可变。**这种不可变性是通过内部字段实现的。</p>This problem tends to occur in Chinese articles, because we often write things like:
**一句完整的话。**下一句继续。
中文**“条件”**在序列中一定如何如何。
中文**<u>重点内容</u>**后面继续接正文。To summarize the problem precisely: when Chinese characters, fullwidth punctuation, Chinese quotation marks, HTML tags, inline code, and other mixed content appear near the opening or closing ** delimiters, markdown-it may fail to recognize them as valid emphasis delimiters.
Locating the Problem First
This blog uses Hexo 7.3.0, with hexo-renderer-markdown-it as the Markdown renderer. The first step in troubleshooting was to reproduce the issue directly with markdown-it.
For example:
const MarkdownIt = require('markdown-it');
const md = new MarkdownIt({ html: true });
console.log(md.renderInline('**Java 字符串的一个重要特点就是字符串不可变。**这种不可变性'));
console.log(md.renderInline('中文**“条件”**在序列中'));
console.log(md.renderInline('中文**<u>粗体</u>**后面'));As you can see from the results, in many cases **...** is not converted into <strong>...</strong>.
Looking further into the markdown-it implementation, you'll find that the key logic lives in StateInline.prototype.scanDelims. It decides whether a run of asterisks can serve as an opening or closing delimiter based on the characters before and after the **.
For example, this snippet:
**abc。**中文The closing ** is preceded by 。 and followed by 中. 。 is punctuation, while 中 is neither whitespace nor punctuation, so under the default rules this run of ** may not qualify as a closing delimiter.
Another example:
中文**“条件”**在序列中The opening ** is preceded by 文 and followed by “. The following character is punctuation, but the preceding one is neither whitespace nor punctuation, so under the default rules this run of ** may not qualify as an opening delimiter. The visible result is that the entire bold segment fails, or consecutive bold segments get paired incorrectly.
In summary: this is a delimiter-determination problem in the Markdown inline parser.
Fixing It with a Hexo Filter
The official Hexo documentation says that filters are used to modify specific kinds of data, and multiple filters are executed in order. hexo-renderer-markdown-it provides the markdown-it:renderer filter, which gives you access to the markdown-it instance in use.
The solution: patch markdown-it's delimiter determination inside the markdown-it:renderer filter.
The reason: this bug occurs when the Markdown inline parser decides whether ** can open or close. Fixing the delimiter determination directly is closer to the root of the problem than writing regexes against Markdown strings or HTML strings.
This approach also avoids several headaches:
- No need to modify all the old posts.
- No need to touch
themes/fluid/. - No need to guess, in the rendered HTML, which
**are body text and which**are code. - It can cover mixed cases like
<u>...</u>, inline code, Chinese quotation marks, fullwidth parentheses, and so on, all at once.
The Plugin Code
This is a local script placed in Hexo's scripts/ directory. Hexo automatically loads scripts from there at startup.
The file is:
scripts/cjk-strong-emphasis.jsThe core entry point is very short:
hexo.extend.filter.register('markdown-it:renderer', patchCjkStrongEmphasis);After patchCjkStrongEmphasis gets the markdownIt instance, it modifies the inline parser:
代码
function patchCjkStrongEmphasis(markdownIt) {
if (!markdownIt || !markdownIt.inline || !markdownIt.inline.State) return;
const inlineState = markdownIt.inline.State.prototype;
if (inlineState[PATCH_FLAG]) return;
const scanDelims = inlineState.scanDelims;
inlineState.scanDelims = function patchedScanDelims(start, canSplitWord) {
const result = scanDelims.call(this, start, canSplitWord);
// 只处理 *,并且只处理长度至少为 2 的 ** / ****。
if (this.src.charCodeAt(start) !== ASTERISK || !canSplitWord || result.length < 2) {
return result;
}
const previousChar = charBefore(this.src, start);
const nextChar = charAt(this.src, start + result.length);
if (!result.can_open && shouldOpenStrongAfterCjk(this, previousChar, nextChar)) {
result.can_open = true;
}
if (!result.can_close && shouldCloseStrongNearCjk(this, previousChar, nextChar)) {
result.can_close = true;
}
return result;
};
inlineState[PATCH_FLAG] = true;
}There are a few details here.
First, only asterisks are handled, not underscores.
if (marker !== ASTERISK || !canSplitWord || result.length < 2) {
return result;
}The reason is that **粗体** is the most common form in Chinese articles. Meanwhile, _ / __ are more common in English words, variable names, and double-underscore identifiers, so loosening the rules for them could easily cause more collateral damage.
Second, the original scanDelims is called first.
const result = scanDelims.call(this, start, canSplitWord);This means Markdown that could already be parsed correctly is unaffected. The script only adds an extra check for Chinese/fullwidth contexts when the default rules yield can_open: false or can_close: false.
Third, Symbol.for is used for idempotency protection.
const PATCH_FLAG = Symbol.for('hexo-blog.cjkStrongEmphasisPatched');When Hexo renders multiple posts, the markdown-it:renderer filter is executed repeatedly. If a patch layer were added each time, the call chain would grow longer and longer. With the flag marking, the script only patches once.
How CJK and Fullwidth Contexts Are Determined
The script contains a function:
function isCjkOrFullwidth(char) {
return /[\u1100-\u11FF\u2018-\u201F\u2E80-\u303F\u3040-\u30FF\u3100-\u312F\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFF\uA960-\uA97F\uAC00-\uD7AF\uF900-\uFAFF\uFE10-\uFE1F\uFE30-\uFE6F\uFF00-\uFFEF]/u.test(char);
}It covers common Chinese, Japanese, and Korean characters, Chinese punctuation, fullwidth characters, and some of the ranges where Chinese quotation marks reside.
In addition, when determining punctuation, the script doesn't hardcode its own punctuation table but reuses markdown-it's utility functions:
function isPunct(state, char) {
if (!char) return false;
const codePoint = char.codePointAt(0);
return state.md.utils.isMdAsciiPunct(codePoint) || state.md.utils.isPunctChar(char);
}This keeps the behavior as consistent as possible with markdown-it's original punctuation determination.
Loosening Opening and Closing Delimiters Separately
The patch logic for opening delimiters is:
function shouldOpenStrongAfterCjk(state, previousChar, nextChar) {
return isCjkOrFullwidth(previousChar) && isPunct(state, nextChar);
}It handles cases like this:
中文**“条件”**在序列中The ** is preceded by Chinese and followed by a Chinese quotation mark. The default rules may consider this opening delimiter invalid, but for Chinese writing, this is a perfectly natural pattern.
The patch logic for closing delimiters is:
function shouldCloseStrongNearCjk(state, previousChar, nextChar) {
if (!isPunct(state, previousChar)) return false;
return isCjkOrFullwidth(previousChar)
|| isCjkOrFullwidth(nextChar)
|| previousChar === '>'
|| previousChar === '`';
}It handles several kinds of cases:
**一句话。**下一句
中文**“条件”**在序列中
中文**<u>重点</u>**后面
中文**`code`**后面Among these, previousChar === '>' covers cases ending with an HTML tag like </u>**后面, and previousChar === '`' covers cases ending with inline code like `code`**后面.
Verification
I used two layers of verification.
The first layer was rendering samples directly with the Hexo renderer:
const Hexo = require('hexo');
const hexo = new Hexo(process.cwd(), { silent: true });
await hexo.init();
const html = await hexo.render.render({
text: '中文**“条件”**在序列中',
engine: 'md'
});After the fix, the output is:
<p>中文<strong>“条件”</strong>在序列中</p>I also verified these cases:
**Java 字符串的一个重要特点就是字符串不可变。**这种不可变性
中文**“条件”**在序列中
中文**<u>粗体</u>**后面
中文**`code`**后面
中文**左值(lvalue)**和**右值(rvalue)**是
中文****粗体。****后面The second layer was running the Hexo build:
.\node_modules\.bin\hexo.cmd generate
.\node_modules\.bin\hexo.cmd generate --forceBoth commands passed without issues.
However, there is a small pitfall here: the old HTML in public/ won't necessarily reflect the new rules immediately, because Hexo may reuse the cache in db.json. To fully refresh the old posts, you can run the following after confirming everything is correct:
.\node_modules\.bin\hexo.cmd clean
.\node_modules\.bin\hexo.cmd generatehexo clean removes generated files and the cache, so I didn't run it casually while fixing the script, to avoid unnecessarily disturbing the local generated directory.
Summary
The key to this fix was not patching things up at the HTML level, but going back to the delimiter determination in the Markdown inline parser itself.
The final change is small — just one new local script:
scripts/cjk-strong-emphasis.jsAnd what it does is quite restrained:
- It only patches
markdown-it'sscanDelims. - It only handles
*, not_. - It only loosens the opening/closing determination of
**in CJK / fullwidth contexts. - Markdown that could already be parsed correctly still goes through the original logic.
For problems like this, if you only use regexes to scan Markdown or HTML, things tend to get messier the more you fix. Solving it at the parser's delimiter stage is actually the smaller, more stable change.
References: