zikaari / monaco-editor-textmate

MIT License
122 stars 16 forks source link

Switching language using setModelLanguage does not work #13

Closed ashvin777 closed 4 years ago

ashvin777 commented 4 years ago

First I would like to thank you for developing this plugin. This is really helping me out to apply better syntax highlight in Monaco editor.

I had an issue where syntax highlight was not applying when I was switching the language of the same editor using monaco.editor.setModelLanguage option.

My grammar load file looks like below, I am setting grammer for required languages

import { loadWASM } from 'onigasm';
import { wireTmGrammars } from 'monaco-editor-textmate';
import { LanguageRegistry } from 'monaco-textmate-languages';
import * as monaco from 'monaco-editor';

import theme from './themes/DarkPlus.json';
monaco.editor.defineTheme('darkplus', theme);

(async () => {
  // See https://www.npmjs.com/package/onigasm#light-it-up
  await loadWASM(`/monaco/onigasm.wasm`);

  const registry = new LanguageRegistry({
    basePath: '/',
    textFetcher: async (uri) => {
      return (await fetch(uri)).text();
    }
  });

  // map of monaco "language id's" to TextMate scopeNames
  const grammars = new Map();

  grammars.set('css', 'source.css');
  grammars.set('less', 'source.less');
  grammars.set('scss', 'source.scss');

  grammars.set('html', 'text.html.basic');
  grammars.set('pug', 'text.pug');

  grammars.set('typescript', 'source.ts');
  grammars.set('javascript', 'source.js');

  await wireTmGrammars(monaco, registry, grammars);
})();

In Monaco editor component, I am instantiating like below (default language:css)

    this.editor = monaco.editor.create(current, {
      ...DEFAULT_EDITOR_PROPS,
      value: value || '',
      readOnly: readonly,
      language
    });

It works for the default language properly image

However when I switch the language of same editor using

    let model = this.editor.getModel();
    let currentLang = model._languageIdentifier.language;

    if (currentLang !== language) {
      monaco.editor.setModelLanguage(model, language);
    }

It turns off the syntax highlight image

I thought earlier that it could be scss grammer loading issue, however it was not because instantiating editor with default "scss" language does load properly image

Please let me know if I am missing anything.

zikaari commented 4 years ago

Please create a minimal codesandbox repro rig for me to inspect the situation. Thank you.

ashvin777 commented 4 years ago

Looks like I have fixed it by invoking the await wireTmGrammars(monaco, registry, grammars); everytime when I switch to a particular grammer. Closing this.