monaco editor自定义代码解析和代码高亮颜色配置

发布时间 2023-11-21 16:20:24作者: nicknames
//目前使用到的关于解析配置
export const language = {
  // 是否区分大小写,true区分
  ignoreCase:false,
  // 关键字 
  keywords: ['aaa','bbb'],
  // 类型关键字
  typeKeywords: [],
  // 代码解析配置格式为[正则表达式,对应的类型如(string,number,comment)]
  tokenizer: {
      // 解析的主入口,用于关联正则表达式和解析类型
    root: [
      [/real|discrete Real|Integer|Boolean|String|reinit/,'namespace'],
      // 关键字的匹配
      [/[a-z_$][\w$]*/, { cases: { '@typeKeywords': 'keyword',
                                   '@keywords': 'keyword',
                                   '@default': 'identifier' } }],
      // [/[A-Z][\w\$]*/, 'type.identifier' ],  // 高亮首字母大写的class
      // 注释
      // 可以理解为[正则表达式,匹配类型如(string,comment,namespace等),命名空间(可以理解为class)]
      // 以注释为例以下配置表示为检索到"后开始标识为注释,按照comment去配置
      [/"/, 'comment', '@comment'],
      // 可以同时对comment设置多组配置,用‘@类名’区分
      [/\/\*/, 'comment', '@commentT'],
      // include表示将@numbers的解析应用
      { include: '@numbers' }
    ],
    // 用于对应上方
    comment:[
      // 表示匹配到"后停止验证
      [/"/,'comment','@pop'],
      // escape表示在当前验证模式下忽略/\\"/匹配项
      [/\\"/,'comment.escape'],
      // content表示在这个验证模式下内容应该是那些/./表示所有包含换行,空格等字符
      [/./, 'comment.content']
      // 还有诸如@push等方法还没试
    ],
    commentT:[
      [/\*\//,'comment','@pop'],
      // 如需配置行注释则添加换行符等验证
      [/./, 'comment.content']
    ],
    // 对应{include:'@numbers'}
    numbers: [
      [/-?0x([abcdef]|[ABCDEF]|\d)+[lL]?/, 'number.hex'],
      [/-?(\d*\.)?\d+([eE][+\-]?\d+)?[jJ]?[lL]?/, 'number']
    ]
  }
};

// 颜色配置
monaco.editor.defineTheme('myTheme', { base: 'vs', rules: [ // 设置token颜色, { token: 'keyword', foreground: '#0000FF', fontStyle: 'bold' }, { token: 'number', foreground: '#FF6600', fontStyle: 'bold' }, { token: 'comment', foreground: '#999999' }, { token: 'namespace', foreground: '#FF0000' }, { token: 'variable', foreground: '#006699' } ], inherit: true, // 必须有否则无法生效 colors: {} }); monaco.editor.setTheme('myTheme'); public editorOptions = { value: this.modelCode, //和自己定义的名称对应 theme: 'myTheme', glyphMargin: true, language: 'modelica', automaticLayout: true, bracketPairColorization: true, lightbulb: { enabled: true }, minimap: { enabled: false }, folding: true, readOnly: false, domReadOnly: false }; monaco.editor.create( document.querySelector('#editor'), this.editorOptions );