首页 > 解决方案 > 如何在 Angular 应用程序中添加 ACE Editor 荧光笔规则?

问题描述

我尝试添加自定义荧光笔规则。我的示例基于thisthis

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

import * as ace from 'ace-builds';

import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/theme-github';
import 'ace-builds/src-noconflict/ext-language_tools';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  @ViewChild('codeEditor') codeEditorElmRef: ElementRef;
  private codeEditor: any;

  constructor() { }

  ngOnInit() {
    var oop = ace.require('ace/lib/oop');
    var textHighlightRules = ace.require('ace/mode/text_highlight_rules').TextHighlightRules;

    const $rules = {
      start: [
        {
          regex: /sometext/,
          token: "keyword"
        },
        {
          regex: /othertext/,
          token: "keyword"
        }
      ]
    };

    const customHighlightRules = function CustomHighlightRules() {
      this.$rules = $rules;
    };

    oop.inherits(customHighlightRules, textHighlightRules);

    //exports.MyNewHighlightRules = customHighlightRules; //??
    const element = this.codeEditorElmRef.nativeElement;

    const options = {
      minLines: 14,
      maxLines: Infinity,
      highlightSelectedWord: true,
      enableBasicAutocompletion: true,
      enableSnippets: true,
      enableLiveAutocompletion: true
    };

    this.codeEditor = ace.edit(element, options);
    this.codeEditor.setTheme('ace/theme/github');
    this.codeEditor.getSession().setMode('ace/mode/text');
    this.codeEditor.setShowFoldWidgets(true);
  }
}

我需要突出显示“sometext”。如何将此示例改编为角度和打字稿?我找不到任何使用与角度集成的工作示例。

标签: angulartypescriptace-editor

解决方案


您需要像这样创建 Mode 和 HighlightRules:

var oop = ace.require("ace/lib/oop");
var TextMode = ace.require("ace/mode/text").Mode;
var TextHighlightRules = ace.require("ace/mode/text_highlight_rules").TextHighlightRules;

var CustomHighlightRules = function(){
    this.$rules = {
        'start': [
            {
              regex: /\b(sometext|othertext)\b/,
              token: "keyword"
            }
        ]
    };
};

oop.inherits(CustomHighlightRules, TextHighlightRules);

var Mode = function() {
    this.HighlightRules = CustomHighlightRules;
};
oop.inherits(Mode,TextMode);

(function() {
    this.$id = "ace/mode/custom";
}).call(Mode.prototype);


element = document.body
this.codeEditor = ace.edit(element, {
    value: "sometext not othertext",
    minLines: 14,
    maxLines: Infinity,
    highlightSelectedWord: true,
    enableBasicAutocompletion: true,
    enableSnippets: true,
    enableLiveAutocompletion: true,
    theme: 'ace/theme/github',
    showFoldWidgets: true,
    mode: new Mode
});


推荐阅读