Pergunta

In my application I have a text area for text and a select list with languages that Code mirror supports. Can someone tell me how to change the mode (programming language) of the code mirror editor when the user selects a language from the select list? Do I need to load js files for the selected mode manually? Is there any setup needed to change that on the fly? Do I need to preload js files for all supported modes? Thank you!

Foi útil?

Solução

There's the loadmode addon that can help with that. See the demo for an example.

Outras dicas

Doing it in such way:

function loadModeForSelectedOption() {
    var script = $("#mode option:selected").attr('data-script');
    var mode = $("#mode option:selected").attr('data-mime-type');
    loadJS(script, function () {
        myCodeMirror.setOption("mode", mode);
    });
}

function loadJS(src, callback) {
    var s = document.createElement('script');
    s.src = src;
    s.async = true;
    s.onreadystatechange = s.onload = function () {
        var state = s.readyState;
        if (!callback.done && (!state || /loaded|complete/.test(state))) {
            callback.done = true;
            callback();
        }
    };
    document.getElementsByTagName('head')[0].appendChild(s);
}

And select list with languages (few examples):

<option value=108
        data-mime-type="text/x-csrc"
        data-script="/Scripts/codemirror-2.37/mode/clike/clike.js">
    C
</option>
<option value=110
        data-mime-type="text/x-csharp"
        data-script="/Scripts/codemirror-2.37/mode/clike/clike.js">
    C#
</option>
<option value=109
        data-mime-type="text/x-c++src"
        data-script="/Scripts/codemirror-2.37/mode/clike/clike.js">
    C++
</option>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top