feat: 改进 Markdown 表格格式化,支持宽字符计算并改为居中对齐
continuous-integration/drone/push Build is passing

This commit is contained in:
seahi committed 2026-09-23 10:17:19 +08:00
1 parent 1e62d97d87
commit c8dda536ca
1 file changed
+22 -4
+22 -4
View File
@@ -5,15 +5,33 @@ import { syntaxTree } from '@codemirror/language';
function getDisplayLength(str: string): number {
let len = 0;
for (let i = 0; i < str.length; i++) {
len += str.charCodeAt(i) > 255 ? 2 : 1;
const c = str.charCodeAt(i);
// Check for CJK and Fullwidth characters
if (
(c >= 0x1100 && c <= 0x115f) || // Hangul Jamo
(c >= 0x2e80 && c <= 0xa4cf) || // CJK Radicals, Kangxi, Ideographs, etc.
(c >= 0xac00 && c <= 0xd7a3) || // Hangul Syllables
(c >= 0xf900 && c <= 0xfaff) || // CJK Compatibility Ideographs
(c >= 0xfe10 && c <= 0xfe19) || // Vertical forms
(c >= 0xfe30 && c <= 0xfe6f) || // CJK Compatibility Forms
(c >= 0xff00 && c <= 0xff60) || // Fullwidth Forms
(c >= 0xffe0 && c <= 0xffe6)
) {
len += 2;
} else {
len += 1;
}
}
return len;
}
function padEnd(str: string, targetLength: number): string {
function padCenter(str: string, targetLength: number): string {
const curLen = getDisplayLength(str);
if (curLen >= targetLength) return str;
return str + ' '.repeat(targetLength - curLen);
const padTotal = targetLength - curLen;
const padLeft = Math.floor(padTotal / 2);
const padRight = padTotal - padLeft;
return ' '.repeat(padLeft) + str + ' '.repeat(padRight);
}
export function formatMarkdownTable(tableStr: string): string {
@@ -65,7 +83,7 @@ export function formatMarkdownTable(tableStr: string): string {
} else {
const parts = colWidths.map((w, i) => {
const col = row[i] || '';
return padEnd(col, w);
return padCenter(col, w);
});
return '| ' + parts.join(' | ') + ' |';
}