monaco-editor

How to change the editor language?


In order to reuse the editor without having to dispose() and create() a new editor, the value can be changed with editor.setValue(). How can the language be changed (e.g. to 'css')?

const editor = monaco.editor.create(document.getElementById('container'), {
  value: ['function x() {', '\tconsole.log("Hello world!");', '}'].join('\n'),
  language: 'javascript'
});

Solution

  • You can use the setModeLanguage method:

    monaco.editor.setModelLanguage(editor.getModel(), 'css');
    

    Demo:

    let f = false
    const b = document.querySelector('button')
    b.onclick = () => monaco.editor.setModelLanguage(
        monaco.editor.getModel(model.uri), 
        (f = !f) ? 'css' : 'html'
    );
    <script type="module">
      import * as monaco from 'https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/+esm';
      
      const val = `<div>Test me</div>
    window { height: 100px; }`;
    
      const model = monaco.editor.createModel(val, 'html');
      monaco.editor.create(document.querySelector('.monaco'), {
          model: model
      });
      
      window.monaco = monaco
      window.model = model
    </script>
    
    <link href="https://cdn.jsdelivr.net/npm/vscode-codicons@0.0.17/dist/codicon.min.css" rel="stylesheet">
    <div class="monaco" style="min-height: 100px"></div>
    <button>Switch between HTML and CSS</button>