javascriptangulartypescriptace-editor

How to highlight custom keywords in Ace Editor in Angular?


I'm trying to highlight a couple of keywords that are present in this.$rules . However I'm not able to get the final output . Can you please tell me what I'm missing here?

This is what I have tried inside an Angular component

Stackblitz

import {
 AfterViewInit,
 Component,
 ElementRef,
 OnInit,
 ViewChild,
} from '@angular/core';
import * as ace from 'ace-builds';

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

 constructor() {}

 ngAfterViewInit() {
   ace.config.set('fontSize', '14px');
   const editor = ace.edit(this.editor.nativeElement);
   const oop = ace.require('ace/lib/oop');
   const TextMode = ace.require('ace/mode/text').Mode;
   const TextHighlightRules = ace.require(
     'ace/mode/text_highlight_rules'
   ).TextHighlightRules;

   const customHighlightRules = function () {
     this.$rules = {
       start: [
         {
           regex: /\b(keyword1|keyword2)\b/,
           token: 'keyword',
         },
       ],
     };
   };

   oop.inherits(customHighlightRules, TextHighlightRules);

   const Mode = function () {
     this.HighlightRules = customHighlightRules;
   };

   oop.inherits(Mode, TextMode);

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

   // Set here
   editor.getSession().setMode(new (ace.require('ace/mode/custom').Mode)());
   
   editor.setValue('keyword1 some text keyword2', 1);
 }

 ngOnInit() {}
}


Solution

  • When setting mode simply do

    editor.session.setMode(new Mode());
    

    instead of .setMode(new (ace.require('ace/mode/custom').Mode)()).

    ace.require is not needed if you did not define the module with ace.define, and you have the object at hand anyway.

    https://stackblitz.com/edit/base-angular-12-app-krfkzr?file=src%2Fapp%2Fapp.component.ts