Tips for incorporating ACE Editor syntax highlighting rules into an Angular application

I am attempting to create custom highlighter rules by referencing examples from here and here.

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);
  }
}

I want to highlight the keyword "sometext". How can I adapt this example for use with Angular and TypeScript? I have been unable to find any functional examples demonstrating integration with Angular.

Answer №1

To successfully implement both Mode and HighlightRules, follow this structure:

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
});

Answer №2

 const utility = ace.require('ace/lib/utility');
    const LanguageMode = ace.require("ace/mode/language").Mode;
    const HighlightRules = ace.require("ace/mode/highlight_rules").HighlightRules;

    const customRules = function CustomRules() {
      this.$rules = {
        'start': [
          {
            regex: /\b(someWord|otherWord)\b/,
            token: "keyword"
          }
        ]
      };
    };
    utility.inherits(customRules, HighlightRules);

    const MyMode = function() {
      this.HighlightRules = customRules;
    };
    utility.inherits(MyMode,LanguageMode);

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

    this.editor.getEditor().getSession().setMode(new MyMode)

Journeying from the future! Finally got it working after some persistence, thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Detecting Changes in the Backend with Angular

I'm curious about the best way to notify the frontend when there is a change in the backend. How can this situation be effectively handled? While developing an application on Azure, I have considered two possibilities, but none of them seem ideal. The ...

How can you ensure in Typescript that a function parameter belongs to a specific set of enumerated values?

Consider this example enum: export enum MyEnum { a = "a", b = "b", c = "c" } Now, let's define a function type where the parameter must be one of these values. For instance, myFunction("c") is acceptabl ...

Tips for incorporating live stock price updates into an Ionic application

Using a 3rd party API, I have successfully displayed a list of stock prices on cards. However, I am struggling to update the real-time data on each card with each second changes. I have attempted various methods, but the entire API is being fetched inste ...

A guide to sorting through in-app notifications in REACT-NATIVE based on their read status

Incorporating two headings, "Unread" and "Read", into the notification system is my goal. When opened, the Unread Notifications should be displayed beneath the Read notifications. This data is being retrieved from an API. Each notification contains a key ...

Make sure the subset interface is selected from the interface / Choose PickDeep<>?

I am searching for a solution using the following interface: interface Person { age: number, name: string, hometown?: { city: string, zip: number } } type SubPerson = EnsureSubInterface<Person, { name: string }> an example that w ...

How to store property transformation in Redux/ngrx

I have the following setup someReducer.ts export interface State { someProp: MyModel; } // some action listeners .. // // export const getProp = (state: State) => state.someProp; selector.ts export const getProperty = createSelector(getState, f ...

Using React.ReactNode as an argument in Storybook

This is a unique button component type that I have created import React from 'react' export type ButtonProps = { label: string; color?:'primary' | 'secondary' | 'tertiary'; size?:'mobile' | 'tabl ...

Issue: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]:

While I am going through a tutorial on the abp framework, I encountered an error with the Author route that says "ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelp ...

Expanding a class in Angular 2

I am attempting to enhance a method within the Angular package available at this link. import { Component, OnInit, Injectable } from '@angular/core'; import { FILE_UPLOAD_DIRECTIVES, FileUploader } from 'ng2-file-upload'; @Injectable ...

Using Angular 2/4/5 to Bind UTC-formatted Date to Datepicker

As someone who is just starting out with Angular and Angular Material, I have encountered an issue regarding zonedDate format for dates in my backend. The backend requires dates to be in zonedDate Format like this: 2018-04-11T02:12:04.455Z[UTC]. However, ...

Exploring Typescript's type narrowing capabilities through destructuring

This code snippet is encountering errors: type Example = { x: true, y: null, z: null } | { x: false, y: Error, z: null } | { x: false, y: null, z: { val: number} } function getExample(): Example { return { x: false, y: null, z: { val ...

What is the best method to completely uninstall Apollo-Angular along with all of its dependencies?

Once I added apollo-angular and @apollo/client to my project, I quickly realized that I no longer needed them. However, simply using "npm uninstall apollo-angular" and "npm uninstall @apollo/client" only removed the main folders but left behind other Apoll ...

Using Angular's routerLink feature to assign a specific outlet (version 5.0.2)

Despite reading numerous posts on this problem, none of the solutions seem to work for me. I am working with one app module, one routing module, and no additional modules. The issue I'm facing is that... Standard routes can be linked from any compo ...

What is the best way to add multiple elements to an array simultaneously?

I am facing an issue with my array arrayPath. I am pushing multiple values into it, but there are duplicates in the data. When the value of singleFile.originalFilename is a duplicate, I do not want to push that duplicate value into arrayPath. How can I ach ...

Is it possible to postpone the initiation of an Angular application until a promise is fulfilled

At the moment, my code looks like this: new Loader().load().then(() => { platformBrowserDynamic().bootstrapModule(AppModule); }); The issue lies in the fact that I only need to delay the execution of ngOnInit and any route resolving until a prom ...

Having trouble importing the UpgradeModule from @angularupgradestatic in Angular version 2.2.1

I am in the process of updating my AngularJS (ng1) application to Angular 2 (ng2). My Angular version is 2.2.1. Upon importing UpgradeModule from @angular\upgrade\static, I encountered the following exceptions: Uncaught SyntaxError: Unexpected ...

What is the correct way to set the default function parameter as `v => v` in JavaScript?

function customFunction<T, NT extends Record<string, string | number | boolean>>( data: T, normalize?: (data: T) => NT, ) { const normalizedData = normalize ? normalize(data) : {}; return Object.keys(normalizedData); } customFuncti ...

Sourcemaps experiencing major issues when using TypeScript and the browserify/gulp combination

Despite successfully generating sourcemaps from my build process using browserify with gulp, I encountered issues when trying to debug. Breakpoints would often jump to different lines in Chrome, indicating that the script was not pausing where it should. A ...

How to Transmit Information from a Parent Component to a Child Component in Angular 2 When the Parent Component's Button is Clicked

Within parentComponenet.html </div><button(click)="discoverClicked()">Discover</button></div> <child-component></child-component> In parentComponent.ts file export class parentComponent implements OnInit { discove ...

Encountered a Building Error: "The type .... is included in the declarations of two modules: AppModule and Ionic."

As I strive to generate my APK for Android, I executed the following command: ionic cordova run android --prod --release Version of Ionic being used: Ionic V3 My app currently does not employ lazy loading (I confess I am not even sure how to go about th ...