MCPcopy
hub / github.com/alibaba/page-agent / highlightSyntax

Function highlightSyntax

packages/website/src/components/HighlightSyntax.tsx:33–167  ·  view source on GitHub ↗
(code: string)

Source from the content-addressed store, hash-verified

31
32// 语法高亮函数,先提取 token 再转义和高亮
33function highlightSyntax(code: string): string {
34 // 构建正则模式,包含更多 token 类型(在原始文本上匹配)
35 const pattern = new RegExp(
36 '(' +
37 // 1. 字符串(双引号、单引号、模板字符串)
38 '"([^"\\\\]|\\\\.)*"|' +
39 "'([^'\\\\]|\\\\.)*'|" +
40 '`([^`\\\\]|\\\\.)*`|' +
41 // 2. 注释(单行和多行)
42 '//[^\\n]*|' +
43 '/\\*[\\s\\S]*?\\*/|' +
44 // 3. 装饰器
45 '@[a-zA-Z_$][\\w$]*|' +
46 // 4. 数字(包括小数、十六进制、科学计数法)
47 '\\b0[xX][0-9a-fA-F]+\\b|' +
48 '\\b\\d+\\.?\\d*(?:[eE][+-]?\\d+)?\\b|' +
49 // 5. TypeScript/JavaScript 关键字
50 '\\b(?:' +
51 keywords +
52 '|' +
53 tsKeywords +
54 '|' +
55 literals +
56 ')\\b|' +
57 // 6. TypeScript 内置类型
58 '\\b(?:' +
59 tsTypes +
60 ')\\b|' +
61 // 7. 箭头函数
62 '=>|' +
63 // 8. 函数调用(函数名后跟括号)
64 '\\b[a-zA-Z_$][\\w$]*(?=\\()|' +
65 // 9. 属性访问
66 '\\.[a-zA-Z_$][\\w$]*|' +
67 // 10. 运算符和特殊符号
68 '[+\\-*/%&|^!~<>=?:]+|' +
69 '[{}\\[\\]();,.]' +
70 ')',
71 'g'
72 )
73
74 const tokens: string[] = []
75 let lastIndex = 0
76 let match: RegExpExecArray | null
77 while ((match = pattern.exec(code)) !== null) {
78 if (match.index > lastIndex) {
79 const gap = code.slice(lastIndex, match.index)
80 // 将间隙按空白符分割,保留空白符
81 tokens.push(...gap.split(/(\s+)/))
82 }
83 tokens.push(match[0])
84 lastIndex = pattern.lastIndex
85 }
86 if (lastIndex < code.length) {
87 tokens.push(...code.slice(lastIndex).split(/(\s+)/))
88 }
89
90 const highlighted = tokens

Callers 1

HighlightSyntaxClientFunction · 0.85

Calls 1

escapeHtmlFunction · 0.70

Tested by

no test coverage detected