How to change display language on monaco editor

Viewed 5032

don`t know how to change display language from javascript to such as swift(or something else)

I installed using "npm install monaco-editor" command

    <script src="node_modules/monaco-editor/min/vs/loader.js"></script>
    <script>
    var editor;
    require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' 
    }});
    require(['vs/editor/editor.main'], function() {

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


    function showMessage() {
        var text = editor.getValue();
        monaco.editor.setModelLanguage(editor.getModel(), "swift")
        editor.updateOptions({
            language: "objective-c"
        });
        alert(text);
    }
</script>

I expect the after running showMessage function, display codes changes to objective-c from javascript. and actually error shows nothing. does anyone know how to do it ??

1 Answers

I'm not quite sure what you're trying to do, but I made this little function:

const changeLang = lang => {
    monaco.editor.setModelLanguage(editor.getModel(), lang);
    console.log(`model language was changed to ${editor.getModel().getLanguageIdentifier().language}`);
}

It changes the language and prints the new model language every time for me.

Your line editor.updateOptions({language: "objective-c"}) will not do anything. If you look at the docs, you'll see that ITextModelUpdateOptions only takes indentSize, insertSpaces, tabSize, or trimAutoWhitespace.

It looks like you might have been looking at the first couple answers of this github issue to make that line. That very first answer given is not correct.

You do text = editor.getValue() at the start of your function and alert(text) at the end, but text never changes. The model language will only affect the appearance, not the content. If you were only trying to get the static content, then the way you wrote it is fine. But if you were expecting it to change, it won't.

Related