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

本文介绍如何在Monaco Editor中实现自定义代码解析和设置代码高亮颜色,以达到个性化编辑体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 自定义代码解析

//目前使用到的关于解析配置
export const language = {
  // 是否区分大小写,true区分
  ignoreCase:false,
  // 关键字 
  keywords: ['aaa','bbb'],
  // 类型关键字
  typeKeywords: [],
  // 代码解析配置格式为[正则表达式,对应的类型如(string,number,comment)]
  tokenizer: {
      // 解析的主入口,用于关联正则表达式和解析类型
    root: [
      [/real/,'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'],
      // 单行注释
      [/\/\//,'comment','@commentL'],
      // 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']
    ],commentL:[
      [/.+/,'comment','@pop']
    ],
  }
};

自定义代码高亮颜色

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: 'language',
    automaticLayout: true,
    bracketPairColorization: true,
    lightbulb: {
      enabled: true
    },
    minimap: { enabled: false },
    folding: true,
    readOnly: false,
    domReadOnly: false
};


monaco.editor.create(
  document.querySelector('#editor'),
  this.editorOptions
);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值