atularen / ngx-monaco-editor

Monaco Editor component for Angular 2 and Above
https://www.npmjs.com/package/ngx-monaco-editor
MIT License
428 stars 155 forks source link

how to register a custom language ? #98

Open yvz5 opened 5 years ago

yvz5 commented 5 years ago

is there a way to register a custom language ?

atu1kr commented 5 years ago

Hope below links will help: https://github.com/atularen/ngx-monaco-editor/blob/7.0.0/README.md#configure-json-defaults https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages

yvz5 commented 5 years ago
// Register a tokens provider for the language
monaco.languages.setMonarchTokensProvider('mySpecialLanguage', {
    tokenizer: {
        root: [
            [/\[error.*/, "custom-error"],
            [/\[notice.*/, "custom-notice"],
            [/\[info.*/, "custom-info"],
            [/\[[a-zA-Z 0-9:]+\]/, "custom-date"],
        ]
    }
});

this does not compile.

maytanthegeek commented 5 years ago

@yvz5 specify the custom language in onMonacoLoad() in the config you pass to MonacoEditorModule like:

import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';

declare const monaco: any;

const monacoConfig: NgxMonacoEditorConfig = {
  onMonacoLoad() {
    // Register DeJoule language
    monaco.languages.register({ id: 'deJouleLanguage' });

    // Register a tokens provider for the language
    monaco.languages.setMonarchTokensProvider('deJouleLanguage', {
      tokenizer: {
        root: [
          [/[=><!~?:&|+\-*\/\^%]+/, 'arithmetic-op'],
          [/(?!and|or)[a-zA-Z ]+[A-Za-z]\((.*?)\)/, 'variables'],
          [/[0-9]+/, 'digits'],
          [/\b(and|or)\b/, 'logical-op'],
        ],
      },
    });
  },
};

@NgModule({
  imports: [
    MonacoEditorModule.forRoot(monacoConfig),
  ],
})
LironHazan commented 4 years ago

As far as I understand the config will be registered once per the module loading? but what about a case where you'll want a dynamic use, e.g. you're getting the lang tokens (and keywords, operators etc) from a server?

I wasn't sure how to tweak that and return a config to the module so I ended up inheriting EditorComponent and overriding the initMonaco method and from initMonaco one of the thing I'm doing is to setMonarchTokensProvider once I have all the tokens from the backend.

  static registerSyntaxHighlight(dynFields: IMonarchLanguageRule[]) {
    monaco.languages.register({ id: 'mylang' });
    // Following rules are used to color / syntax highlight
    monaco.languages.setMonarchTokensProvider('mylang', { ...........

It basically means that I bypassed the library model management and I'm handling everything from my own custom-lang-editor component but ngx-monaco still plays a major part in loading monaco globally with all its workers.