VitePress 中以中文字符结尾的字体加粗 Markdown 格式无法解析
背景
在编写vitepress项目过程中,发现了一个markdown格式解析的问题。
md文件中,以中文句号结尾的字体加粗,无法正确解析:
不只是中文句号,只要是加粗语句中以中文字符结尾,都无法被正确解析
需要将中文字符移动到外部,才能被解析为正确的markdown格式
但如果在typora笔记软件上的话,是一切正常的。
原因
在vitepess的github项目上发起了issue,收到外国coder的回复
以句号结尾的字体加粗md格式无法被正确解析 · Issue #4752 · vuejs/vitepress · GitHub
原因是这是markdown语法的规范,中文(CJK)用户来说是个问题,因为他们的文本周围没有空格
加粗语句星号后处加上空格就可以被正确解析。
解决方案
在项目的配置文件处加上以下markdown自定义解析代码。
import { defineConfig } from 'vitepress';export default defineConfig({markdown: {config(md) {// https://github.com/markdown-it/markdown-it/blob/a367c44154d6c906c8652ed779af6a21f7eaed2e/lib/rules_inline/state_inline.mjs#L88md.inline.State.prototype.scanDelims = function (start, canSplitWord) {const max = this.posMax;const marker = this.src.charCodeAt(start);// treat beginning of the line as a whitespaceconst lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20;let pos = start;while (pos < max && this.src.charCodeAt(pos) === marker) {pos++;}const count = pos - start;// treat end of the line as a whitespaceconst nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20;const isLastPunctChar = md.utils.isMdAsciiPunct(lastChar); // MODIFIEDconst isNextPunctChar = md.utils.isMdAsciiPunct(nextChar); // MODIFIEDconst isLastWhiteSpace = md.utils.isWhiteSpace(lastChar);const isNextWhiteSpace = md.utils.isWhiteSpace(nextChar);const left_flanking =!isNextWhiteSpace &&(!isNextPunctChar || isLastWhiteSpace || isLastPunctChar);const right_flanking =!isLastWhiteSpace &&(!isLastPunctChar || isNextWhiteSpace || isNextPunctChar);const can_open =left_flanking && (canSplitWord || !right_flanking || isLastPunctChar);const can_close =right_flanking && (canSplitWord || !left_flanking || isNextPunctChar);return { can_open, can_close, length: count };};},},
});