summaryrefslogtreecommitdiff
path: root/js/codeq/editor.js
blob: 157c70e55c3bc13ad2cdd9a14e66b7ff3ce652d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* CodeQ: an online programming tutor.
   Copyright (C) 2015 UL FRI

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */

codeq.makeEditor = function (elt, options, onEscape) {
    "use strict";
    var statusBar = $(elt).siblings(".block-statusbar")[0],
        updateStatusBar = function (pos) {
            statusBar.innerHTML = 'line ' + (pos.line+1) + ', column ' + (pos.ch+1);
        },
        allOptions = $.extend({
            cursorHeight: 0.85,
            lineNumbers: true,
            matchBrackets: true,
            extraKeys: {
                // allow a custom function to escape the editor (there is no blur)
                'Esc': onEscape || CodeMirror.Pass,
                // replace tabs with spaces
                'Tab': function (cm) {
                    var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
                    cm.replaceSelection(spaces);
                },
                // decrease indent if on first non-whitespace character in line
                'Backspace': function (cm) {
                    var doc = cm.getDoc(),
                        cursor = doc.getCursor(),
                        line = doc.getLine(cursor.line),
                        col = cursor.ch;
                    if (col > 0 && !/\S/.test(line.substring(0, col)) &&
                            (col === line.length || /\S/.test(line[col]))) {
                        // cursor on the first non-whitespace character in line
                        cm.execCommand('indentLess');
                    }
                    else {
                        cm.execCommand('delCharBefore');
                    }
                },
                'Shift-Tab': 'indentLess',
            }
        }, options),
        editor = CodeMirror(elt, allOptions);

    updateStatusBar({line: 0, ch: 0});
    editor.on('cursorActivity', function (instance) {
        var pos = instance.getDoc().getCursor();
        updateStatusBar(pos);
    });

    return editor;
};