Add CodeMirror to Skulpt Textarea

633 Views Asked by At

I am making an online python editor. I am using Skulpt to run the code entered into the texarea by the user. Here is my code:

HTML:

<script src="skulpt.min.js" type="text/javascript"></script> 
<script src="skulpt-stdlib.js" type="text/javascript"></script> 
<textarea id="textbox" cols="50" rows="10"></textarea>
<br /> 
<button type="button" onclick="runit()">Run</button> 
<pre id="dynamicframe"></pre>
<div id="canvas"></div>

Javascript:

function builtinRead(x) {
    if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
        throw "File not found: '" + x + "'";
    return Sk.builtinFiles["files"][x];
}

function runit() {
    var prog = document.getElementById("textbox").value;
    var mypre = document.getElementById("dynamicframe");
    mypre.innerHTML = '';
    Sk.pre = "output";
    Sk.configure({
        output: outf,
        read: builtinRead
    });
    (Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'canvas';
    var myPromise = Sk.misceval.asyncToPromise(function() {
        return Sk.importMainWithBody("<stdin>", false, prog, true);
    });
    myPromise.then(function(mod) {
            console.log('success');
        },
        function(err) {
            console.log(err.toString());
        });
}

I am new to CodeMirror, and I would like to use their python version to add code colouring, line numbering and indentation to my textarea, but I am a bit confused as to how I would go about changing my code to add these features, as I find their website a little vague on connecting their tool to textareas.

How can I use CodeMirror alongside my existing textarea?

1

There are 1 best solutions below

2
On BEST ANSWER

This is how I have added codemirror to highlight matching brackets in my textarea:

var editor = CodeMirror.fromTextArea(document.getElementByid('textbox'), {
                        mode: 'none',
                        matchBrackets: true,
                        dragDrop: false,
                        styleSelectedText: false,
                        showCursorWhenSelecting: true,
                        lineWrapping: true
                    });
var textAreaContents = editor.getDoc().getValue(); 

Thats all I had to do. You can tweak the configuration to tailor it e.g. setting the mode will highlight and optionally smart-indent text in a specific programming language.

Here is the fiddle that shows codemirror setup in the python mode with lineNumbers and indentation: https://jsfiddle.net/gw0shwok/2/

Configuration options for Python are documented here

Extra functionality is available via several addons