Exemplo n.º 1
0
var Mode = function(suppressHighlighting, doc, session) {

   // Keep references to current session, document
   this.$session = session;
   this.$doc = doc;

   // Only need one tokenizer for the document (we assume other rules
   // have been properly embedded)
   this.$tokenizer = new Tokenizer(new c_cppHighlightRules().getRules());

   // R-related tokenization
   this.$r_outdent = {};
   oop.implement(this.$r_outdent, RMatchingBraceOutdent);
   this.r_codeModel = new RCodeModel(doc, this.$tokenizer, /^r-/, /^\s*\/\*{3,}\s+(.*)\s*$/);

   // C/C++ related tokenization
   this.codeModel = new CppCodeModel(session, this.$tokenizer);
   
   this.$behaviour = new CStyleBehaviour(this.codeModel);
   this.$outdent = new MatchingBraceOutdent(this.codeModel);
   
   this.$sweaveBackgroundHighlighter = new SweaveBackgroundHighlighter(
      session,
         /^\s*\/\*{3,}\s+[Rr]\s*$/,
         /^\s*\*\/$/,
      true
   );

   if (!window.NodeWebkit)     
      this.foldingRules = new CppStyleFoldMode();

   this.$tokens = this.codeModel.$tokens;
   this.getLineSansComments = this.codeModel.getLineSansComments;

};
Exemplo n.º 2
0
(function() {
    oop.implement(this, EventEmitter);

    this.$scrollTop = 0;
    this.getScrollTop = function() { return this.$scrollTop; };
    this.setScrollTop = function(scrollTop) {
        scrollTop = Math.round(scrollTop);
        if (this.$scrollTop === scrollTop || isNaN(scrollTop))
            return;

        this.$scrollTop = scrollTop;
        this._signal("changeScrollTop", scrollTop);
    };

    this.$scrollLeft = 0;
    this.getScrollLeft = function() { return this.$scrollLeft; };
    this.setScrollLeft = function(scrollLeft) {
        scrollLeft = Math.round(scrollLeft);
        if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft))
            return;

        this.$scrollLeft = scrollLeft;
        this._signal("changeScrollLeft", scrollLeft);
    };

    
}).call(scrollable);
Exemplo n.º 3
0
var MsgStreamMock = module.exports = function() {

    oop.implement(this, EventEmitter);

    var self = this;
    this.requests = [];
    this.sendRequest = function(message) {
        self.requests.push(message);
    };

    this.$send = function(msg) {
        msg = JSON.parse(JSON.stringify(msg));
        this._signal("message", { data: msg });
    };
};
Exemplo n.º 4
0
var Mode = function(suppressHighlighting, doc, session) {
    this.$session = session;
    this.$tokenizer = new Tokenizer(new c_cppHighlightRules().getRules());
    this.$outdent = new MatchingBraceOutdent();
    this.$r_outdent = {};
    oop.implement(this.$r_outdent, RMatchingBraceOutdent);
    this.$behaviour = new CstyleBehaviour();
    this.codeModel = new RCodeModel(doc, this.$tokenizer, /^r-/, /^\s*\/\*{3,}\s+[Rr]\s*$/);
    this.$sweaveBackgroundHighlighter = new SweaveBackgroundHighlighter(
        session,
        /^\s*\/\*{3,}\s+[Rr]\s*$/,
        /^\*\/$/,
        true);
    this.foldingRules = new CppStyleFoldMode();

};
Exemplo n.º 5
0
(function() {

    oop.implement(this, EventEmitter);
    
    this.addBuffer = function(buffer) {
        this._buffers.push(buffer);
        return this._buffers.length-1;
    };
    
    this.addWindow = function(win) {
        this._windows.push(win);
        return this._windows.length-1;
    };
    
    this.openInWindow = function(bufferId, winId) {
        this._windows[winId || 0].setBuffer(this._buffers[bufferId]);
    };
    
}).call(Editor.prototype);
Exemplo n.º 6
0
var Mode = function(suppressHighlighting, doc, session) {
   var that = this;

   this.$session = session;
   this.$tokenizer = new Tokenizer(new RMarkdownHighlightRules().getRules());

   this.$outdent = new MatchingBraceOutdent();
   this.$r_outdent = {};
   oop.implement(this.$r_outdent, RMatchingBraceOutdent);

   this.codeModel = new RCodeModel(doc, this.$tokenizer, /^r-/,
                                   /^`{3,}\s*\{r(.*)\}\s*$/);

   var markdownFoldingRules = new MarkdownFoldMode();

   this.foldingRules = {

      getFoldWidget: function(session, foldStyle, row) {
         if (that.getLanguageMode({row: row, column: 0}) == "Markdown")
            return markdownFoldingRules.getFoldWidget(session, foldStyle, row);
         else
            return that.codeModel.getFoldWidget(session, foldStyle, row);
      },

      getFoldWidgetRange: function(session, foldStyle, row) {
         if (that.getLanguageMode({row: row, column: 0}) == "Markdown")
            return markdownFoldingRules.getFoldWidgetRange(session, foldStyle, row);
         else
            return that.codeModel.getFoldWidgetRange(session, foldStyle, row);
      }

   };   

   this.$sweaveBackgroundHighlighter = new SweaveBackgroundHighlighter(
         session,
         /^`{3,}\s*\{r(?:.*)\}\s*$/,
         /^`{3,}\s*$/,
         true);
};
Exemplo n.º 7
0
(function(){
    oop.implement(this, EventEmitter);
    
    this.token = {};
    this.range = new Range();

    this.update = function() {
        this.$timer = null;
        var editor = this.editor;
        var renderer = editor.renderer;
        
        var canvasPos = renderer.scroller.getBoundingClientRect();
        var offset = (this.x + renderer.scrollLeft - canvasPos.left - renderer.$padding) / renderer.characterWidth;
        var row = Math.floor((this.y + renderer.scrollTop - canvasPos.top) / renderer.lineHeight);
        var col = Math.round(offset);

        var screenPos = {row: row, column: col, side: offset - col > 0 ? 1 : -1};
        var session = editor.session;
        var docPos = session.screenToDocumentPosition(screenPos.row, screenPos.column);
        
        var selectionRange = editor.selection.getRange();
        if (!selectionRange.isEmpty()) {
            if (selectionRange.start.row <= row && selectionRange.end.row >= row)
                return this.clear();
        }
        
        var line = editor.session.getLine(docPos.row);
        if (docPos.column == line.length) {
            var clippedPos = editor.session.documentToScreenPosition(docPos.row, docPos.column);
            if (clippedPos.column != screenPos.column) {
                return this.clear();
            }
        }
        
        var token = this.findLink(docPos.row, docPos.column);
        // var isFocused = editor.isFocused();
        this.link = token;
        if (!token) {
            return this.clear();
        }
        if (!this.isOpen) {
            this.isOpen = true;
        }
        // token.isFocused = isFocused;
        editor.renderer.setCursorStyle("pointer");
        
        session.removeMarker(this.marker);
        
        this.range = this.getRange(token);
        this.marker = session.addMarker(this.range, "ace_link_marker", "text", true);
    };
    
    this.clear = function() {
        if (this.isOpen) {
            this.editor.session.removeMarker(this.marker);
            this.editor.renderer.setCursorStyle("");
            this.isOpen = false;
        }
    };
    
    this.getMatchAround = function(regExp, string, col) {
        var match;
        regExp.lastIndex = 0;
        string.replace(regExp, function(str) {
            var offset = arguments[arguments.length-2];
            var length = str.length;
            if (offset <= col && offset + length >= col)
                match = {
                    start: offset,
                    value: str
                };
        });
    
        return match;
    };
    
    this.onClick = function(e) {
        if (!this.editor.isFocused())
            return;
        
        if (this.link && this.isOpen) { // && this.link.isFocused
            if (this.editor.selection.isEmpty()) {
                this.editor.selection.setSelectionRange(this.range);
                this.lastRange = this.range;
            }
            
            this.link.editor = this.editor;
            this.link.x = e.clientX;
            this.link.y = e.clientY;
            this.link.metaKey = e.metaKey;
            this.link.ctrlKey = e.ctrlKey;
            this._signal("open", this.link);
        }
    };
    
    this.onContextMenu = function(e) {
        var range = this.editor.selection.getRange();
        if (!range.isEmpty()) {
            if (this.lastRange && range.isEqual(this.lastRange)) {
                this.editor.selection.clearSelection();
                this.update();
            }
        }
        if (this.link && this.isOpen) {
            if (this.editor.selection.isEmpty()) {
                this.editor.selection.setSelectionRange(this.range);
                this.lastRange = this.range;
            }
        }
    };
    
    this.getRange = function(token) {
        var session = this.editor.session;
        var startCol = token.start;
        var row = token.row;
        var line = session.getLine(row);
        while (line && line.length < startCol) {
            startCol -= line.length;
            row++;
            line = session.getLine(row);
        }
        var startRow = row;
        var endCol = startCol + token.value.length;
        while (line && line.length < endCol) {
            endCol -= line.length;
            row++;
            line = session.getLine(row);
        }
        var endRow = row;
        return new Range(startRow, startCol, endRow, endCol);
    };
    
    this.findLink = function(row, column) {
        var editor = this.editor;
        var session = editor.session;
        var lineData = session.getLineData(row);
        var prevLineData = session.getLineData(row - 1);
        var line = session.getLine(row);
        for (var i = 1; lineData && lineData.wrapped; i++) {
            line += session.getLine(row + i);
            lineData = session.getLineData(row + i);
        }
        while (prevLineData && prevLineData.wrapped) {
            row --;
            var prevLine = session.getLine(row);
            column += prevLine.length;
            line = prevLine + line;
            prevLineData = session.getLineData(row - 1);
        }
        lineData = session.getLineData(row);
        
        var match = this.getMatchAround(/https?:\/\/[^\s"']+|[~\/\w.]([:.~/\w-_]|\\.)+/g, line, column);
        if (!match)
            return;
        
        match.row = row;
        var value = match.value;
        if (/^https?:|\bc9.io\b|(\d{1,3}\b.?){4}|localhost/.test(value)) {
            match.type = "link";
            var m =  /((https?:\/\/)?(\d{1,3}\b.?){4}(:\d+[^\d\/]|[^:\d\/]))/.exec(value);
            if (m)
                value = m[0].slice(0, -1);
            value = value.replace(/[>)}\].,;:]+$/, "");
            match.value = value;
            return match;
        }
        var prompt = this.findPrompt(row);
        if (!prompt) {
            if (/^(\/|~|\/?\w:[\\/])/.test(value)) { // windows or unix absolute path
                match.type = "path";
                match.value = value.replace(/["'>)}\].,;:]+$/, "");
                return match;
            }
            return;
        }
        
        if (lineData.prompt && match.start <= prompt.index) {
            match.value = value = value.substr(prompt.index - match.start);
            match.start = prompt.index;
            if (match.start > column || !value)
                return;
            return;
        }
        
        match.command = prompt.command;
        match.args = prompt.args;
        match.basePath = prompt.path;
        
        if (prompt.command === "ls") {
            match.type = "path";
            if (lineData.prompt)
                return;
            // update basepath for ls /dir/name    
            if (prompt.args)
                match.basePath = this.findBasePath(prompt.args, prompt.path);
            if (prompt.args && /( |^)(--help|-h)\b/.test(prompt.args))
                return;
            var longStyle = /(^|\s)[ld\-][\-rwx]+\s/.test(line);
            if (longStyle) {
                if (/[*@|=>]$/.test(line))
                    line = line.slice(0, -1);
                if (match.start + value.length < line.length) {
                    var isLink = line[0] == "l" && line.substr(match.start + value.length, 4) == " -> ";
                    if (!isLink)
                        return;
                }
            } else {
                var before = line.substring(0, match.start).match(/[^\s\\\/@"']+ $/);
                var after = line.substr(match.start + value.length).match(/^ [^\s\\\/@"']+/);
                if (before && !/\d+/.test(before[0])) {
                    value = before[0] + value;
                    match.start -= before[0].length;
                }
                if (after) {
                    value += after[0];
                }
                match.value = value;
                return match;
            }
        }
        else if (prompt.command === "find") {
            if (match.start !== 0 || match.length < line.length)
                return;
            if (prompt.args)
                match.basePath = this.findBasePath(prompt.args, prompt.path);
            match.type = "path";
        }
        else if (prompt.command === "grep") {
            if (match.start !== 0)
                return;
            match.type = "path";
            match.value = value.replace(/:[^\d][^:]*$/, "");
            // match.basePath = "";
        }
        else if (prompt.command === "ack" || prompt.command === "ag" || prompt.command === "ack-grep") {
            match.type = "path";
            var fontColor = lineData[column] && lineData[column][0];
            if (match.start !== 0) {
                if (fontColor == session.term.defAttr)
                    return;
                
                var col = column;
                while (lineData[col] && lineData[col][0] == fontColor)
                    col--;
                match.start = col + 1;
                col = column;
                while (lineData[col] && lineData[col][0] == fontColor)
                    col++;
                match.value = line.substring(match.start, col);
            }
            
            var jumpLine = line.match(/^(\d*:)?/)[0];
            var jumpColumn = Math.max(match.start - jumpLine.length, 0);
            
            if (match.start == 0 && jumpLine)
                match.value = jumpLine;
            
            var pathLine = line;
            while (/^\d+/.test(pathLine) && row > prompt.row) {
                lineData = session.getLineData(row);
                if (!lineData.wrapped) {
                    pathLine = session.getLine(row);
                }
                row--;
            }
            
            match.path = pathLine;
            if (jumpLine)
                match.path += ":" + jumpLine + jumpColumn;
            
            if (match.start == 0 && jumpLine)
                match.action = "open";
        }
        else if (/^(~|\.\.?)?[\/\\]/.test(value) || /\w:[\\]/.test(value)) {
            match.type = "path";
            match.value = value.replace(/['">)}\].,;:]+$/, "");
        }
        else if (/^[ab]?\//.test(value) && /^([+\-]{3}|diff)/.test(line)) { // diff
            match.type = "path";
            match.basePath = "";
            match.start++;
            match.value = value.substr(2);
        }
        else if (prompt.command === "git") { // git status
            var prefix = line.substr(0, match.start);
            if (match.start + value.length == line.length
                && /^(#|[ MDRU?A]{2})\s+([\w\s]+:\s+)?$/.test(prefix)
            ) {
                match.type = "path";
            } else {
                value = value.replace(/[.:]$/, "");
                if (value.match(/[/][^/]*\.\w+[.:]$/) || prefix.match(/( in |merging )$/)) {
                    match.type = "path";
                    match.value = value;
                } else {
                    return;
                }
            }
        } else {
            return;
        }
        
        return match;
    };
    
    this.findBasePath = function(args, basePath) {
        var argList = args.split(" ").filter(function(x) {
            return x[0] != "-";
        });
        var pathArg = argList[argList.length - 1];
        if (pathArg) {
            if (pathArg[0] === "~" || pathArg[0] === "/")
                return pathArg;
            return basePath + "/" + pathArg;
        }
        return basePath;
    };

    this.findPrompt = function(row) {
        var promptRe = /([~\/](?:[^\\\s'"\(<]|\\.)*)[^$]*?\$/;
        var editor = this.editor;
        var session = editor.session;
        var prompt, args, command, promptRow;
        do {
            var lineData = session.getLineData(row);
            
            if (lineData.prompt)
                return lineData.prompt;
            
            var line = session.getLine(row);
            var m = promptRe.exec(line);
            if (m) {
                line = line.substr(m.index + m[0].length);
                var m2 = /^\s*([\w\-]+)/.exec(line);
                if (m2) {
                    command = m2[1];
                    args = line.substr(m2[0].length);
                }
                if (!prompt || lineData.isUserInput) {
                    prompt = {
                        path: m[1],
                        command: command,
                        index: m.index,
                        args: args,
                        lineData: lineData,
                        row: row
                    };
                }
                if (lineData.isUserInput)
                    break;
            }
        } while (row-- > 0);
        if (prompt && promptRow < session.term.ybase)
            prompt.lineData.prompt = prompt;
        return prompt;
    };

    this.onMouseMove = function(e) {
        if (e.shiftKey || e.ctrlKey || e.metaKey || !this.editor.isFocused())
            return this.clear();
        
        if (this.editor.$mouseHandler.isMousePressed) {
            if (!this.editor.selection.isEmpty())
                this.clear();
            return;
        }
        if (this.x == e.clientX && this.y == e.clientY)
            return;
        this.x = e.clientX;
        this.y = e.clientY;
        if (this.isOpen) {
            this.lastT = e.timeStamp;
        }
        this.update();
    };

    this.onMouseOut = function(e) {
        this.clear();
        this.$timer = clearTimeout(this.$timer);
    };

    this.destroy = function() {
        this.onMouseOut();
        event.removeListener(this.editor.renderer.scroller, "mousemove", this.onMouseMove);
        event.removeListener(this.editor.renderer.content, "mouseout", this.onMouseOut);
        delete this.editor.hoverLink;
    };

}).call(HoverLink.prototype);
Exemplo n.º 8
0
(function() {

    oop.implement(this, EventEmitter);

    this.EOF_CHAR = "\xB6";
    this.EOL_CHAR_LF = "\xAC";
    this.EOL_CHAR_CRLF = "\xa4";
    this.EOL_CHAR = this.EOL_CHAR_LF;
    this.TAB_CHAR = "\u2014"; //"\u21E5";
    this.SPACE_CHAR = "\xB7";
    this.$padding = 0;

    this.$updateEolChar = function() {
        var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n"
           ? this.EOL_CHAR_LF
           : this.EOL_CHAR_CRLF;
        if (this.EOL_CHAR != EOL_CHAR) {
            this.EOL_CHAR = EOL_CHAR;
            return true;
        }
    }

    this.setPadding = function(padding) {
        this.$padding = padding;
        this.element.style.padding = "0 " + padding + "px";
    };

    this.getLineHeight = function() {
        return this.$fontMetrics.$characterSize.height || 0;
    };

    this.getCharacterWidth = function() {
        return this.$fontMetrics.$characterSize.width || 0;
    };
    
    this.$setFontMetrics = function(measure) {
        this.$fontMetrics = measure;
        this.$fontMetrics.on("changeCharacterSize", function(e) {
            this._signal("changeCharacterSize", e);
        }.bind(this));
        this.$pollSizeChanges();
    }

    this.checkForSizeChanges = function() {
        this.$fontMetrics.checkForSizeChanges();
    };
    this.$pollSizeChanges = function() {
        return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges();
    };
    this.setSession = function(session) {
        this.session = session;
        if (session)
            this.$computeTabString();
    };

    this.showInvisibles = false;
    this.setShowInvisibles = function(showInvisibles) {
        if (this.showInvisibles == showInvisibles)
            return false;

        this.showInvisibles = showInvisibles;
        this.$computeTabString();
        return true;
    };

    this.displayIndentGuides = true;
    this.setDisplayIndentGuides = function(display) {
        if (this.displayIndentGuides == display)
            return false;

        this.displayIndentGuides = display;
        this.$computeTabString();
        return true;
    };

    this.$tabStrings = [];
    this.onChangeTabSize =
    this.$computeTabString = function() {
        var tabSize = this.session.getTabSize();
        this.tabSize = tabSize;
        var tabStr = this.$tabStrings = [0];
        for (var i = 1; i < tabSize + 1; i++) {
            if (this.showInvisibles) {
                tabStr.push("<span class='ace_invisible ace_invisible_tab'>"
                    + lang.stringRepeat(this.TAB_CHAR, i)
                    + "</span>");
            } else {
                tabStr.push(lang.stringRepeat(" ", i));
            }
        }
        if (this.displayIndentGuides) {
            this.$indentGuideRe =  /\s\S| \t|\t |\s$/;
            var className = "ace_indent-guide";
            var spaceClass = "";
            var tabClass = "";
            if (this.showInvisibles) {
                className += " ace_invisible";
                spaceClass = " ace_invisible_space";
                tabClass = " ace_invisible_tab";
                var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize);
                var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize);
            } else{
                var spaceContent = lang.stringRepeat(" ", this.tabSize);
                var tabContent = spaceContent;
            }

            this.$tabStrings[" "] = "<span class='" + className + spaceClass + "'>" + spaceContent + "</span>";
            this.$tabStrings["\t"] = "<span class='" + className + tabClass + "'>" + tabContent + "</span>";
        }
    };

    this.updateLines = function(config, firstRow, lastRow) {
        if (this.config.lastRow != config.lastRow ||
            this.config.firstRow != config.firstRow) {
            this.scrollLines(config);
        }
        this.config = config;

        var first = Math.max(firstRow, config.firstRow);
        var last = Math.min(lastRow, config.lastRow);

        var lineElements = this.element.childNodes;
        var lineElementsIdx = 0;

        for (var row = config.firstRow; row < first; row++) {
            var foldLine = this.session.getFoldLine(row);
            if (foldLine) {
                if (foldLine.containsRow(first)) {
                    first = foldLine.start.row;
                    break;
                } else {
                    row = foldLine.end.row;
                }
            }
            lineElementsIdx ++;
        }

        var row = first;
        var foldLine = this.session.getNextFoldLine(row);
        var foldStart = foldLine ? foldLine.start.row : Infinity;

        while (true) {
            if (row > foldStart) {
                row = foldLine.end.row+1;
                foldLine = this.session.getNextFoldLine(row, foldLine);
                foldStart = foldLine ? foldLine.start.row :Infinity;
            }
            if (row > last)
                break;

            var lineElement = lineElements[lineElementsIdx++];
            if (lineElement) {
                var html = [];
                this.$renderLine(
                    html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false
                );
                lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px";
                lineElement.innerHTML = html.join("");
            }
            row++;
        }
    };

    this.scrollLines = function(config) {
        var oldConfig = this.config;
        this.config = config;

        if (!oldConfig || oldConfig.lastRow < config.firstRow)
            return this.update(config);

        if (config.lastRow < oldConfig.firstRow)
            return this.update(config);

        var el = this.element;
        if (oldConfig.firstRow < config.firstRow)
            for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--)
                el.removeChild(el.firstChild);

        if (oldConfig.lastRow > config.lastRow)
            for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--)
                el.removeChild(el.lastChild);

        if (config.firstRow < oldConfig.firstRow) {
            var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1);
            if (el.firstChild)
                el.insertBefore(fragment, el.firstChild);
            else
                el.appendChild(fragment);
        }

        if (config.lastRow > oldConfig.lastRow) {
            var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow);
            el.appendChild(fragment);
        }
    };

    this.$renderLinesFragment = function(config, firstRow, lastRow) {
        var fragment = this.element.ownerDocument.createDocumentFragment();
        var row = firstRow;
        var foldLine = this.session.getNextFoldLine(row);
        var foldStart = foldLine ? foldLine.start.row : Infinity;

        while (true) {
            if (row > foldStart) {
                row = foldLine.end.row+1;
                foldLine = this.session.getNextFoldLine(row, foldLine);
                foldStart = foldLine ? foldLine.start.row : Infinity;
            }
            if (row > lastRow)
                break;

            var container = dom.createElement("div");

            var html = [];
            this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
            container.innerHTML = html.join("");
            if (this.$useLineGroups()) {
                container.className = 'ace_line_group';
                fragment.appendChild(container);
                container.style.height = config.lineHeight * this.session.getRowLength(row) + "px";

            } else {
                while(container.firstChild)
                    fragment.appendChild(container.firstChild);
            }

            row++;
        }
        return fragment;
    };

    this.update = function(config) {
        this.config = config;

        var html = [];
        var firstRow = config.firstRow, lastRow = config.lastRow;

        var row = firstRow;
        var foldLine = this.session.getNextFoldLine(row);
        var foldStart = foldLine ? foldLine.start.row : Infinity;

        while (true) {
            if (row > foldStart) {
                row = foldLine.end.row+1;
                foldLine = this.session.getNextFoldLine(row, foldLine);
                foldStart = foldLine ? foldLine.start.row :Infinity;
            }
            if (row > lastRow)
                break;

            if (this.$useLineGroups())
                html.push("<div class='ace_line_group' style='height:", config.lineHeight*this.session.getRowLength(row), "px'>")

            this.$renderLine(html, row, false, row == foldStart ? foldLine : false);

            if (this.$useLineGroups())
                html.push("</div>"); // end the line group

            row++;
        }
        this.element.innerHTML = html.join("");
    };

    this.$textToken = {
        "text": true,
        "rparen": true,
        "lparen": true
    };

    this.$renderToken = function(stringBuilder, screenColumn, token, value) {
        var self = this;
        var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g;
        var replaceFunc = function(c, a, b, tabIdx, idx4) {
            if (a) {
                return self.showInvisibles
                    ? "<span class='ace_invisible ace_invisible_space'>" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "</span>"
                    : c;
            } else if (c == "&") {
                return "&#38;";
            } else if (c == "<") {
                return "&#60;";
            } else if (c == ">") {
                return "&#62;";
            } else if (c == "\t") {
                var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx);
                screenColumn += tabSize - 1;
                return self.$tabStrings[tabSize];
            } else if (c == "\u3000") {
                var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk";
                var space = self.showInvisibles ? self.SPACE_CHAR : "";
                screenColumn += 1;
                return "<span class='" + classToUse + "' style='width:" +
                    (self.config.characterWidth * 2) +
                    "px'>" + space + "</span>";
            } else if (b) {
                return "<span class='ace_invisible ace_invisible_space ace_invalid'>" + self.SPACE_CHAR + "</span>";
            } else {
                screenColumn += 1;
                return "<span class='ace_cjk' style='width:" +
                    (self.config.characterWidth * 2) +
                    "px'>" + c + "</span>";
            }
        };

        var output = value.replace(replaceReg, replaceFunc);

        if (!this.$textToken[token.type]) {
            var classes = "ace_" + token.type.replace(/\./g, " ace_");
            var style = "";
            if (token.type == "fold")
                style = " style='width:" + (token.value.length * this.config.characterWidth) + "px;' ";
            stringBuilder.push("<span class='", classes, "'", style, ">", output, "</span>");
        }
        else {
            stringBuilder.push(output);
        }
        return screenColumn + value.length;
    };

    this.renderIndentGuide = function(stringBuilder, value, max) {
        var cols = value.search(this.$indentGuideRe);
        if (cols <= 0 || cols >= max)
            return value;
        if (value[0] == " ") {
            cols -= cols % this.tabSize;
            stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize));
            return value.substr(cols);
        } else if (value[0] == "\t") {
            stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols));
            return value.substr(cols);
        }
        return value;
    };

    this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) {
        var chars = 0;
        var split = 0;
        var splitChars = splits[0];
        var screenColumn = 0;

        for (var i = 0; i < tokens.length; i++) {
            var token = tokens[i];
            var value = token.value;
            if (i == 0 && this.displayIndentGuides) {
                chars = value.length;
                value = this.renderIndentGuide(stringBuilder, value, splitChars);
                if (!value)
                    continue;
                chars -= value.length;
            }

            if (chars + value.length < splitChars) {
                screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
                chars += value.length;
            } else {
                while (chars + value.length >= splitChars) {
                    screenColumn = this.$renderToken(
                        stringBuilder, screenColumn,
                        token, value.substring(0, splitChars - chars)
                    );
                    value = value.substring(splitChars - chars);
                    chars = splitChars;

                    if (!onlyContents) {
                        stringBuilder.push("</div>",
                            "<div class='ace_line' style='height:",
                            this.config.lineHeight, "px'>"
                        );
                    }

                    stringBuilder.push(lang.stringRepeat("\xa0", splits.indent));

                    split ++;
                    screenColumn = 0;
                    splitChars = splits[split] || Number.MAX_VALUE;
                }
                if (value.length != 0) {
                    chars += value.length;
                    screenColumn = this.$renderToken(
                        stringBuilder, screenColumn, token, value
                    );
                }
            }
        }
    };

    this.$renderSimpleLine = function(stringBuilder, tokens) {
        var screenColumn = 0;
        var token = tokens[0];
        var value = token.value;
        if (this.displayIndentGuides)
            value = this.renderIndentGuide(stringBuilder, value);
        if (value)
            screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
        for (var i = 1; i < tokens.length; i++) {
            token = tokens[i];
            value = token.value;
            screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
        }
    };
    this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) {
        if (!foldLine && foldLine != false)
            foldLine = this.session.getFoldLine(row);

        if (foldLine)
            var tokens = this.$getFoldLineTokens(row, foldLine);
        else
            var tokens = this.session.getTokens(row);


        if (!onlyContents) {
            stringBuilder.push(
                "<div class='ace_line' style='height:", 
                    this.config.lineHeight * (
                        this.$useLineGroups() ? 1 :this.session.getRowLength(row)
                    ), "px'>"
            );
        }

        if (tokens.length) {
            var splits = this.session.getRowSplitData(row);
            if (splits && splits.length)
                this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents);
            else
                this.$renderSimpleLine(stringBuilder, tokens);
        }

        if (this.showInvisibles) {
            if (foldLine)
                row = foldLine.end.row

            stringBuilder.push(
                "<span class='ace_invisible ace_invisible_eol'>",
                row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR,
                "</span>"
            );
        }
        if (!onlyContents)
            stringBuilder.push("</div>");
    };

    this.$getFoldLineTokens = function(row, foldLine) {
        var session = this.session;
        var renderTokens = [];

        function addTokens(tokens, from, to) {
            var idx = 0, col = 0;
            while ((col + tokens[idx].value.length) < from) {
                col += tokens[idx].value.length;
                idx++;

                if (idx == tokens.length)
                    return;
            }
            if (col != from) {
                var value = tokens[idx].value.substring(from - col);
                if (value.length > (to - from))
                    value = value.substring(0, to - from);

                renderTokens.push({
                    type: tokens[idx].type,
                    value: value
                });

                col = from + value.length;
                idx += 1;
            }

            while (col < to && idx < tokens.length) {
                var value = tokens[idx].value;
                if (value.length + col > to) {
                    renderTokens.push({
                        type: tokens[idx].type,
                        value: value.substring(0, to - col)
                    });
                } else
                    renderTokens.push(tokens[idx]);
                col += value.length;
                idx += 1;
            }
        }

        var tokens = session.getTokens(row);
        foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
            if (placeholder != null) {
                renderTokens.push({
                    type: "fold",
                    value: placeholder
                });
            } else {
                if (isNewRow)
                    tokens = session.getTokens(row);

                if (tokens.length)
                    addTokens(tokens, lastColumn, column);
            }
        }, foldLine.end.row, this.session.getLine(foldLine.end.row).length);

        return renderTokens;
    };

    this.$useLineGroups = function() {
        return this.session.getUseWrapMode();
    };

    this.destroy = function() {
        clearInterval(this.$pollSizeChangesTimer);
        if (this.$measureNode)
            this.$measureNode.parentNode.removeChild(this.$measureNode);
        delete this.$measureNode;
    };

}).call(Text.prototype);
Exemplo n.º 9
0
define(function(require, exports, module) {
var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var EventEmitter = require("ace/lib/event_emitter").EventEmitter;
var ace = require("ace/ace");
var Range = require("ace/range").Range;
// @todo this is too broad
var Client = require("ext/ot/client");
var OTDocument = Client.OTDocument;

var ui = {
    canEdit: function() {return true;}
};
var editors = [];
var join = function(id) {
    var editor = ace.edit(id);
    id = editors.push(editor) - 1;
    editor.otDoc = new OTDocument(editor.session, ui);
    
    editor.outgoing = [];
    editor.incoming = [];
    
    editor.otDoc.init({
        "userId": id,
        "clientId": id,
        "docId": id,
        "selections": {},
        "authAttribs": [],
        "contents": "",
        "starRevNums": [],
        "revNum": 0,
        "revisions": [
            {
                "id": 300,
                "contents": "",
                "operation": [],
                "revNum": 0,
                "deleted_at": null,
                "document_id": 6
            }
        ]
    });
    return editor;
};

var server = {
    history: [],
    revNum: 0,
    send: function(type, msg) {
        if (type !== "EDIT_UPDATE")
            return;
        console.log(type, msg);

        var id = msg.docId;
        var ed = editors[id];
        ed.outgoing.push(lang.deepCopy(msg));
        
        this._signal("recieve", id);
    },
    handleEdit: function(msg) {
        this.revNum = msg.revNum;
        editors.forEach(function(ed) {
            ed.incoming.push({
                data: lang.deepCopy(msg),
                type: "EDIT_UPDATE"
            });
        });

        this._signal("send");
    },
    pickMsg: function(id) {
        var ed = editors[id];
        var msg = ed.outgoing.shift();
        if (!msg) return;
        if (msg.revNum != this.revNum + 1) {
            ed.incoming.push({
                type: "SYNC_COMMIT",
                data: {
                    revNum: this.revNum,
                    reason: "err"
                }
            });
            return this.pickMsg(id);
        }
        this.handleEdit(msg);
    },
    applyEdit: function(id) {
        var ed = editors[id];
        var msg = ed.incoming.shift();
        if (msg)
            ed.otDoc.handleDocMsg(lang.deepCopy(msg));
    },
    reset: function() {
        
    }
};
oop.implement(server, EventEmitter);

Client.onConnect({ connected: true, send: function(msg) {server.send(msg.type, msg.data); }});

var ed1 = join("ed1");
var ed2 = join("ed2");
var ed3 = join("ed3");

function clip(val, min, max) {return Math.max(min, Math.min(val, max));}

function getRandomInt(min, max) {
    var i = Math.floor(Math.random() * (max - min + 1)) + min;
    if (i >= max) i = max - 1;
    if (i <= min) i = min;
    return i;
}

var c = 0;
function randomString(len) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    c = (c+1) % possible.length;
    text = lang.stringRepeat(possible[c], len);
    return text;
}
function nextString(len) {
    var text = "";
    var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    nextString.c = ((nextString.c||0) + 1) % chars.length;
    text = lang.stringRepeat(chars[nextString.c], len);
    return text;
}

var deleteMore;
function randomOp() {
    var id = getRandomInt(0, editors.length + 3);
    var op = {id: id};
    if (!editors[id]) {
        op.id = getRandomInt(0, editors.length);
        op.type = "server";
    } else {
        var ed = editors[id];
        var doc = ed.session.doc;
        var l = doc.getValue().length;
        var random = Math.random();
        if (!l || random < 0.3) {
            l = doc.getValue().length;
            op.pos = doc.indexToPosition(getRandomInt(0, l), false, true);
            op.text = nextString(getRandomInt(0, 5)) + (getRandomInt(0, 10) ? "" : "\n");
            op.type = "insert";
        } else if (random < 0.5) {
            var p = [getRandomInt(0, l), getRandomInt(0, l)].sort(function(a,b){return a-b;});
            
            if (!deleteMore)
                p[1] = clip(p[1], p[0], p[0] + 2);
            
            op.range = Range.fromPoints(doc.indexToPosition(p[0], false, true), doc.indexToPosition(p[1], false, true));
            op.type = "remove";
        } else {
            op.type = "apply";
        }
    }
    return op;
}
function applyOp(op) {
    var id = op.id;
    if (op.type == "server") {
        server.pickMsg(op.id);
    } else {
        var ed = editors[id];
        var doc = ed.session;
        if (op.type == "insert") {
            doc.insert(op.pos, op.text);
        } else if (op.type == "remove") {
            doc.remove(op.range);
        } else if (op.type == "apply") {
            server.applyEdit(id);
        }
    }
}

window.server = server;
window.applyOp = applyOp;
window.randomOp = randomOp;
window.editors = editors;

var editRandomly = window.editRandomly = function() {
    editRandomly.editCount = document.getElementById("editCb").checked ? 300 : 0;
    var interv = setInterval(function step() {
        if (editRandomly.editCount --< 0) {
            editRandomly.editCount = document.getElementById("editCb").checked ? 300 : 0;
            if (!editRandomly.editCount) {
                return clearInterval(interv);
            }
        }
        var op = randomOp();
        
        server.history.push(op);
        applyOp(op);
    }, 10);
};
editRandomly.editCount = 300;

window.editRandomlyWithoutServer = function(editorNum) {
    var i = 300;
    var interv = setInterval(function step() {
        if (i --< 0) {
            return clearInterval(interv);
        }
        var op = randomOp();
        
        if ((op.type != "insert" && op.type != "remove"))
            return step();
        
        server.history.push(op);
        applyOp(op);
    }, 10);
};

window.enableAutoSync = function(enable, latency) {
    server.removeAllListeners("send");
    server.removeAllListeners("recieve");
    
    if (enable === false) return;
    
    function has(aName) {
        return editors.some(function(ed) {return ed[aName].length;});
    }
    var onsend = lang.delayedCall(function() {
        server.applyEdit(getRandomInt(0, editors.length));
        if (has("incoming")) server._emit("send");
        if (has("outgoing")) server._emit("recieve");
    });
    var onrecieve = lang.delayedCall(function() {
        server.pickMsg(getRandomInt(0, editors.length));
        if (has("outgoing")) server._emit("recieve");
        if (has("incoming")) server._emit("send");
    });
    latency = latency * 0.5;
    server.on("send", function() {
        onsend.schedule(latency + Math.random() * latency);
    });
    server.on("recieve", function() {
        onrecieve.schedule(latency + Math.random() * latency);
    });
    
    onsend.schedule();
    onrecieve.schedule();
};

window.setDeleteMore = function(val) {
    deleteMore = val;
};

});
Exemplo n.º 10
0
Arquivo: cells.js Projeto: Alovez/core
(function() {

    oop.implement(this, EventEmitter);
    
    this.config = {},

    this.setDataProvider = function(provider) {
        this.provider = provider;
        if (provider)
            this.update = provider.renderRow ? this.$customUpdate : this.$treeModeUpdate;
    };
    
    this.update = function (config) {
    };
    
    this.measureSizes = function() {
        var domNode = this.element.firstChild;
        if (domNode) {
            this.provider.rowHeight = domNode.offsetHeight;
            this.provider.rowHeightInner = domNode.clientHeight;
        }
    };
    
    this.$treeModeUpdate = function (config) {
        this.config = config;
        
        var provider = this.provider;
        var row, html = [], view = config.view, datarow;
        var firstRow = config.firstRow, lastRow = config.lastRow + 1;
        var hsize = "auto;", vsize = provider.rowHeightInner || provider.rowHeight;
        
        for (row = firstRow; row < lastRow; row++) {
            datarow = view[row - firstRow];
            if (provider.getItemHeight)
                vsize = provider.getItemHeight(datarow, row);
            this.$renderRow(html, datarow, vsize, hsize, row);
        }
        
        if (firstRow === 0 && lastRow === 0) {
            this.renderPlaceHolder(provider, html, config);
        }
        
        this.element = dom.setInnerHtml(this.element, html.join(""));
        
        if (!vsize) {
            this.measureSizes();
        }
    };
    
    this.columnNode = function(datarow, column) {
        return "<span class='tree-column " 
        + (column.className || "")
        + "' style='"
        + (datarow.fullWidth ? "" : "width:" + column.$width + ";")
        + "'>";
    };
    
    this.getRowClass = function(datarow, row) {
        var provider = this.provider;
        return "tree-row " 
            + (provider.isSelected(datarow) ? "selected ": '')  
            + (provider.getClassName(datarow) || "") + (row & 1 ? " odd" : " even");
    };
    
    this.$renderRow = function(html, datarow, vsize, hsize, row) {
        var provider = this.provider;
        var columns = provider.columns;
        var indent = provider.$indentSize;// provider.getIndent(datarow);
        html.push("<div style='height:" + vsize + "px;"
            + (columns ? "padding-right:" + columns.$fixedWidth : "")
            + "' class='"
            + this.getRowClass(datarow, row)
            + "'>");
        
        if (!columns || columns[0].type == "tree") {
            if (columns) {
                html.push(this.columnNode(datarow, columns[0], row));
            }
            var depth = provider.getRowIndent(datarow);
            html.push(
                (depth ? "<span style='width:" + depth * indent + "px' class='tree-indent'></span>" : "" )
                + "<span class='toggler " + (provider.hasChildren(datarow)
                    ? (provider.isOpen(datarow) ? "open" : "closed")
                    : "empty")
                + "'></span>"
                + (provider.getCheckboxHTML ? provider.getCheckboxHTML(datarow) : "")
                + provider.getIconHTML(datarow)
                + ( provider.getContentHTML ? provider.getContentHTML(datarow)
                    : "<span class='caption' style='width: " + hsize + "px;height: " + vsize + "px'>"
                    +   provider.getCaptionHTML(datarow)
                    + "</span>"
                )
            );
        }
        if (columns) {
            for (var col = columns[0].type == "tree" ? 1 : 0; col < columns.length; col++) {
                var column = columns[col];
                var rowStr = (column.getHTML) ? column.getHTML(datarow) : escapeHTML(column.getText(datarow) + "");
                html.push("</span>" + this.columnNode(datarow, column, row) + rowStr);
            }
            html.push("</span>");
        }
        
        html.push("</div>");
    };
    
    this.$customUpdate = function(config) {
        this.config = config;
        
        var provider = this.provider;
        var html = [];
        var firstRow = config.firstRow, lastRow = config.lastRow + 1;

        for (var row = firstRow; row < lastRow; row++) {
           provider.renderRow(row, html, config);
        }
        
        if (firstRow === 0 && lastRow === 0) {
            this.renderPlaceHolder(provider, html, config);
        }
        
        this.element = dom.setInnerHtml(this.element, html.join(""));
    };
    
    this.updateClasses = function(config) {
        // fallback to full redraw for customUpdate
        if (this.update == this.$customUpdate && !this.provider.updateNode)
            return this.update(config);
            
        this.config = config;
        
        var provider = this.provider;
        var row, view = config.view, datarow;
        var firstRow = config.firstRow, lastRow = config.lastRow + 1;
        var children = this.element.children;
        
        if (children.length != lastRow - firstRow)
            return this.update(config);
        
        for (row = firstRow; row < lastRow; row++) {
            datarow = view[row - firstRow];
            var el = children[row - firstRow];
            el.className = this.getRowClass(datarow, row);
            if (provider.redrawNode)
                provider.redrawNode(el, datarow);
        }
    };

    this.scroll = function(config) {
        // not implemented
        return this.update(config);
        
        this.element.insertAdjacentHTML("afterBegin", "<span>a</span><s>r</s>");
        this.element.insertAdjacentHTML("beforeEnd", "<span>a</span><s>r</s>");
    };
    
    this.updateRows = function(config, firstRow, lastRow) {
        // not implemented
    };

    this.destroy = function() {
        
    };
    
    this.getDomNodeAtIndex = function(i) {
        return this.element.children[i - this.config.firstRow];
    };
    
    this.renderPlaceHolder = function(provider, html, config) {
        if (provider.renderEmptyMessage) {
            provider.renderEmptyMessage(html, config);
        } else if (provider.getEmptyMessage) {
            html.push(
                "<div class='message empty'>",
                    provider.getEmptyMessage(),
                "</div>"
            );
        }
    };

}).call(Cells.prototype);
Exemplo n.º 11
0
"no use strict";(function(e){if(typeof e.window!="undefined"&&e.document)return;e.console={log:function(){var e=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:e})},error:function(){var e=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:e})}},e.window=e,e.ace=e,e.normalizeModule=function(e,t){if(t.indexOf("!")!==-1){var n=t.split("!");return normalizeModule(e,n[0])+"!"+normalizeModule(e,n[1])}if(t.charAt(0)=="."){var r=e.split("/").slice(0,-1).join("/");t=r+"/"+t;while(t.indexOf(".")!==-1&&i!=t){var i=t;t=t.replace(/\/\.\//,"/").replace(/[^\/]+\/\.\.\//,"")}}return t},e.require=function(e,t){t||(t=e,e=null);if(!t.charAt)throw new Error("worker.js require() accepts only (parentId, id) as arguments");t=normalizeModule(e,t);var n=require.modules[t];if(n)return n.initialized||(n.initialized=!0,n.exports=n.factory().exports),n.exports;var r=t.split("/");r[0]=require.tlns[r[0]]||r[0];var i=r.join("/")+".js";return require.id=t,importScripts(i),require(e,t)},require.modules={},require.tlns={},e.define=function(e,t,n){arguments.length==2?(n=t,typeof e!="string"&&(t=e,e=require.id)):arguments.length==1&&(n=e,e=require.id);if(e.indexOf("text!")===0)return;var r=function(t,n){return require(e,t,n)};require.modules[e]={factory:function(){var e={exports:{}},t=n(r,e.exports,e);return t&&(e.exports=t),e}}},e.initBaseUrls=function(e){require.tlns=e},e.initSender=function(){var e=require("ace/lib/event_emitter").EventEmitter,t=require("ace/lib/oop"),n=function(){};return function(){t.implement(this,e),this.callback=function(e,t){postMessage({type:"call",id:t,data:e})},this.emit=function(e,t){postMessage({type:"event",name:e,data:t})}}.call(n.prototype),new n},e.main=null,e.sender=null,e.onmessage=function(e){var t=e.data;if(t.command){if(!main[t.command])throw new Error("Unknown command:"+t.command);main[t.command].apply(main,t.args)}else if(t.init){initBaseUrls(t.tlns),require("ace/lib/es5-shim"),sender=initSender();var n=require(t.module)[t.classname];main=new n(sender)}else t.event&&sender&&sender._emit(t.event,t.data)}})(this),ace.define("ace/lib/event_emitter",["require","exports","module"],function(e,t,n){var r={},i=function(){this.propagationStopped=!0},s=function(){this.defaultPrevented=!0};r._emit=r._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var n=this._eventRegistry[e]||[],r=this._defaultHandlers[e];if(!n.length&&!r)return;if(typeof t!="object"||!t)t={};t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=i),t.preventDefault||(t.preventDefault=s);for(var o=0;o<n.length;o++){n[o](t,this);if(t.propagationStopped)break}if(r&&!t.defaultPrevented)return r(t,this)},r._signal=function(e,t){var n=(this._eventRegistry||{})[e];if(!n)return;for(var r=0;r<n.length;r++)n[r](t,this)},r.once=function(e,t){var n=this;t&&this.addEventListener(e,function r(){n.removeEventListener(e,r),t.apply(null,arguments)})},r.setDefaultHandler=function(e,t){var n=this._defaultHandlers;n||(n=this._defaultHandlers={_disabled_:{}});if(n[e]){var r=n[e],i=n._disabled_[e];i||(n._disabled_[e]=i=[]),i.push(r);var s=i.indexOf(t);s!=-1&&i.splice(s,1)}n[e]=t},r.removeDefaultHandler=function(e,t){var n=this._defaultHandlers;if(!n)return;var r=n._disabled_[e];if(n[e]==t){var i=n[e];r&&this.setDefaultHandler(e,r.pop())}else if(r){var s=r.indexOf(t);s!=-1&&r.splice(s,1)}},r.on=r.addEventListener=function(e,t,n){this._eventRegistry=this._eventRegistry||{};var r=this._eventRegistry[e];return r||(r=this._eventRegistry[e]=[]),r.indexOf(t)==-1&&r[n?"unshift":"push"](t),t},r.off=r.removeListener=r.removeEventListener=function(e,t){this._eventRegistry=this._eventRegistry||{};var n=this._eventRegistry[e];if(!n)return;var r=n.indexOf(t);r!==-1&&n.splice(r,1)},r.removeAllListeners=function(e){this._eventRegistry&&(this._eventRegistry[e]=[])},t.EventEmitter=r}),ace.define("ace/lib/oop",["require","exports","module"],function(e,t,n){t.inherits=function(){var e=function(){};return function(t,n){e.prototype=n.prototype,t.super_=n.prototype,t.prototype=new e,t.prototype.constructor=t}}(),t.mixin=function(e,t){for(var n in t)e[n]=t[n];return e},t.implement=function(e,n){t.mixin(e,n)}}),ace.define("ace/lib/es5-shim",["require","exports","module"],function(e,t,n){function r(){}function i(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(t){}}function s(e){return e=+e,e!==e?e=0:e!==0&&e!==1/0&&e!==-1/0&&(e=(e>0||-1)*Math.floor(Math.abs(e))),e}function o(e){var t=typeof e;return e===null||t==="undefined"||t==="boolean"||t==="number"||t==="string"}function u(e){var t,n,r;if(o(e))return e;n=e.valueOf;if(typeof n=="function"){t=n.call(e);if(o(t))return t}r=e.toString;if(typeof r=="function"){t=r.call(e);if(o(t))return t}throw new TypeError}Function.prototype.bind||(Function.prototype.bind=function(e){var t=this;if(typeof t!="function")throw new TypeError("Function.prototype.bind called on incompatible "+t);var n=c.call(arguments,1),i=function(){if(this instanceof i){var r=t.apply(this,n.concat(c.call(arguments)));return Object(r)===r?r:this}return t.apply(e,n.concat(c.call(arguments)))};return t.prototype&&(r.prototype=t.prototype,i.prototype=new r,r.prototype=null),i});var a=Function.prototype.call,f=Array.prototype,l=Object.prototype,c=f.slice,h=a.bind(l.toString),p=a.bind(l.hasOwnProperty),d,v,m,g,y;if(y=p(l,"__defineGetter__"))d=a.bind(l.__defineGetter__),v=a.bind(l.__defineSetter__),m=a.bind(l.__lookupGetter__),g=a.bind(l.__lookupSetter__);if([1,2].splice(0).length!=2)if(!function(){function e(e){var t=new Array(e+2);return t[0]=t[1]=0,t}var t=[],n;t.splice.apply(t,e(20)),t.splice.apply(t,e(26)),n=t.length,t.splice(5,0,"XXX"),n+1==t.length;if(n+1==t.length)return!0}())Array.prototype.splice=function(e,t){var n=this.length;e>0?e>n&&(e=n):e==void 0?e=0:e<0&&(e=Math.max(n+e,0)),e+t<n||(t=n-e);var r=this.slice(e,e+t),i=c.call(arguments,2),s=i.length;if(e===n)s&&this.push.apply(this,i);else{var o=Math.min(t,n-e),u=e+o,a=u+s-o,f=n-u,l=n-o;if(a<u)for(var h=0;h<f;++h)this[a+h]=this[u+h];else if(a>u)for(h=f;h--;)this[a+h]=this[u+h];if(s&&e===l)this.length=l,this.push.apply(this,i);else{this.length=l+s;for(h=0;h<s;++h)this[e+h]=i[h]}}return r};else{var b=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?b.apply(this,[e===void 0?0:e,t===void 0?this.length-e:t].concat(c.call(arguments,2))):[]}}Array.isArray||(Array.isArray=function(e){return h(e)=="[object Array]"});var w=Object("a"),E=w[0]!="a"||!(0 in w);Array.prototype.forEach||(Array.prototype.forEach=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=arguments[1],i=-1,s=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError;while(++i<s)i in n&&e.call(r,n[i],i,t)}),Array.prototype.map||(Array.prototype.map=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=Array(r),s=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var o=0;o<r;o++)o in n&&(i[o]=e.call(s,n[o],o,t));return i}),Array.prototype.filter||(Array.prototype.filter=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=[],s,o=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var u=0;u<r;u++)u in n&&(s=n[u],e.call(o,s,u,t)&&i.push(s));return i}),Array.prototype.every||(Array.prototype.every=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var s=0;s<r;s++)if(s in n&&!e.call(i,n[s],s,t))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var s=0;s<r;s++)if(s in n&&e.call(i,n[s],s,t))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");if(!r&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var i=0,s;if(arguments.length>=2)s=arguments[1];else do{if(i in n){s=n[i++];break}if(++i>=r)throw new TypeError("reduce of empty array with no initial value")}while(!0);for(;i<r;i++)i in n&&(s=e.call(void 0,s,n[i],i,t));return s}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");if(!r&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var i,s=r-1;if(arguments.length>=2)i=arguments[1];else do{if(s in n){i=n[s--];break}if(--s<0)throw new TypeError("reduceRight of empty array with no initial value")}while(!0);do s in this&&(i=e.call(void 0,i,n[s],s,t));while(s--);return i});if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function(e){var t=E&&h(this)=="[object String]"?this.split(""):F(this),n=t.length>>>0;if(!n)return-1;var r=0;arguments.length>1&&(r=s(arguments[1])),r=r>=0?r:Math.max(0,n+r);for(;r<n;r++)if(r in t&&t[r]===e)return r;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=function(e){var t=E&&h(this)=="[object String]"?this.split(""):F(this),n=t.length>>>0;if(!n)return-1;var r=n-1;arguments.length>1&&(r=Math.min(r,s(arguments[1]))),r=r>=0?r:n-Math.abs(r);for(;r>=0;r--)if(r in t&&e===t[r])return r;return-1};Object.getPrototypeOf||(Object.getPrototypeOf=function(e){return e.__proto__||(e.constructor?e.constructor.prototype:l)});if(!Object.getOwnPropertyDescriptor){var S="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(e,t){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(S+e);if(!p(e,t))return;var n,r,i;n={enumerable:!0,configurable:!0};if(y){var s=e.__proto__;e.__proto__=l;var r=m(e,t),i=g(e,t);e.__proto__=s;if(r||i)return r&&(n.get=r),i&&(n.set=i),n}return n.value=e[t],n}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(e){return Object.keys(e)});if(!Object.create){var x;Object.prototype.__proto__===null?x=function(){return{__proto__:null}}:x=function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(e,t){var n;if(e===null)n=x();else{if(typeof e!="object")throw new TypeError("typeof prototype["+typeof e+"] != 'object'");var r=function(){};r.prototype=e,n=new r,n.__proto__=e}return t!==void 0&&Object.defineProperties(n,t),n}}if(Object.defineProperty){var T=i({}),N=typeof document=="undefined"||i(document.createElement("div"));if(!T||!N)var C=Object.defineProperty}if(!Object.defineProperty||C){var k="Property description must be an object: ",L="Object.defineProperty called on non-object: ",A="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(e,t,n){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(L+e);if(typeof n!="object"&&typeof n!="function"||n===null)throw new TypeError(k+n);if(C)try{return C.call(Object,e,t,n)}catch(r){}if(p(n,"value"))if(y&&(m(e,t)||g(e,t))){var i=e.__proto__;e.__proto__=l,delete e[t],e[t]=n.value,e.__proto__=i}else e[t]=n.value;else{if(!y)throw new TypeError(A);p(n,"get")&&d(e,t,n.get),p(n,"set")&&v(e,t,n.set)}return e}}Object.defineProperties||(Object.defineProperties=function(e,t){for(var n in t)p(t,n)&&Object.defineProperty(e,n,t[n]);return e}),Object.seal||(Object.seal=function(e){return e}),Object.freeze||(Object.freeze=function(e){return e});try{Object.freeze(function(){})}catch(O){Object.freeze=function(e){return function(t){return typeof t=="function"?t:e(t)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(e){return e}),Object.isSealed||(Object.isSealed=function(e){return!1}),Object.isFrozen||(Object.isFrozen=function(e){return!1}),Object.isExtensible||(Object.isExtensible=function(e){if(Object(e)===e)throw new TypeError;var t="";while(p(e,t))t+="?";e[t]=!0;var n=p(e,t);return delete e[t],n});if(!Object.keys){var M=!0,_=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],D=_.length;for(var P in{toString:null})M=!1;Object.keys=function I(e){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError("Object.keys called on a non-object");var I=[];for(var t in e)p(e,t)&&I.push(t);if(M)for(var n=0,r=D;n<r;n++){var i=_[n];p(e,i)&&I.push(i)}return I}}Date.now||(Date.now=function(){return(new Date).getTime()});var H="	\n\f\r   ᠎              \u2028\u2029";if(!String.prototype.trim||H.trim()){H="["+H+"]";var B=new RegExp("^"+H+H+"*"),j=new RegExp(H+H+"*$");String.prototype.trim=function(){return String(this).replace(B,"").replace(j,"")}}var F=function(e){if(e==null)throw new TypeError("can't convert "+e+" to object");return Object(e)}}),ace.define("ace/mode/json_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/json/json_parse"],function(e,t,n){var r=e("../lib/oop"),i=e("../worker/mirror").Mirror,s=e("./json/json_parse"),o=t.JsonWorker=function(e){i.call(this,e),this.setTimeout(200)};r.inherits(o,i),function(){this.onUpdate=function(){var e=this.doc.getValue();try{var t=s(e)}catch(n){var r=this.doc.indexToPosition(n.at-1);this.sender.emit("error",{row:r.row,column:r.column,text:n.message,type:"error"});return}this.sender.emit("ok")}}.call(o.prototype)}),ace.define("ace/worker/mirror",["require","exports","module","ace/document","ace/lib/lang"],function(e,t,n){var r=e("../document").Document,i=e("../lib/lang"),s=t.Mirror=function(e){this.sender=e;var t=this.doc=new r(""),n=this.deferredUpdate=i.delayedCall(this.onUpdate.bind(this)),s=this;e.on("change",function(e){t.applyDeltas(e.data),n.schedule(s.$timeout)})};(function(){this.$timeout=500,this.setTimeout=function(e){this.$timeout=e},this.setValue=function(e){this.doc.setValue(e),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(e){this.sender.callback(this.doc.getValue(),e)},this.onUpdate=function(){}}).call(s.prototype)}),ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=e("./range").Range,o=e("./anchor").Anchor,u=function(e){this.$lines=[],e.length==0?this.$lines=[""]:Array.isArray(e)?this._insertLines(0,e):this.insert({row:0,column:0},e)};(function(){r.implement(this,i),this.setValue=function(e){var t=this.getLength();this.remove(new s(0,0,t,this.getLine(t-1).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new o(this,e,t)},"aaa".split(/a/).length==0?this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:this.$split=function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[1]:"\n"},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\r\n";case"unix":return"\n";default:return this.$autoNewLine}},this.$autoNewLine="\n",this.$newLineMode="auto",this.setNewLineMode=function(e){if(this.$newLineMode===e)return;this.$newLineMode=e},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return e=="\r\n"||e=="\r"||e=="\n"},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){if(e.start.row==e.end.row)return this.$lines[e.start.row].substring(e.start.column,e.end.column);var t=this.getLines(e.start.row,e.end.row);t[0]=(t[0]||"").substring(e.start.column);var n=t.length-1;return e.end.row-e.start.row==n&&(t[n]=t[n].substring(0,e.end.column)),t.join(this.getNewLineCharacter())},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):e.row<0&&(e.row=0),e},this.insert=function(e,t){if(!t||t.length===0)return e;e=this.$clipPosition(e),this.getLength()<=1&&this.$detectNewLine(t);var n=this.$split(t),r=n.splice(0,1)[0],i=n.length==0?null:n.splice(n.length-1,1)[0];return e=this.insertInLine(e,r),i!==null&&(e=this.insertNewLine(e),e=this._insertLines(e.row,n),e=this.insertInLine(e,i||"")),e},this.insertLines=function(e,t){return e>=this.getLength()?this.insert({row:e,column:0},"\n"+t.join("\n")):this._insertLines(Math.max(e,0),t)},this._insertLines=function(e,t){if(t.length==0)return{row:e,column:0};if(t.length>65535){var n=this._insertLines(e,t.slice(65535));t=t.slice(0,65535)}var r=[e,0];r.push.apply(r,t),this.$lines.splice.apply(this.$lines,r);var i=new s(e,0,e+t.length,0),o={action:"insertLines",range:i,lines:t};return this._emit("change",{data:o}),n||i.end},this.insertNewLine=function(e){e=this.$clipPosition(e);var t=this.$lines[e.row]||"";this.$lines[e.row]=t.substring(0,e.column),this.$lines.splice(e.row+1,0,t.substring(e.column,t.length));var n={row:e.row+1,column:0},r={action:"insertText",range:s.fromPoints(e,n),text:this.getNewLineCharacter()};return this._emit("change",{data:r}),n},this.insertInLine=function(e,t){if(t.length==0)return e;var n=this.$lines[e.row]||"";this.$lines[e.row]=n.substring(0,e.column)+t+n.substring(e.column);var r={row:e.row,column:e.column+t.length},i={action:"insertText",range:s.fromPoints(e,r),text:t};return this._emit("change",{data:i}),r},this.remove=function(e){e.start=this.$clipPosition(e.start),e.end=this.$clipPosition(e.end);if(e.isEmpty())return e.start;var t=e.start.row,n=e.end.row;if(e.isMultiLine()){var r=e.start.column==0?t:t+1,i=n-1;e.end.column>0&&this.removeInLine(n,0,e.end.column),i>=r&&this._removeLines(r,i),r!=t&&(this.removeInLine(t,e.start.column,this.getLine(t).length),this.removeNewLine(e.start.row))}else this.removeInLine(t,e.start.column,e.end.column);return e.start},this.removeInLine=function(e,t,n){if(t==n)return;var r=new s(e,t,e,n),i=this.getLine(e),o=i.substring(t,n),u=i.substring(0,t)+i.substring(n,i.length);this.$lines.splice(e,1,u);var a={action:"removeText",range:r,text:o};return this._emit("change",{data:a}),r.start},this.removeLines=function(e,t){return e<0||t>=this.getLength()?this.remove(new s(e,0,t+1,0)):this._removeLines(e,t)},this._removeLines=function(e,t){var n=new s(e,0,t+1,0),r=this.$lines.splice(e,t-e+1),i={action:"removeLines",range:n,nl:this.getNewLineCharacter(),lines:r};return this._emit("change",{data:i}),r},this.removeNewLine=function(e){var t=this.getLine(e),n=this.getLine(e+1),r=new s(e,t.length,e+1,0),i=t+n;this.$lines.splice(e,2,i);var o={action:"removeText",range:r,text:this.getNewLineCharacter()};this._emit("change",{data:o})},this.replace=function(e,t){if(t.length==0&&e.isEmpty())return e.start;if(t==this.getTextRange(e))return e.end;this.remove(e);if(t)var n=this.insert(e.start,t);else n=e.start;return n},this.applyDeltas=function(e){for(var t=0;t<e.length;t++){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this.insertLines(r.start.row,n.lines):n.action=="insertText"?this.insert(r.start,n.text):n.action=="removeLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="removeText"&&this.remove(r)}},this.revertDeltas=function(e){for(var t=e.length-1;t>=0;t--){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="insertText"?this.remove(r):n.action=="removeLines"?this._insertLines(r.start.row,n.lines):n.action=="removeText"&&this.insert(r.start,n.text)}},this.indexToPosition=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length;for(var i=t||0,s=n.length;i<s;i++){e-=n[i].length+r;if(e<0)return{row:i,column:e+n[i].length+r}}return{row:s-1,column:n[s-1].length}},this.positionToIndex=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length,i=0,s=Math.min(e.row,n.length);for(var o=t||0;o<s;++o)i+=n[o].length;return i+r*o+e.column}}).call(u.prototype),t.Document=u}),ace.define("ace/range",["require","exports","module"],function(e,t,n){var r=function(e,t){return e.row-t.row||e.column-t.column},i=function(e,t,n,r){this.start={row:e,column:t},this.end={row:n,column:r}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return this.compare(e,t)==0},this.compareRange=function(e){var t,n=e.end,r=e.start;return t=this.compare(n.row,n.column),t==1?(t=this.compare(r.row,r.column),t==1?2:t==0?1:0):t==-1?-2:(t=this.compare(r.row,r.column),t==-1?-1:t==1?42:0)},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return this.comparePoint(e.start)==0&&this.comparePoint(e.end)==0},this.intersects=function(e){var t=this.compareRange(e);return t==-1||t==0||t==1},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){typeof e=="object"?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){typeof e=="object"?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)||this.isStart(e,t)?!1:!0:!1},this.insideStart=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)?!1:!0:!1},this.insideEnd=function(e,t){return this.compare(e,t)==0?this.isStart(e,t)?!1:!0:!1},this.compare=function(e,t){return!this.isMultiLine()&&e===this.start.row?t<this.start.column?-1:t>this.end.column?1:0:e<this.start.row?-1:e>this.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?t<=this.end.column?0:1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var n={row:t+1,column:0};else if(this.end.row<e)var n={row:e,column:0};if(this.start.row>t)var r={row:t+1,column:0};else if(this.start.row<e)var r={row:e,column:0};return i.fromPoints(r||this.start,n||this.end)},this.extend=function(e,t){var n=this.compare(e,t);if(n==0)return this;if(n==-1)var r={row:e,column:t};else var s={row:e,column:t};return i.fromPoints(r||this.start,s||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return i.fromPoints(this.start,this.end)},this.collapseRows=function(){return this.end.column==0?new i(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new i(this.start.row,0,this.end.row,0)},this.toScreenRange=function(e){var t=e.documentToScreenPosition(this.start),n=e.documentToScreenPosition(this.end);return new i(t.row,t.column,n.row,n.column)},this.moveBy=function(e,t){this.start.row+=e,this.start.column+=t,this.end.row+=e,this.end.column+=t}}).call(i.prototype),i.fromPoints=function(e,t){return new i(e.row,e.column,t.row,t.column)},i.comparePoints=r,i.comparePoints=function(e,t){return e.row-t.row||e.column-t.column},t.Range=i}),ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=t.Anchor=function(e,t,n){this.document=e,typeof n=="undefined"?this.setPosition(t.row,t.column):this.setPosition(t,n),this.$onChange=this.onChange.bind(this),e.on("change",this.$onChange)};(function(){r.implement(this,i),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.onChange=function(e){var t=e.data,n=t.range;if(n.start.row==n.end.row&&n.start.row!=this.row)return;if(n.start.row>this.row)return;if(n.start.row==this.row&&n.start.column>this.column)return;var r=this.row,i=this.column,s=n.start,o=n.end;t.action==="insertText"?s.row===r&&s.column<=i?s.row===o.row?i+=o.column-s.column:(i-=s.column,r+=o.row-s.row):s.row!==o.row&&s.row<r&&(r+=o.row-s.row):t.action==="insertLines"?s.row<=r&&(r+=o.row-s.row):t.action==="removeText"?s.row===r&&s.column<i?o.column>=i?i=s.column:i=Math.max(0,i-(o.column-s.column)):s.row!==o.row&&s.row<r?(o.row===r&&(i=Math.max(0,i-o.column)+s.column),r-=o.row-s.row):o.row===r&&(r-=o.row-s.row,i=Math.max(0,i-o.column)+s.column):t.action=="removeLines"&&s.row<=r&&(o.row<=r?r-=o.row-s.row:(r=s.row,i=0)),this.setPosition(r,i,!0)},this.setPosition=function(e,t,n){var r;n?r={row:e,column:t}:r=this.$clipPositionToDocument(e,t);if(this.row==r.row&&this.column==r.column)return;var i={row:this.row,column:this.column};this.row=r.row,this.column=r.column,this._emit("change",{old:i,value:r})},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var n={};return e>=this.document.getLength()?(n.row=Math.max(0,this.document.getLength()-1),n.column=this.document.getLine(n.row).length):e<0?(n.row=0,n.column=0):(n.row=e,n.column=Math.min(this.document.getLine(n.row).length,Math.max(0,t))),t<0&&(n.column=0),n}}).call(s.prototype)}),ace.define("ace/lib/lang",["require","exports","module"],function(e,t,n){t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){var n="";while(t>0){t&1&&(n+=e);if(t>>=1)e+=e}return n};var r=/^\s\s*/,i=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(r,"")},t.stringTrimRight=function(e){return e.replace(i,"")},t.copyObject=function(e){var t={};for(var n in e)t[n]=e[n];return t},t.copyArray=function(e){var t=[];for(var n=0,r=e.length;n<r;n++)e[n]&&typeof e[n]=="object"?t[n]=this.copyObject(e[n]):t[n]=e[n];return t},t.deepCopy=function(e){if(typeof e!="object")return e;var t=e.constructor();for(var n in e)typeof e[n]=="object"?t[n]=this.deepCopy(e[n]):t[n]=e[n];return t},t.arrayToMap=function(e){var t={};for(var n=0;n<e.length;n++)t[e[n]]=1;return t},t.createMap=function(e){var t=Object.create(null);for(var n in e)t[n]=e[n];return t},t.arrayRemove=function(e,t){for(var n=0;n<=e.length;n++)t===e[n]&&e.splice(n,1)},t.escapeRegExp=function(e){return e.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},t.escapeHTML=function(e){return e.replace(/&/g,"&#38;").replace(/"/g,"&#34;").replace(/'/g,"&#39;").replace(/</g,"&#60;")},t.getMatchOffsets=function(e,t){var n=[];return e.replace(t,function(e){n.push({offset:arguments[arguments.length-2],length:e.length})}),n},t.deferredCall=function(e){var t=null,n=function(){t=null,e()},r=function(e){return r.cancel(),t=setTimeout(n,e||0),r};return r.schedule=r,r.call=function(){return this.cancel(),e(),r},r.cancel=function(){return clearTimeout(t),t=null,r},r},t.delayedCall=function(e,t){var n=null,r=function(){n=null,e()},i=function(e){n&&clearTimeout(n),n=setTimeout(r,e||t)};return i.delay=i,i.schedule=function(e){n==null&&(n=setTimeout(r,e||0))},i.call=function(){this.cancel(),e()},i.cancel=function(){n&&clearTimeout(n),n=null},i.isPending=function(){return n},i}}),ace.define("ace/mode/json/json_parse",["require","exports","module"],function(e,t,n){var r,i,s={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"	"},o,u=function(e){throw{name:"SyntaxError",message:e,at:r,text:o}},a=function(e){return e&&e!==i&&u("Expected '"+e+"' instead of '"+i+"'"),i=o.charAt(r),r+=1,i},f=function(){var e,t="";i==="-"&&(t="-",a("-"));while(i>="0"&&i<="9")t+=i,a();if(i==="."){t+=".";while(a()&&i>="0"&&i<="9")t+=i}if(i==="e"||i==="E"){t+=i,a();if(i==="-"||i==="+")t+=i,a();while(i>="0"&&i<="9")t+=i,a()}e=+t;if(!isNaN(e))return e;u("Bad number")},l=function(){var e,t,n="",r;if(i==='"')while(a()){if(i==='"')return a(),n;if(i==="\\"){a();if(i==="u"){r=0;for(t=0;t<4;t+=1){e=parseInt(a(),16);if(!isFinite(e))break;r=r*16+e}n+=String.fromCharCode(r)}else{if(typeof s[i]!="string")break;n+=s[i]}}else n+=i}u("Bad string")},c=function(){while(i&&i<=" ")a()},h=function(){switch(i){case"t":return a("t"),a("r"),a("u"),a("e"),!0;case"f":return a("f"),a("a"),a("l"),a("s"),a("e"),!1;case"n":return a("n"),a("u"),a("l"),a("l"),null}u("Unexpected '"+i+"'")},p,d=function(){var e=[];if(i==="["){a("["),c();if(i==="]")return a("]"),e;while(i){e.push(p()),c();if(i==="]")return a("]"),e;a(","),c()}}u("Bad array")},v=function(){var e,t={};if(i==="{"){a("{"),c();if(i==="}")return a("}"),t;while(i){e=l(),c(),a(":"),Object.hasOwnProperty.call(t,e)&&u('Duplicate key "'+e+'"'),t[e]=p(),c();if(i==="}")return a("}"),t;a(","),c()}}u("Bad object")};return p=function(){c();switch(i){case"{":return v();case"[":return d();case'"':return l();case"-":return f();default:return i>="0"&&i<="9"?f():h()}},function(e,t){var n;return o=e,r=0,i=" ",n=p(),c(),i&&u("Syntax error"),typeof t=="function"?function s(e,n){var r,i,o=e[n];if(o&&typeof o=="object")for(r in o)Object.hasOwnProperty.call(o,r)&&(i=s(o,r),i!==undefined?o[r]=i:delete o[r]);return t.call(e,n,o)}({"":n},""):n}})
Exemplo n.º 12
0
(function() {

    oop.implement(this, EventEmitter);

    this.setSession = function(session) {
        if (this.session)
            this.session.removeEventListener("change", this.$updateAnnotations);
        this.session = session;
        if (session)
            session.on("change", this.$updateAnnotations);
    };

    this.addGutterDecoration = function(row, className){
        if (window.console)
            console.warn && console.warn("deprecated use session.addGutterDecoration");
        this.session.addGutterDecoration(row, className);
    };

    this.removeGutterDecoration = function(row, className){
        if (window.console)
            console.warn && console.warn("deprecated use session.removeGutterDecoration");
        this.session.removeGutterDecoration(row, className);
    };

    this.setAnnotations = function(annotations) {
        this.$annotations = [];
        for (var i = 0; i < annotations.length; i++) {
            var annotation = annotations[i];
            var row = annotation.row;
            var rowInfo = this.$annotations[row];
            if (!rowInfo)
                rowInfo = this.$annotations[row] = {text: []};
           
            var annoText = annotation.text;
            annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || "";

            if (rowInfo.text.indexOf(annoText) === -1)
                rowInfo.text.push(annoText);

            var type = annotation.type;
            if (type == "error")
                rowInfo.className = " ace_error";
            else if (type == "warning" && rowInfo.className != " ace_error")
                rowInfo.className = " ace_warning";
            else if (type == "info" && (!rowInfo.className))
                rowInfo.className = " ace_info";
        }
    };

    this.$updateAnnotations = function (delta) {
        if (!this.$annotations.length)
            return;
        var firstRow = delta.start.row;
        var len = delta.end.row - firstRow;
        if (len === 0) {
        } else if (delta.action == 'remove') {
            this.$annotations.splice(firstRow, len + 1, null);
        } else {
            var args = new Array(len + 1);
            args.unshift(firstRow, 1);
            this.$annotations.splice.apply(this.$annotations, args);
        }
    };

    this.update = function(config) {
        var session = this.session;
        var firstRow = config.firstRow;
        var lastRow = Math.min(config.lastRow + config.gutterOffset,  // needed to compensate for hor scollbar
            session.getLength() - 1);
        var fold = session.getNextFoldLine(firstRow);
        var foldStart = fold ? fold.start.row : Infinity;
        var foldWidgets = this.$showFoldWidgets && session.foldWidgets;
        var breakpoints = session.$breakpoints;
        var decorations = session.$decorations;
        var firstLineNumber = session.$firstLineNumber;
        var lastLineNumber = 0;
        
        var gutterRenderer = session.gutterRenderer || this.$renderer;

        var cell = null;
        var index = -1;
        var row = firstRow;
        while (true) {
            if (row > foldStart) {
                row = fold.end.row + 1;
                fold = session.getNextFoldLine(row, fold);
                foldStart = fold ? fold.start.row : Infinity;
            }
            if (row > lastRow) {
                while (this.$cells.length > index + 1) {
                    cell = this.$cells.pop();
                    this.element.removeChild(cell.element);
                }
                break;
            }

            cell = this.$cells[++index];
            if (!cell) {
                cell = {element: null, textNode: null, foldWidget: null};
                cell.element = dom.createElement("div");
                cell.textNode = document.createTextNode('');
                cell.element.appendChild(cell.textNode);
                this.element.appendChild(cell.element);
                this.$cells[index] = cell;
            }

            var className = "ace_gutter-cell ";
            if (breakpoints[row])
                className += breakpoints[row];
            if (decorations[row])
                className += decorations[row];
            if (this.$annotations[row])
                className += this.$annotations[row].className;
            if (cell.element.className != className)
                cell.element.className = className;

            var height = session.getRowLength(row) * config.lineHeight + "px";
            if (height != cell.element.style.height)
                cell.element.style.height = height;

            if (foldWidgets) {
                var c = foldWidgets[row];
                if (c == null)
                    c = foldWidgets[row] = session.getFoldWidget(row);
            }

            if (c) {
                if (!cell.foldWidget) {
                    cell.foldWidget = dom.createElement("span");
                    cell.element.appendChild(cell.foldWidget);
                }
                var className = "ace_fold-widget ace_" + c;
                if (c == "start" && row == foldStart && row < fold.end.row)
                    className += " ace_closed";
                else
                    className += " ace_open";
                if (cell.foldWidget.className != className)
                    cell.foldWidget.className = className;

                var height = config.lineHeight + "px";
                if (cell.foldWidget.style.height != height)
                    cell.foldWidget.style.height = height;
            } else {
                if (cell.foldWidget) {
                    cell.element.removeChild(cell.foldWidget);
                    cell.foldWidget = null;
                }
            }
            
            var text = lastLineNumber = gutterRenderer
                ? gutterRenderer.getText(session, row)
                : row + firstLineNumber;
            if (text != cell.textNode.data)
                cell.textNode.data = text;

            row++;
        }

        this.element.style.height = config.minHeight + "px";

        if (this.$fixedWidth || session.$useWrapMode)
            lastLineNumber = session.getLength() + firstLineNumber;

        var gutterWidth = gutterRenderer 
            ? gutterRenderer.getWidth(session, lastLineNumber, config)
            : lastLineNumber.toString().length * config.characterWidth;
        
        var padding = this.$padding || this.$computePadding();
        gutterWidth += padding.left + padding.right;
        if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) {
            this.gutterWidth = gutterWidth;
            this.element.style.width = Math.ceil(this.gutterWidth) + "px";
            this._emit("changeGutterWidth", gutterWidth);
        }
    };

    this.$fixedWidth = false;
    
    this.$showLineNumbers = true;
    this.$renderer = "";
    this.setShowLineNumbers = function(show) {
        this.$renderer = !show && {
            getWidth: function() {return ""},
            getText: function() {return ""}
        };
    };
    
    this.getShowLineNumbers = function() {
        return this.$showLineNumbers;
    };
    
    this.$showFoldWidgets = true;
    this.setShowFoldWidgets = function(show) {
        if (show)
            dom.addCssClass(this.element, "ace_folding-enabled");
        else
            dom.removeCssClass(this.element, "ace_folding-enabled");

        this.$showFoldWidgets = show;
        this.$padding = null;
    };
    
    this.getShowFoldWidgets = function() {
        return this.$showFoldWidgets;
    };

    this.$computePadding = function() {
        if (!this.element.firstChild)
            return {left: 0, right: 0};
        var style = dom.computedStyle(this.element.firstChild);
        this.$padding = {};
        this.$padding.left = parseInt(style.paddingLeft) + 1 || 0;
        this.$padding.right = parseInt(style.paddingRight) || 0;
        return this.$padding;
    };

    this.getRegion = function(point) {
        var padding = this.$padding || this.$computePadding();
        var rect = this.element.getBoundingClientRect();
        if (point.x < padding.left + rect.left)
            return "markers";
        if (this.$showFoldWidgets && point.x > rect.right - padding.right)
            return "foldWidgets";
    };

}).call(Gutter.prototype);
Exemplo n.º 13
0
  (function() {

    oop.implement(this, EventEmitter);

    /**
     * Replaces the text of the comment with the specified parameter.
     * This function also emits the `'changeText'` event.
     *
     * @param {String} text The text of the comment to use
     *
     * @memberof Comment
     * @instance
     * @method setText
     */
    this.setText = function(text) {
      this.text = text;
      this._signal('changeText', this.text);
    };

    /**
     * Returns the text of the comment.
     *
     * @returns {String} The text of the comment
     *
     * @memberof Comment
     * @instance
     * @method getText
     */
    this.getText = function() {
      return this.text;
    };

    /**
     * Selects the comment. This function also emits the
     * `'changeSelected'` event.
     *
     * @memberof Comment
     * @instance
     * @method select
     */
    this.select = function() {
      this.selected = true;
      this._signal('changeSelected', this.selected);
    };

    /**
     * Deselects the comment. This function also emits the
     * `'changeSelected'` event.
     *
     * @memberof Comment
     * @instance
     * @method deselect
     */
    this.deselect = function() {
      this.selected = false;
      this._signal('changeSelected', this.selected);
    };

    /**
     * Returns whether the comment is selected or not.
     *
     * @returns {boolean} `true` if the comment is selected, and `false`
     *    otherwise
     *
     * @memberof Comment
     * @instance
     * @method isSelected
     */
    this.isSelected = function() {
      return this.selected;
    };

    /**
     * Returns the index of the comment within a list. Note that a
     * comment may only be in one list at a time.
     *
     * @returns {Number|null} The index of the comment within a list,
     *    or `null` if not in any list
     *
     * @memberof Comment
     * @instance
     * @method getIndex
     */
    this.getIndex = function() {
      return this.index;
    };

  }).call(Comment.prototype);
Exemplo n.º 14
0
			(function() {
				oop.implement(this, EventEmitter);

				this.init = function() {
					this.wrap = document.createElement('div');
					this.listWrap = document.createElement('div');
					this.listElement = document.createElement('ul');
					this.listElement.style.listStyleType = 'none';
					this.listWrap.appendChild(this.listElement);
					this.listWrap.style.overflow = "hidden";
					$(this.wrap)
						.css("overflow", "hidden")
						.css("width", "402px")
						.addClass("ace_autocomplete")
						.addClass("ace_autocomplete_wrap")
						.append($("<div/>").addClass("hint"))
						.append(this.listWrap)
					;

					this.wrap2 = document.createElement('div');
					$(this.wrap2)
						.append($("<div/>").addClass("hint"))
						.append($("<div/>").addClass("comment"))
						.addClass("ace_autocomplete_wrap")
						.css("width", $(window).width() - 700+"px")
						.css("padding", "px")
						.css("overflow-x", "hidden")
						.css("overflow-y", "scroll")
					;

					var wrapper = $(this.wrap).add(this.wrap2);
					wrapper.find(".hint")
						.css("padding", "2px")
						.css("display", "none")
						.css("border-bottom", "1px solid #ccc")
						.css("margin-bottom", "2px")
						.css("background-color", "white")
					;
				}

				this.show = function() {
					this.wrap.style.display = 'block';
					this.wrap2.style.display = "block";
				}

				this.hide = function() {
					this.wrap.style.display = 'none';
					this.wrap2.style.display = "none";
				}

				this.setPosition = function(coords) {
					var top = coords.pageY + 20;
					var editorBottom = $(this.editor.container).offset().top + $(this.editor.container).height();
					var bottom = top + $(this.wrap).height();
					if (bottom < editorBottom) {
						this.wrap.style.top = top + 'px';
						this.wrap.style.left = coords.pageX + 'px';
					} else {
						this.wrap.style.top = (top - $(this.wrap).height() - 20) + 'px';
						this.wrap.style.left = coords.pageX + 'px';
					}
					var left = parseInt(this.wrap.style.left)+400;
					$(this.wrap2)
						.css("left", left)
						.css("top", this.wrap.style.top)
						.css("width", Math.max($(window).width()-left-50, 100));
				}

				this.current = function() {
					var children = this.listElement.childNodes;
					for (var i in children) {
						var child = children[i];
						if (child.className === selectedClassName) return child;
					}
					return null;
				}

				this.focusNext = function() {
					var curr = this.current();
					var focus = curr.nextSibling;
					if (focus) {
						curr.className = '';
						focus.className = selectedClassName;
						return this.adjustPosition();
					}
				};

				this.focusPrev = function() {
					var curr = this.current();
					var focus = curr.previousSibling;
					if (focus) {
						curr.className = '';
						focus.className = selectedClassName;
						return this.adjustPosition();
					}
				}

				this.ensureFocus = function() {
					if (!this.current()) {
						if (this.listElement.firstChild) {
							this.listElement.firstChild.className = selectedClassName;
							return this.adjustPosition();
						}
					}
				}

				this.adjustPosition = function() {
					var elm = this.current();
					this._signal("changed", elm);
					if (elm) {
						var newMargin = '';
						var wrapHeight = $(this.wrap).height();
						var elmOuterHeight = $(elm).outerHeight();
						var preMargin = parseInt($(this.listElement).css("margin-top"));
						var pos = $(elm).position();

						var hint = $(this.wrap).find(".hint");
						if (hint.css("display") == "block") {
							var hintHeight = hint.height() + 6;
							wrapHeight -= hintHeight;
							pos.top -= hintHeight;
						}

						if (pos.top >= (wrapHeight - elmOuterHeight)) {
							newMargin = (preMargin - elmOuterHeight);
							$(this.listElement).css("margin-top", newMargin);
						}
						if (pos.top < 0) {
							newMargin = (-pos.top + preMargin);
							$(this.listElement).css("margin-top", newMargin);
						}
					}
				}

				this.showComment = function(docComment) {
					var self = this;
					var comment = $(self.wrap2).find(".comment");
					comment.html("");
					if (! docComment || docComment.length == 0) {
						return;
					}
					var lines = docComment.split(/\n/g);
					lines.forEach(function(line) {
						comment.append($("<div/>").text(line));
					});
				}

				this.hideParameterHint = function() {
					$(this.wrap).add(this.wrap2).find(".hint").css("display", "none");
				}

				this.showParameterHint = function(formal) {
					$(this.wrap).find(".hint")
						.html("")
						.append(
							$("<div/>").text(formal.signatureInfo)
						)
						.append(
							$("<div/>").text(formal.docComment)
						)
						.css("display", "block")
					;
					var paramsDoc = $("<div/>");
					for (var i=0; i<formal.parameters.length; i++) {
						var p = formal.parameters[i];
						paramsDoc.append(
							$("<div/>").append(
								$("<span/>").css("font-weight", "bold").text(p.name)
							)
							.append(
								$("<span/>").text(": "+p.docComment)
							)
						);
					}
					if (formal.parameters.length > 0) {
						var hintComment = $(this.wrap2).find(".hint");
						hintComment
							.html("")
							.css("display", "block")
						;
						hintComment.append(paramsDoc);
					}
				}
			}).call(AutoCompleteView.prototype);
Exemplo n.º 15
0
(function() {

    oop.implement(this, EventEmitter);
    this.getPosition = function() {
        return this.$clipPositionToDocument(this.row, this.column);
    };
    this.getDocument = function() {
        return this.document;
    };
    this.$insertRight = false;
    this.onChange = function(delta) {
        if (delta.start.row == delta.end.row && delta.start.row != this.row)
            return;

        if (delta.start.row > this.row)
            return;
            
        var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight);
        this.setPosition(point.row, point.column, true);
    };
    
    function $pointsInOrder(point1, point2, equalPointsInOrder) {
        var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
        return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
    }
            
    function $getTransformedPoint(delta, point, moveIfEqual) {
        var deltaIsInsert = delta.action == "insert";
        var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row    - delta.start.row);
        var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
        var deltaStart = delta.start;
        var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
        if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
            return {
                row: point.row,
                column: point.column
            };
        }
        if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
            return {
                row: point.row + deltaRowShift,
                column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
            };
        }
        
        return {
            row: deltaStart.row,
            column: deltaStart.column
        };
    }
    this.setPosition = function(row, column, noClip) {
        var pos;
        if (noClip) {
            pos = {
                row: row,
                column: column
            };
        } else {
            pos = this.$clipPositionToDocument(row, column);
        }

        if (this.row == pos.row && this.column == pos.column)
            return;

        var old = {
            row: this.row,
            column: this.column
        };

        this.row = pos.row;
        this.column = pos.column;
        this._signal("change", {
            old: old,
            value: pos
        });
    };
    this.detach = function() {
        this.document.removeEventListener("change", this.$onChange);
    };
    this.attach = function(doc) {
        this.document = doc || this.document;
        this.document.on("change", this.$onChange);
    };
    this.$clipPositionToDocument = function(row, column) {
        var pos = {};

        if (row >= this.document.getLength()) {
            pos.row = Math.max(0, this.document.getLength() - 1);
            pos.column = this.document.getLine(pos.row).length;
        }
        else if (row < 0) {
            pos.row = 0;
            pos.column = 0;
        }
        else {
            pos.row = row;
            pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
        }

        if (column < 0)
            pos.column = 0;

        return pos;
    };

}).call(Anchor.prototype);
Exemplo n.º 16
0
(function() {

    oop.implement(this, EventEmitter);
    this.setup = function() {
        var _self = this;
        var doc = this.doc;
        var session = this.session;
        var pos = this.$pos;
        
        this.selectionBefore = session.selection.toJSON();
        if (session.selection.inMultiSelectMode)
            session.selection.toSingleRange();

        this.pos = doc.createAnchor(pos.row, pos.column);
        this.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false);
        this.pos.on("change", function(event) {
            session.removeMarker(_self.markerId);
            _self.markerId = session.addMarker(new Range(event.value.row, event.value.column, event.value.row, event.value.column+_self.length), _self.mainClass, null, false);
        });
        this.others = [];
        this.$others.forEach(function(other) {
            var anchor = doc.createAnchor(other.row, other.column);
            _self.others.push(anchor);
        });
        session.setUndoSelect(false);
    };
    this.showOtherMarkers = function() {
        if(this.othersActive) return;
        var session = this.session;
        var _self = this;
        this.othersActive = true;
        this.others.forEach(function(anchor) {
            anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false);
            anchor.on("change", function(event) {
                session.removeMarker(anchor.markerId);
                anchor.markerId = session.addMarker(new Range(event.value.row, event.value.column, event.value.row, event.value.column+_self.length), _self.othersClass, null, false);
            });
        });
    };
    this.hideOtherMarkers = function() {
        if(!this.othersActive) return;
        this.othersActive = false;
        for (var i = 0; i < this.others.length; i++) {
            this.session.removeMarker(this.others[i].markerId);
        }
    };
    this.onUpdate = function(delta) {
        var range = delta;
        if(range.start.row !== range.end.row) return;
        if(range.start.row !== this.pos.row) return;
        if (this.$updating) return;
        this.$updating = true;
        var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column;
        
        if(range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1) {
            var distanceFromStart = range.start.column - this.pos.column;
            this.length += lengthDiff;
            if(!this.session.$fromUndo) {
                if(delta.action === 'insert') {
                    for (var i = this.others.length - 1; i >= 0; i--) {
                        var otherPos = this.others[i];
                        var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
                        if(otherPos.row === range.start.row && range.start.column < otherPos.column)
                            newPos.column += lengthDiff;
                        this.doc.insertMergedLines(newPos, delta.lines);
                    }
                } else if(delta.action === 'remove') {
                    for (var i = this.others.length - 1; i >= 0; i--) {
                        var otherPos = this.others[i];
                        var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
                        if(otherPos.row === range.start.row && range.start.column < otherPos.column)
                            newPos.column += lengthDiff;
                        this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff));
                    }
                }
                if(range.start.column === this.pos.column && delta.action === 'insert') {
                    setTimeout(function() {
                        this.pos.setPosition(this.pos.row, this.pos.column - lengthDiff);
                        for (var i = 0; i < this.others.length; i++) {
                            var other = this.others[i];
                            var newPos = {row: other.row, column: other.column - lengthDiff};
                            if(other.row === range.start.row && range.start.column < other.column)
                                newPos.column += lengthDiff;
                            other.setPosition(newPos.row, newPos.column);
                        }
                    }.bind(this), 0);
                }
                else if(range.start.column === this.pos.column && delta.action === 'remove') {
                    setTimeout(function() {
                        for (var i = 0; i < this.others.length; i++) {
                            var other = this.others[i];
                            if(other.row === range.start.row && range.start.column < other.column) {
                                other.setPosition(other.row, other.column - lengthDiff);
                            }
                        }
                    }.bind(this), 0);
                }
            }
            this.pos._emit("change", {value: this.pos});
            for (var i = 0; i < this.others.length; i++) {
                this.others[i]._emit("change", {value: this.others[i]});
            }
        }
        this.$updating = false;
    };

    this.onCursorChange = function(event) {
        if (this.$updating || !this.session) return;
        var pos = this.session.selection.getCursor();
        if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) {
            this.showOtherMarkers();
            this._emit("cursorEnter", event);
        } else {
            this.hideOtherMarkers();
            this._emit("cursorLeave", event);
        }
    };    
    this.detach = function() {
        this.session.removeMarker(this.markerId);
        this.hideOtherMarkers();
        this.doc.removeEventListener("change", this.$onUpdate);
        this.session.selection.removeEventListener("changeCursor", this.$onCursorChange);
        this.pos.detach();
        for (var i = 0; i < this.others.length; i++) {
            this.others[i].detach();
        }
        this.session.setUndoSelect(true);
        this.session = null;
    };
    this.cancel = function() {
        if(this.$undoStackDepth === -1)
            throw Error("Canceling placeholders only supported with undo manager attached to session.");
        var undoManager = this.session.getUndoManager();
        var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth;
        for (var i = 0; i < undosRequired; i++) {
            undoManager.undo(true);
        }
        if (this.selectionBefore)
            this.session.selection.fromJSON(this.selectionBefore);
    };
}).call(PlaceHolder.prototype);
Exemplo n.º 17
0
"no use strict";(function(e){if(typeof e.window!="undefined"&&e.document)return;e.console=function(){var e=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:e})},e.console.error=e.console.warn=e.console.log=e.console.trace=e.console,e.window=e,e.ace=e,e.normalizeModule=function(e,t){if(t.indexOf("!")!==-1){var n=t.split("!");return normalizeModule(e,n[0])+"!"+normalizeModule(e,n[1])}if(t.charAt(0)=="."){var r=e.split("/").slice(0,-1).join("/");t=r+"/"+t;while(t.indexOf(".")!==-1&&i!=t){var i=t;t=t.replace(/\/\.\//,"/").replace(/[^\/]+\/\.\.\//,"")}}return t},e.require=function(e,t){t||(t=e,e=null);if(!t.charAt)throw new Error("worker.js require() accepts only (parentId, id) as arguments");t=normalizeModule(e,t);var n=require.modules[t];if(n)return n.initialized||(n.initialized=!0,n.exports=n.factory().exports),n.exports;var r=t.split("/");if(!require.tlns)return console.log("unable to load "+t);r[0]=require.tlns[r[0]]||r[0];var i=r.join("/")+".js";return require.id=t,importScripts(i),require(e,t)},require.modules={},require.tlns={},e.define=function(e,t,n){arguments.length==2?(n=t,typeof e!="string"&&(t=e,e=require.id)):arguments.length==1&&(n=e,e=require.id);if(e.indexOf("text!")===0)return;var r=function(t,n){return require(e,t,n)};require.modules[e]={exports:{},factory:function(){var e=this,t=n(r,e.exports,e);return t&&(e.exports=t),e}}},e.initBaseUrls=function(e){require.tlns=e},e.initSender=function(){var e=require("ace/lib/event_emitter").EventEmitter,t=require("ace/lib/oop"),n=function(){};return function(){t.implement(this,e),this.callback=function(e,t){postMessage({type:"call",id:t,data:e})},this.emit=function(e,t){postMessage({type:"event",name:e,data:t})}}.call(n.prototype),new n},e.main=null,e.sender=null,e.onmessage=function(e){var t=e.data;if(t.command){if(!main[t.command])throw new Error("Unknown command:"+t.command);main[t.command].apply(main,t.args)}else if(t.init){initBaseUrls(t.tlns),require("ace/lib/es5-shim"),sender=initSender();var n=require(t.module)[t.classname];main=new n(sender)}else t.event&&sender&&sender._emit(t.event,t.data)}})(this),define("ace/lib/event_emitter",["require","exports","module"],function(e,t,n){var r={},i=function(){this.propagationStopped=!0},s=function(){this.defaultPrevented=!0};r._emit=r._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var n=this._eventRegistry[e]||[],r=this._defaultHandlers[e];if(!n.length&&!r)return;if(typeof t!="object"||!t)t={};t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=i),t.preventDefault||(t.preventDefault=s),n=n.slice();for(var o=0;o<n.length;o++){n[o](t,this);if(t.propagationStopped)break}if(r&&!t.defaultPrevented)return r(t,this)},r._signal=function(e,t){var n=(this._eventRegistry||{})[e];if(!n)return;n=n.slice();for(var r=0;r<n.length;r++)n[r](t,this)},r.once=function(e,t){var n=this;t&&this.addEventListener(e,function r(){n.removeEventListener(e,r),t.apply(null,arguments)})},r.setDefaultHandler=function(e,t){var n=this._defaultHandlers;n||(n=this._defaultHandlers={_disabled_:{}});if(n[e]){var r=n[e],i=n._disabled_[e];i||(n._disabled_[e]=i=[]),i.push(r);var s=i.indexOf(t);s!=-1&&i.splice(s,1)}n[e]=t},r.removeDefaultHandler=function(e,t){var n=this._defaultHandlers;if(!n)return;var r=n._disabled_[e];if(n[e]==t){var i=n[e];r&&this.setDefaultHandler(e,r.pop())}else if(r){var s=r.indexOf(t);s!=-1&&r.splice(s,1)}},r.on=r.addEventListener=function(e,t,n){this._eventRegistry=this._eventRegistry||{};var r=this._eventRegistry[e];return r||(r=this._eventRegistry[e]=[]),r.indexOf(t)==-1&&r[n?"unshift":"push"](t),t},r.off=r.removeListener=r.removeEventListener=function(e,t){this._eventRegistry=this._eventRegistry||{};var n=this._eventRegistry[e];if(!n)return;var r=n.indexOf(t);r!==-1&&n.splice(r,1)},r.removeAllListeners=function(e){this._eventRegistry&&(this._eventRegistry[e]=[])},t.EventEmitter=r}),define("ace/lib/oop",["require","exports","module"],function(e,t,n){t.inherits=function(){var e=function(){};return function(t,n){e.prototype=n.prototype,t.super_=n.prototype,t.prototype=new e,t.prototype.constructor=t}}(),t.mixin=function(e,t){for(var n in t)e[n]=t[n];return e},t.implement=function(e,n){t.mixin(e,n)}}),define("ace/lib/es5-shim",["require","exports","module"],function(e,t,n){function r(){}function i(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(t){}}function s(e){return e=+e,e!==e?e=0:e!==0&&e!==1/0&&e!==-1/0&&(e=(e>0||-1)*Math.floor(Math.abs(e))),e}function o(e){var t=typeof e;return e===null||t==="undefined"||t==="boolean"||t==="number"||t==="string"}function u(e){var t,n,r;if(o(e))return e;n=e.valueOf;if(typeof n=="function"){t=n.call(e);if(o(t))return t}r=e.toString;if(typeof r=="function"){t=r.call(e);if(o(t))return t}throw new TypeError}Function.prototype.bind||(Function.prototype.bind=function(e){var t=this;if(typeof t!="function")throw new TypeError("Function.prototype.bind called on incompatible "+t);var n=c.call(arguments,1),i=function(){if(this instanceof i){var r=t.apply(this,n.concat(c.call(arguments)));return Object(r)===r?r:this}return t.apply(e,n.concat(c.call(arguments)))};return t.prototype&&(r.prototype=t.prototype,i.prototype=new r,r.prototype=null),i});var a=Function.prototype.call,f=Array.prototype,l=Object.prototype,c=f.slice,h=a.bind(l.toString),p=a.bind(l.hasOwnProperty),d,v,m,g,y;if(y=p(l,"__defineGetter__"))d=a.bind(l.__defineGetter__),v=a.bind(l.__defineSetter__),m=a.bind(l.__lookupGetter__),g=a.bind(l.__lookupSetter__);if([1,2].splice(0).length!=2)if(!function(){function e(e){var t=new Array(e+2);return t[0]=t[1]=0,t}var t=[],n;t.splice.apply(t,e(20)),t.splice.apply(t,e(26)),n=t.length,t.splice(5,0,"XXX"),n+1==t.length;if(n+1==t.length)return!0}())Array.prototype.splice=function(e,t){var n=this.length;e>0?e>n&&(e=n):e==void 0?e=0:e<0&&(e=Math.max(n+e,0)),e+t<n||(t=n-e);var r=this.slice(e,e+t),i=c.call(arguments,2),s=i.length;if(e===n)s&&this.push.apply(this,i);else{var o=Math.min(t,n-e),u=e+o,a=u+s-o,f=n-u,l=n-o;if(a<u)for(var h=0;h<f;++h)this[a+h]=this[u+h];else if(a>u)for(h=f;h--;)this[a+h]=this[u+h];if(s&&e===l)this.length=l,this.push.apply(this,i);else{this.length=l+s;for(h=0;h<s;++h)this[e+h]=i[h]}}return r};else{var b=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?b.apply(this,[e===void 0?0:e,t===void 0?this.length-e:t].concat(c.call(arguments,2))):[]}}Array.isArray||(Array.isArray=function(e){return h(e)=="[object Array]"});var w=Object("a"),E=w[0]!="a"||!(0 in w);Array.prototype.forEach||(Array.prototype.forEach=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=arguments[1],i=-1,s=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError;while(++i<s)i in n&&e.call(r,n[i],i,t)}),Array.prototype.map||(Array.prototype.map=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=Array(r),s=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var o=0;o<r;o++)o in n&&(i[o]=e.call(s,n[o],o,t));return i}),Array.prototype.filter||(Array.prototype.filter=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=[],s,o=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var u=0;u<r;u++)u in n&&(s=n[u],e.call(o,s,u,t)&&i.push(s));return i}),Array.prototype.every||(Array.prototype.every=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var s=0;s<r;s++)if(s in n&&!e.call(i,n[s],s,t))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var s=0;s<r;s++)if(s in n&&e.call(i,n[s],s,t))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");if(!r&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var i=0,s;if(arguments.length>=2)s=arguments[1];else do{if(i in n){s=n[i++];break}if(++i>=r)throw new TypeError("reduce of empty array with no initial value")}while(!0);for(;i<r;i++)i in n&&(s=e.call(void 0,s,n[i],i,t));return s}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");if(!r&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var i,s=r-1;if(arguments.length>=2)i=arguments[1];else do{if(s in n){i=n[s--];break}if(--s<0)throw new TypeError("reduceRight of empty array with no initial value")}while(!0);do s in this&&(i=e.call(void 0,i,n[s],s,t));while(s--);return i});if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function(e){var t=E&&h(this)=="[object String]"?this.split(""):F(this),n=t.length>>>0;if(!n)return-1;var r=0;arguments.length>1&&(r=s(arguments[1])),r=r>=0?r:Math.max(0,n+r);for(;r<n;r++)if(r in t&&t[r]===e)return r;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=function(e){var t=E&&h(this)=="[object String]"?this.split(""):F(this),n=t.length>>>0;if(!n)return-1;var r=n-1;arguments.length>1&&(r=Math.min(r,s(arguments[1]))),r=r>=0?r:n-Math.abs(r);for(;r>=0;r--)if(r in t&&e===t[r])return r;return-1};Object.getPrototypeOf||(Object.getPrototypeOf=function(e){return e.__proto__||(e.constructor?e.constructor.prototype:l)});if(!Object.getOwnPropertyDescriptor){var S="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(e,t){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(S+e);if(!p(e,t))return;var n,r,i;n={enumerable:!0,configurable:!0};if(y){var s=e.__proto__;e.__proto__=l;var r=m(e,t),i=g(e,t);e.__proto__=s;if(r||i)return r&&(n.get=r),i&&(n.set=i),n}return n.value=e[t],n}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(e){return Object.keys(e)});if(!Object.create){var x;Object.prototype.__proto__===null?x=function(){return{__proto__:null}}:x=function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(e,t){var n;if(e===null)n=x();else{if(typeof e!="object")throw new TypeError("typeof prototype["+typeof e+"] != 'object'");var r=function(){};r.prototype=e,n=new r,n.__proto__=e}return t!==void 0&&Object.defineProperties(n,t),n}}if(Object.defineProperty){var T=i({}),N=typeof document=="undefined"||i(document.createElement("div"));if(!T||!N)var C=Object.defineProperty}if(!Object.defineProperty||C){var k="Property description must be an object: ",L="Object.defineProperty called on non-object: ",A="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(e,t,n){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(L+e);if(typeof n!="object"&&typeof n!="function"||n===null)throw new TypeError(k+n);if(C)try{return C.call(Object,e,t,n)}catch(r){}if(p(n,"value"))if(y&&(m(e,t)||g(e,t))){var i=e.__proto__;e.__proto__=l,delete e[t],e[t]=n.value,e.__proto__=i}else e[t]=n.value;else{if(!y)throw new TypeError(A);p(n,"get")&&d(e,t,n.get),p(n,"set")&&v(e,t,n.set)}return e}}Object.defineProperties||(Object.defineProperties=function(e,t){for(var n in t)p(t,n)&&Object.defineProperty(e,n,t[n]);return e}),Object.seal||(Object.seal=function(e){return e}),Object.freeze||(Object.freeze=function(e){return e});try{Object.freeze(function(){})}catch(O){Object.freeze=function(e){return function(t){return typeof t=="function"?t:e(t)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(e){return e}),Object.isSealed||(Object.isSealed=function(e){return!1}),Object.isFrozen||(Object.isFrozen=function(e){return!1}),Object.isExtensible||(Object.isExtensible=function(e){if(Object(e)===e)throw new TypeError;var t="";while(p(e,t))t+="?";e[t]=!0;var n=p(e,t);return delete e[t],n});if(!Object.keys){var M=!0,_=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],D=_.length;for(var P in{toString:null})M=!1;Object.keys=function I(e){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError("Object.keys called on a non-object");var I=[];for(var t in e)p(e,t)&&I.push(t);if(M)for(var n=0,r=D;n<r;n++){var i=_[n];p(e,i)&&I.push(i)}return I}}Date.now||(Date.now=function(){return(new Date).getTime()});var H="	\n\f\r   ᠎              \u2028\u2029";if(!String.prototype.trim||H.trim()){H="["+H+"]";var B=new RegExp("^"+H+H+"*"),j=new RegExp(H+H+"*$");String.prototype.trim=function(){return String(this).replace(B,"").replace(j,"")}}var F=function(e){if(e==null)throw new TypeError("can't convert "+e+" to object");return Object(e)}}),define("ace/mode/lua_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/lua/luaparse"],function(e,t,n){var r=e("../lib/oop"),i=e("../worker/mirror").Mirror,s=e("../mode/lua/luaparse"),o=t.Worker=function(e){i.call(this,e),this.setTimeout(500)};r.inherits(o,i),function(){this.onUpdate=function(){var e=this.doc.getValue();try{s.parse(e)}catch(t){t instanceof SyntaxError&&this.sender.emit("error",{row:t.line-1,column:t.column,text:t.message,type:"error"});return}this.sender.emit("ok")}}.call(o.prototype)}),define("ace/worker/mirror",["require","exports","module","ace/document","ace/lib/lang"],function(e,t,n){var r=e("../document").Document,i=e("../lib/lang"),s=t.Mirror=function(e){this.sender=e;var t=this.doc=new r(""),n=this.deferredUpdate=i.delayedCall(this.onUpdate.bind(this)),s=this;e.on("change",function(e){t.applyDeltas(e.data),n.schedule(s.$timeout)})};(function(){this.$timeout=500,this.setTimeout=function(e){this.$timeout=e},this.setValue=function(e){this.doc.setValue(e),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(e){this.sender.callback(this.doc.getValue(),e)},this.onUpdate=function(){}}).call(s.prototype)}),define("ace/document",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=e("./range").Range,o=e("./anchor").Anchor,u=function(e){this.$lines=[],e.length==0?this.$lines=[""]:Array.isArray(e)?this._insertLines(0,e):this.insert({row:0,column:0},e)};(function(){r.implement(this,i),this.setValue=function(e){var t=this.getLength();this.remove(new s(0,0,t,this.getLine(t-1).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new o(this,e,t)},"aaa".split(/a/).length==0?this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:this.$split=function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[1]:"\n"},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\r\n";case"unix":return"\n";default:return this.$autoNewLine}},this.$autoNewLine="\n",this.$newLineMode="auto",this.setNewLineMode=function(e){if(this.$newLineMode===e)return;this.$newLineMode=e},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return e=="\r\n"||e=="\r"||e=="\n"},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){if(e.start.row==e.end.row)return this.getLine(e.start.row).substring(e.start.column,e.end.column);var t=this.getLines(e.start.row,e.end.row);t[0]=(t[0]||"").substring(e.start.column);var n=t.length-1;return e.end.row-e.start.row==n&&(t[n]=t[n].substring(0,e.end.column)),t.join(this.getNewLineCharacter())},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):e.row<0&&(e.row=0),e},this.insert=function(e,t){if(!t||t.length===0)return e;e=this.$clipPosition(e),this.getLength()<=1&&this.$detectNewLine(t);var n=this.$split(t),r=n.splice(0,1)[0],i=n.length==0?null:n.splice(n.length-1,1)[0];return e=this.insertInLine(e,r),i!==null&&(e=this.insertNewLine(e),e=this._insertLines(e.row,n),e=this.insertInLine(e,i||"")),e},this.insertLines=function(e,t){return e>=this.getLength()?this.insert({row:e,column:0},"\n"+t.join("\n")):this._insertLines(Math.max(e,0),t)},this._insertLines=function(e,t){if(t.length==0)return{row:e,column:0};if(t.length>65535){var n=this._insertLines(e,t.slice(65535));t=t.slice(0,65535)}var r=[e,0];r.push.apply(r,t),this.$lines.splice.apply(this.$lines,r);var i=new s(e,0,e+t.length,0),o={action:"insertLines",range:i,lines:t};return this._emit("change",{data:o}),n||i.end},this.insertNewLine=function(e){e=this.$clipPosition(e);var t=this.$lines[e.row]||"";this.$lines[e.row]=t.substring(0,e.column),this.$lines.splice(e.row+1,0,t.substring(e.column,t.length));var n={row:e.row+1,column:0},r={action:"insertText",range:s.fromPoints(e,n),text:this.getNewLineCharacter()};return this._emit("change",{data:r}),n},this.insertInLine=function(e,t){if(t.length==0)return e;var n=this.$lines[e.row]||"";this.$lines[e.row]=n.substring(0,e.column)+t+n.substring(e.column);var r={row:e.row,column:e.column+t.length},i={action:"insertText",range:s.fromPoints(e,r),text:t};return this._emit("change",{data:i}),r},this.remove=function(e){!e instanceof s&&(e=s.fromPoints(e.start,e.end)),e.start=this.$clipPosition(e.start),e.end=this.$clipPosition(e.end);if(e.isEmpty())return e.start;var t=e.start.row,n=e.end.row;if(e.isMultiLine()){var r=e.start.column==0?t:t+1,i=n-1;e.end.column>0&&this.removeInLine(n,0,e.end.column),i>=r&&this._removeLines(r,i),r!=t&&(this.removeInLine(t,e.start.column,this.getLine(t).length),this.removeNewLine(e.start.row))}else this.removeInLine(t,e.start.column,e.end.column);return e.start},this.removeInLine=function(e,t,n){if(t==n)return;var r=new s(e,t,e,n),i=this.getLine(e),o=i.substring(t,n),u=i.substring(0,t)+i.substring(n,i.length);this.$lines.splice(e,1,u);var a={action:"removeText",range:r,text:o};return this._emit("change",{data:a}),r.start},this.removeLines=function(e,t){return e<0||t>=this.getLength()?this.remove(new s(e,0,t+1,0)):this._removeLines(e,t)},this._removeLines=function(e,t){var n=new s(e,0,t+1,0),r=this.$lines.splice(e,t-e+1),i={action:"removeLines",range:n,nl:this.getNewLineCharacter(),lines:r};return this._emit("change",{data:i}),r},this.removeNewLine=function(e){var t=this.getLine(e),n=this.getLine(e+1),r=new s(e,t.length,e+1,0),i=t+n;this.$lines.splice(e,2,i);var o={action:"removeText",range:r,text:this.getNewLineCharacter()};this._emit("change",{data:o})},this.replace=function(e,t){!e instanceof s&&(e=s.fromPoints(e.start,e.end));if(t.length==0&&e.isEmpty())return e.start;if(t==this.getTextRange(e))return e.end;this.remove(e);if(t)var n=this.insert(e.start,t);else n=e.start;return n},this.applyDeltas=function(e){for(var t=0;t<e.length;t++){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this.insertLines(r.start.row,n.lines):n.action=="insertText"?this.insert(r.start,n.text):n.action=="removeLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="removeText"&&this.remove(r)}},this.revertDeltas=function(e){for(var t=e.length-1;t>=0;t--){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="insertText"?this.remove(r):n.action=="removeLines"?this._insertLines(r.start.row,n.lines):n.action=="removeText"&&this.insert(r.start,n.text)}},this.indexToPosition=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length;for(var i=t||0,s=n.length;i<s;i++){e-=n[i].length+r;if(e<0)return{row:i,column:e+n[i].length+r}}return{row:s-1,column:n[s-1].length}},this.positionToIndex=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length,i=0,s=Math.min(e.row,n.length);for(var o=t||0;o<s;++o)i+=n[o].length+r;return i+e.column}}).call(u.prototype),t.Document=u}),define("ace/range",["require","exports","module"],function(e,t,n){var r=function(e,t){return e.row-t.row||e.column-t.column},i=function(e,t,n,r){this.start={row:e,column:t},this.end={row:n,column:r}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return this.compare(e,t)==0},this.compareRange=function(e){var t,n=e.end,r=e.start;return t=this.compare(n.row,n.column),t==1?(t=this.compare(r.row,r.column),t==1?2:t==0?1:0):t==-1?-2:(t=this.compare(r.row,r.column),t==-1?-1:t==1?42:0)},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return this.comparePoint(e.start)==0&&this.comparePoint(e.end)==0},this.intersects=function(e){var t=this.compareRange(e);return t==-1||t==0||t==1},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){typeof e=="object"?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){typeof e=="object"?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)||this.isStart(e,t)?!1:!0:!1},this.insideStart=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)?!1:!0:!1},this.insideEnd=function(e,t){return this.compare(e,t)==0?this.isStart(e,t)?!1:!0:!1},this.compare=function(e,t){return!this.isMultiLine()&&e===this.start.row?t<this.start.column?-1:t>this.end.column?1:0:e<this.start.row?-1:e>this.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?t<=this.end.column?0:1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var n={row:t+1,column:0};else if(this.end.row<e)var n={row:e,column:0};if(this.start.row>t)var r={row:t+1,column:0};else if(this.start.row<e)var r={row:e,column:0};return i.fromPoints(r||this.start,n||this.end)},this.extend=function(e,t){var n=this.compare(e,t);if(n==0)return this;if(n==-1)var r={row:e,column:t};else var s={row:e,column:t};return i.fromPoints(r||this.start,s||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return i.fromPoints(this.start,this.end)},this.collapseRows=function(){return this.end.column==0?new i(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new i(this.start.row,0,this.end.row,0)},this.toScreenRange=function(e){var t=e.documentToScreenPosition(this.start),n=e.documentToScreenPosition(this.end);return new i(t.row,t.column,n.row,n.column)},this.moveBy=function(e,t){this.start.row+=e,this.start.column+=t,this.end.row+=e,this.end.column+=t}}).call(i.prototype),i.fromPoints=function(e,t){return new i(e.row,e.column,t.row,t.column)},i.comparePoints=r,i.comparePoints=function(e,t){return e.row-t.row||e.column-t.column},t.Range=i}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=t.Anchor=function(e,t,n){this.$onChange=this.onChange.bind(this),this.attach(e),typeof n=="undefined"?this.setPosition(t.row,t.column):this.setPosition(t,n)};(function(){r.implement(this,i),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.$insertRight=!1,this.onChange=function(e){var t=e.data,n=t.range;if(n.start.row==n.end.row&&n.start.row!=this.row)return;if(n.start.row>this.row)return;if(n.start.row==this.row&&n.start.column>this.column)return;var r=this.row,i=this.column,s=n.start,o=n.end;if(t.action==="insertText")if(s.row===r&&s.column<=i){if(s.column!==i||!this.$insertRight)s.row===o.row?i+=o.column-s.column:(i-=s.column,r+=o.row-s.row)}else s.row!==o.row&&s.row<r&&(r+=o.row-s.row);else t.action==="insertLines"?s.row<=r&&(r+=o.row-s.row):t.action==="removeText"?s.row===r&&s.column<i?o.column>=i?i=s.column:i=Math.max(0,i-(o.column-s.column)):s.row!==o.row&&s.row<r?(o.row===r&&(i=Math.max(0,i-o.column)+s.column),r-=o.row-s.row):o.row===r&&(r-=o.row-s.row,i=Math.max(0,i-o.column)+s.column):t.action=="removeLines"&&s.row<=r&&(o.row<=r?r-=o.row-s.row:(r=s.row,i=0));this.setPosition(r,i,!0)},this.setPosition=function(e,t,n){var r;n?r={row:e,column:t}:r=this.$clipPositionToDocument(e,t);if(this.row==r.row&&this.column==r.column)return;var i={row:this.row,column:this.column};this.row=r.row,this.column=r.column,this._emit("change",{old:i,value:r})},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(e){this.document=e||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var n={};return e>=this.document.getLength()?(n.row=Math.max(0,this.document.getLength()-1),n.column=this.document.getLine(n.row).length):e<0?(n.row=0,n.column=0):(n.row=e,n.column=Math.min(this.document.getLine(n.row).length,Math.max(0,t))),t<0&&(n.column=0),n}}).call(s.prototype)}),define("ace/lib/lang",["require","exports","module"],function(e,t,n){t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){var n="";while(t>0){t&1&&(n+=e);if(t>>=1)e+=e}return n};var r=/^\s\s*/,i=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(r,"")},t.stringTrimRight=function(e){return e.replace(i,"")},t.copyObject=function(e){var t={};for(var n in e)t[n]=e[n];return t},t.copyArray=function(e){var t=[];for(var n=0,r=e.length;n<r;n++)e[n]&&typeof e[n]=="object"?t[n]=this.copyObject(e[n]):t[n]=e[n];return t},t.deepCopy=function(e){if(typeof e!="object")return e;var t=e.constructor();for(var n in e)typeof e[n]=="object"?t[n]=this.deepCopy(e[n]):t[n]=e[n];return t},t.arrayToMap=function(e){var t={};for(var n=0;n<e.length;n++)t[e[n]]=1;return t},t.createMap=function(e){var t=Object.create(null);for(var n in e)t[n]=e[n];return t},t.arrayRemove=function(e,t){for(var n=0;n<=e.length;n++)t===e[n]&&e.splice(n,1)},t.escapeRegExp=function(e){return e.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},t.escapeHTML=function(e){return e.replace(/&/g,"&#38;").replace(/"/g,"&#34;").replace(/'/g,"&#39;").replace(/</g,"&#60;")},t.getMatchOffsets=function(e,t){var n=[];return e.replace(t,function(e){n.push({offset:arguments[arguments.length-2],length:e.length})}),n},t.deferredCall=function(e){var t=null,n=function(){t=null,e()},r=function(e){return r.cancel(),t=setTimeout(n,e||0),r};return r.schedule=r,r.call=function(){return this.cancel(),e(),r},r.cancel=function(){return clearTimeout(t),t=null,r},r},t.delayedCall=function(e,t){var n=null,r=function(){n=null,e()},i=function(e){n&&clearTimeout(n),n=setTimeout(r,e||t)};return i.delay=i,i.schedule=function(e){n==null&&(n=setTimeout(r,e||0))},i.call=function(){this.cancel(),e()},i.cancel=function(){n&&clearTimeout(n),n=null},i.isPending=function(){return n},i}}),define("ace/mode/lua/luaparse",["require","exports","module"],function(e,t,n){(function(e,n,r){r(t)})(this,"luaparse",function(e){function t(e){if(Jt){var t=$t.pop();t.complete(),bt.locations&&(e.loc=t.loc),bt.ranges&&(e.range=t.range)}return e}function n(e,t,n){for(var r=0,i=e.length;r<i;r++)if(e[r][t]===n)return r;return-1}function r(e){var t=Dt.call(arguments,1);return e=e.replace(/%(\d)/g,function(e,n){return""+t[n-1]||""}),e}function i(){var e=Dt.call(arguments),t={},n,r;for(var i=0,s=e.length;i<s;i++){n=e[i];for(r in n)n.hasOwnProperty(r)&&(t[r]=n[r])}return t}function s(e){var t=r.apply(null,Dt.call(arguments,1)),n,i;throw"undefined"!=typeof e.line?(i=e.range[0]-e.lineStart,n=new SyntaxError(r("[%1:%2] %3",e.line,i,t)),n.line=e.line,n.index=e.range[0],n.column=i):(i=Bt-zt+1,n=new SyntaxError(r("[%1:%2] %3",Ut,i,t)),n.index=Bt,n.line=Ut,n.column=i),n}function o(e,t){s(t,Mt.expectedToken,e,t.value)}function u(e,t){"undefined"==typeof t&&(t=It.value);if("undefined"!=typeof e.type){var n;switch(e.type){case xt:n="string";break;case Tt:n="keyword";break;case Nt:n="identifier";break;case Ct:n="number";break;case kt:n="symbol";break;case Lt:n="boolean";break;case At:return s(e,Mt.unexpected,"symbol","nil",t)}return s(e,Mt.unexpected,n,e.value,t)}return s(e,Mt.unexpected,"symbol",e,t)}function a(){f();while(45===yt.charCodeAt(Bt)&&45===yt.charCodeAt(Bt+1))b(),f();if(Bt>=wt)return{type:St,value:"<eof>",line:Ut,lineStart:zt,range:[Bt,Bt]};var e=yt.charCodeAt(Bt),t=yt.charCodeAt(Bt+1);Rt=Bt;if(L(e))return l();switch(e){case 39:case 34:return p();case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return v();case 46:if(C(t))return v();if(46===t)return 46===yt.charCodeAt(Bt+2)?h():c("..");return c(".");case 61:if(61===t)return c("==");return c("=");case 62:if(61===t)return c(">=");return c(">");case 60:if(61===t)return c("<=");return c("<");case 126:if(61===t)return c("~=");return s({},Mt.expected,"=","~");case 58:if(58===t)return c("::");return c(":");case 91:if(91===t||61===t)return d();return c("[");case 42:case 47:case 94:case 37:case 44:case 123:case 125:case 93:case 40:case 41:case 59:case 35:case 45:case 43:return c(yt.charAt(Bt))}return u(yt.charAt(Bt))}function f(){while(Bt<wt){var e=yt.charCodeAt(Bt);if(T(e))Bt++;else{if(!N(e))break;Ut++,zt=++Bt}}}function l(){var e,t;while(A(yt.charCodeAt(++Bt)));return e=yt.slice(Rt,Bt),O(e)?t=Tt:"true"===e||"false"===e?(t=Lt,e="true"===e):"nil"===e?(t=At,e=null):t=Nt,{type:t,value:e,line:Ut,lineStart:zt,range:[Rt,Bt]}}function c(e){return Bt+=e.length,{type:kt,value:e,line:Ut,lineStart:zt,range:[Rt,Bt]}}function h(){return Bt+=3,{type:Ot,value:"...",line:Ut,lineStart:zt,range:[Rt,Bt]}}function p(){var e=yt.charCodeAt(Bt++),t=Bt,n="",r;while(Bt<wt){r=yt.charCodeAt(Bt++);if(e===r)break;if(92===r)n+=yt.slice(t,Bt-1)+y(),t=Bt;else if(Bt>=wt||N(r))n+=yt.slice(t,Bt-1),s({},Mt.unfinishedString,n+String.fromCharCode(r))}return n+=yt.slice(t,Bt-1),{type:xt,value:n,line:Ut,lineStart:zt,range:[Rt,Bt]}}function d(){var e=w();return!1===e&&s(jt,Mt.expected,"[",jt.value),{type:xt,value:e,line:Ut,lineStart:zt,range:[Rt,Bt]}}function v(){var e=yt.charAt(Bt),t=yt.charAt(Bt+1),n="0"===e&&"xX".indexOf(t||null)>=0?m():g();return{type:Ct,value:n,line:Ut,lineStart:zt,range:[Rt,Bt]}}function m(){var e=0,t=1,n=1,r,i,o,u;u=Bt+=2,k(yt.charCodeAt(Bt))||s({},Mt.malformedNumber,yt.slice(Rt,Bt));while(k(yt.charCodeAt(Bt)))Bt++;r=parseInt(yt.slice(u,Bt),16);if("."===yt.charAt(Bt)){i=++Bt;while(k(yt.charCodeAt(Bt)))Bt++;e=yt.slice(i,Bt),e=i===Bt?0:parseInt(e,16)/Math.pow(16,Bt-i)}if("pP".indexOf(yt.charAt(Bt)||null)>=0){Bt++,"+-".indexOf(yt.charAt(Bt)||null)>=0&&(n="+"===yt.charAt(Bt++)?1:-1),o=Bt,C(yt.charCodeAt(Bt))||s({},Mt.malformedNumber,yt.slice(Rt,Bt));while(C(yt.charCodeAt(Bt)))Bt++;t=yt.slice(o,Bt),t=Math.pow(2,t*n)}return(r+e)*t}function g(){while(C(yt.charCodeAt(Bt)))Bt++;if("."===yt.charAt(Bt)){Bt++;while(C(yt.charCodeAt(Bt)))Bt++}if("eE".indexOf(yt.charAt(Bt)||null)>=0){Bt++,"+-".indexOf(yt.charAt(Bt)||null)>=0&&Bt++,C(yt.charCodeAt(Bt))||s({},Mt.malformedNumber,yt.slice(Rt,Bt));while(C(yt.charCodeAt(Bt)))Bt++}return parseFloat(yt.slice(Rt,Bt))}function y(){var e=Bt;switch(yt.charAt(Bt)){case"n":return Bt++,"\n";case"r":return Bt++,"\r";case"t":return Bt++,"	";case"v":return Bt++,"";case"b":return Bt++,"\b";case"f":return Bt++,"\f";case"z":return Bt++,f(),"";case"x":if(k(yt.charCodeAt(Bt+1))&&k(yt.charCodeAt(Bt+2)))return Bt+=3,"\\"+yt.slice(e,Bt);return"\\"+yt.charAt(Bt++);default:if(C(yt.charCodeAt(Bt))){while(C(yt.charCodeAt(++Bt)));return"\\"+yt.slice(e,Bt)}return yt.charAt(Bt++)}}function b(){Rt=Bt,Bt+=2;var e=yt.charAt(Bt),t="",n=!1,r=Bt,i=zt,s=Ut;"["===e&&(t=w(),!1===t?t=e:n=!0);if(!n){while(Bt<wt){if(N(yt.charCodeAt(Bt)))break;Bt++}bt.comments&&(t=yt.slice(r,Bt))}if(bt.comments){var o=_t.comment(t,yt.slice(Rt,Bt));bt.locations&&(o.loc={start:{line:s,column:Rt-i},end:{line:Ut,column:Bt-zt}}),bt.ranges&&(o.range=[Rt,Bt]),qt.push(o)}}function w(){var e=0,t="",n=!1,r,i;Bt++;while("="===yt.charAt(Bt+e))e++;if("["!==yt.charAt(Bt+e))return!1;Bt+=e+1,N(yt.charCodeAt(Bt))&&(Ut++,zt=Bt++),i=Bt;while(Bt<wt){r=yt.charAt(Bt++),N(r.charCodeAt(0))&&(Ut++,zt=Bt);if("]"===r){n=!0;for(var s=0;s<e;s++)"="!==yt.charAt(Bt+s)&&(n=!1);"]"!==yt.charAt(Bt+e)&&(n=!1)}if(n)break}return t+=yt.slice(i,Bt-1),Bt+=e+1,t}function E(){Ft=jt,jt=It,It=a()}function S(e){return e===jt.value?(E(),!0):!1}function x(e){e===jt.value?E():s(jt,Mt.expected,e,jt.value)}function T(e){return 9===e||32===e||11===e||12===e}function N(e){return 10===e||13===e}function C(e){return e>=48&&e<=57}function k(e){return e>=48&&e<=57||e>=97&&e<=102||e>=65&&e<=70}function L(e){return e>=65&&e<=90||e>=97&&e<=122||95===e}function A(e){return e>=65&&e<=90||e>=97&&e<=122||95===e||e>=48&&e<=57}function O(e){switch(e.length){case 2:return"do"===e||"if"===e||"in"===e||"or"===e;case 3:return"and"===e||"end"===e||"for"===e||"not"===e;case 4:return"else"===e||"goto"===e||"then"===e;case 5:return"break"===e||"local"===e||"until"===e||"while"===e;case 6:return"elseif"===e||"repeat"===e||"return"===e;case 8:return"function"===e}return!1}function M(e){return kt===e.type?"#-".indexOf(e.value)>=0:Tt===e.type?"not"===e.value:!1}function _(e){switch(e.type){case"CallExpression":case"TableCallExpression":case"StringCallExpression":return!0}return!1}function D(e){if(St===e.type)return!0;if(Tt!==e.type)return!1;switch(e.value){case"else":case"elseif":case"end":case"until":return!0;default:return!1}}function P(){Wt.push(Array.apply(null,Wt[Xt++]))}function H(){Wt.pop(),Xt--}function B(e){if(-1!==Ht(Wt[Xt],e))return;Wt[Xt].push(e)}function j(e){B(e.name),F(e,!0)}function F(e,t){!t&&-1===n(Vt,"name",e.name)&&Vt.push(e),e.isLocal=t}function I(e){return-1!==Ht(Wt[Xt],e)}function q(){return new R(jt)}function R(e){bt.locations&&(this.loc={start:{line:e.line,column:e.range[0]-e.lineStart},end:{line:0,column:0}}),bt.ranges&&(this.range=[e.range[0],0])}function U(){Jt&&$t.push(q())}function z(e){Jt&&$t.push(e)}function W(){E(),U();var e=X();return St!==jt.type&&u(jt),Jt&&!e.length&&(Ft=jt),t(_t.chunk(e))}function X(e){var t=[],n;bt.scope&&P();while(!D(jt)){if("return"===jt.value){t.push(V());break}n=V(),n&&t.push(n)}return bt.scope&&H(),t}function V(){U();if(Tt===jt.type)switch(jt.value){case"local":return E(),nt();case"if":return E(),et();case"return":return E(),Z();case"function":E();var e=ot();return st(e);case"while":return E(),G();case"for":return E(),tt();case"repeat":return E(),Y();case"break":return E(),J();case"do":return E(),Q();case"goto":return E(),K()}if(kt===jt.type&&S("::"))return $();Jt&&$t.pop();if(S(";"))return;return rt()}function $(){var e=jt.value,n=it();return bt.scope&&(B("::"+e+"::"),F(n,!0)),x("::"),t(_t.labelStatement(n))}function J(){return t(_t.breakStatement())}function K(){var e=jt.value,n=it();return bt.scope&&(n.isLabel=I("::"+e+"::")),t(_t.gotoStatement(n))}function Q(){var e=X();return x("end"),t(_t.doStatement(e))}function G(){var e=ft();x("do");var n=X();return x("end"),t(_t.whileStatement(e,n))}function Y(){var e=X();x("until");var n=ft();return t(_t.repeatStatement(n,e))}function Z(){var e=[];if("end"!==jt.value){var n=at();null!=n&&e.push(n);while(S(","))n=ft(),e.push(n);S(";")}return t(_t.returnStatement(e))}function et(){var e=[],n,r,i;Jt&&(i=$t[$t.length-1],$t.push(i)),n=ft(),x("then"),r=X(),e.push(t(_t.ifClause(n,r))),Jt&&(i=q());while(S("elseif"))z(i),n=ft(),x("then"),r=X(),e.push(t(_t.elseifClause(n,r))),Jt&&(i=q());return S("else")&&(Jt&&(i=new R(Ft),$t.push(i)),r=X(),e.push(t(_t.elseClause(r)))),x("end"),t(_t.ifStatement(e))}function tt(){var e=it(),n;bt.scope&&j(e);if(S("=")){var r=ft();x(",");var i=ft(),s=S(",")?ft():null;return x("do"),n=X(),x("end"),t(_t.forNumericStatement(e,r,i,s,n))}var o=[e];while(S(","))e=it(),bt.scope&&j(e),o.push(e);x("in");var u=[];do{var a=ft();u.push(a)}while(S(","));return x("do"),n=X(),x("end"),t(_t.forGenericStatement(o,u,n))}function nt(){var e;if(Nt===jt.type){var n=[],r=[];do e=it(),n.push(e);while(S(","));if(S("="))do{var i=ft();r.push(i)}while(S(","));if(bt.scope)for(var s=0,u=n.length;s<u;s++)j(n[s]);return t(_t.localStatement(n,r))}if(S("function"))return e=it(),bt.scope&&j(e),st(e,!0);o("<name>",jt)}function rt(){var e=jt,n,r;Jt&&(r=q()),n=ht();if(null==n)return u(jt);if(",=".indexOf(jt.value)>=0){var i=[n],s=[],a;while(S(","))a=ht(),null==a&&o("<expression>",jt),i.push(a);x("=");do a=ft(),s.push(a);while(S(","));return z(r),t(_t.assignmentStatement(i,s))}return _(n)?(z(r),t(_t.callStatement(n))):u(e)}function it(){U();var e=jt.value;return Nt!==jt.type&&o("<name>",jt),E(),t(_t.identifier(e))}function st(e,n){var r=[];x("(");if(!S(")"))for(;;)if(Nt===jt.type){var i=it();bt.scope&&j(i),r.push(i);if(S(","))continue;if(S(")"))break}else{if(Ot===jt.type){r.push(dt()),x(")");break}o("<name> or '...'",jt)}var s=X();return x("end"),n=n||!1,t(_t.functionStatement(e,r,n,s))}function ot(){var e,n,r;Jt&&(r=q()),e=it(),bt.scope&&F(e,!1);while(S("."))z(r),n=it(),bt.scope&&F(n,!1),e=t(_t.memberExpression(e,".",n));return S(":")&&(z(r),n=it(),bt.scope&&F(n,!1),e=t(_t.memberExpression(e,":",n))),e}function ut(){var e=[],n,r;for(;;){U();if(kt===jt.type&&S("["))n=ft(),x("]"),x("="),r=ft(),e.push(t(_t.tableKey(n,r)));else if(Nt===jt.type)n=ft(),S("=")?(r=ft(),e.push(t(_t.tableKeyString(n,r)))):e.push(t(_t.tableValue(n)));else{if(null==(r=at())){$t.pop();break}e.push(t(_t.tableValue(r)))}if(",;".indexOf(jt.value)>=0){E();continue}if("}"===jt.value)break}return x("}"),t(_t.tableConstructorExpression(e))}function at(){var e=ct(0);return e}function ft(){var e=at();if(null!=e)return e;o("<expression>",jt)}function lt(e){var t=e.charCodeAt(0),n=e.length;if(1===n)switch(t){case 94:return 10;case 42:case 47:case 37:return 7;case 43:case 45:return 6;case 60:case 62:return 3}else if(2===n)switch(t){case 46:return 5;case 60:case 62:case 61:case 126:return 3;case 111:return 1}else if(97===t&&"and"===e)return 2;return 0}function ct(e){var n=jt.value,r,i;Jt&&(i=q());if(M(jt)){U(),E();var s=ct(8);s==null&&o("<expression>",jt),r=t(_t.unaryExpression(n,s))}null==r&&(r=dt(),null==r&&(r=ht()));if(null==r)return null;var u;for(;;){n=jt.value,u=kt===jt.type||Tt===jt.type?lt(n):0;if(u===0||u<=e)break;("^"===n||".."===n)&&u--,E();var a=ct(u);null==a&&o("<expression>",jt),Jt&&$t.push(i),r=t(_t.binaryExpression(n,r,a))}return r}function ht(){var e,n,r,i;Jt&&(r=q());if(Nt===jt.type)n=jt.value,e=it(),bt.scope&&F(e,i=I(n));else{if(!S("("))return null;e=ft(),x(")"),bt.scope&&(i=e.isLocal)}var s,o;for(;;)if(kt===jt.type)switch(jt.value){case"[":z(r),E(),s=ft(),e=t(_t.indexExpression(e,s)),x("]");break;case".":z(r),E(),o=it(),bt.scope&&F(o,i),e=t(_t.memberExpression(e,".",o));break;case":":z(r),E(),o=it(),bt.scope&&F(o,i),e=t(_t.memberExpression(e,":",o)),z(r),e=pt(e);break;case"(":case"{":z(r),e=pt(e);break;default:return e}else{if(xt!==jt.type)break;z(r),e=pt(e)}return e}function pt(e){if(kt===jt.type)switch(jt.value){case"(":E();var n=[],r=at();null!=r&&n.push(r);while(S(","))r=ft(),n.push(r);return x(")"),t(_t.callExpression(e,n));case"{":U(),E();var i=ut();return t(_t.tableCallExpression(e,i))}else if(xt===jt.type)return t(_t.stringCallExpression(e,dt()));o("function arguments",jt)}function dt(){var e=xt|Ct|Lt|At|Ot,n=jt.value,r=jt.type,i;Jt&&(i=q());if(r&e){z(i);var s=yt.slice(jt.range[0],jt.range[1]);return E(),t(_t.literal(r,n,s))}if(Tt===r&&"function"===n)return z(i),E(),st(null);if(S("{"))return z(i),ut()}function vt(t,n){return"undefined"==typeof n&&"object"==typeof t&&(n=t,t=undefined),n||(n={}),yt=t||"",bt=i(Et,n),Bt=0,Ut=1,zt=0,wt=yt.length,Wt=[[]],Xt=0,Vt=[],$t=[],bt.comments&&(qt=[]),bt.wait?e:gt()}function mt(t){return yt+=String(t),wt=yt.length,e}function gt(e){"undefined"!=typeof e&&mt(e),wt=yt.length,Jt=bt.locations||bt.ranges,It=a();var t=W();bt.comments&&(t.comments=qt),bt.scope&&(t.globals=Vt);if($t.length>0)throw new Error("Location tracking failed. This is most likely a bug in luaparse");return t}e.version="0.1.4";var yt,bt,wt,Et=e.defaultOptions={wait:!1,comments:!0,scope:!1,locations:!1,ranges:!1},St=1,xt=2,Tt=4,Nt=8,Ct=16,kt=32,Lt=64,At=128,Ot=256;e.tokenTypes={EOF:St,StringLiteral:xt,Keyword:Tt,Identifier:Nt,NumericLiteral:Ct,Punctuator:kt,BooleanLiteral:Lt,NilLiteral:At,VarargLiteral:Ot};var Mt=e.errors={unexpected:"Unexpected %1 '%2' near '%3'",expected:"'%1' expected near '%2'",expectedToken:"%1 expected near '%2'",unfinishedString:"unfinished string near '%1'",malformedNumber:"malformed number near '%1'"},_t=e.ast={labelStatement:function(e){return{type:"LabelStatement",label:e}},breakStatement:function(){return{type:"BreakStatement"}},gotoStatement:function(e){return{type:"GotoStatement",label:e}},returnStatement:function(e){return{type:"ReturnStatement",arguments:e}},ifStatement:function(e){return{type:"IfStatement",clauses:e}},ifClause:function(e,t){return{type:"IfClause",condition:e,body:t}},elseifClause:function(e,t){return{type:"ElseifClause",condition:e,body:t}},elseClause:function(e){return{type:"ElseClause",body:e}},whileStatement:function(e,t){return{type:"WhileStatement",condition:e,body:t}},doStatement:function(e){return{type:"DoStatement",body:e}},repeatStatement:function(e,t){return{type:"RepeatStatement",condition:e,body:t}},localStatement:function(e,t){return{type:"LocalStatement",variables:e,init:t}},assignmentStatement:function(e,t){return{type:"AssignmentStatement",variables:e,init:t}},callStatement:function(e){return{type:"CallStatement",expression:e}},functionStatement:function(e,t,n,r){return{type:"FunctionDeclaration",identifier:e,isLocal:n,parameters:t,body:r}},forNumericStatement:function(e,t,n,r,i){return{type:"ForNumericStatement",variable:e,start:t,end:n,step:r,body:i}},forGenericStatement:function(e,t,n){return{type:"ForGenericStatement",variables:e,iterators:t,body:n}},chunk:function(e){return{type:"Chunk",body:e}},identifier:function(e){return{type:"Identifier",name:e}},literal:function(e,t,n){return e=e===xt?"StringLiteral":e===Ct?"NumericLiteral":e===Lt?"BooleanLiteral":e===At?"NilLiteral":"VarargLiteral",{type:e,value:t,raw:n}},tableKey:function(e,t){return{type:"TableKey",key:e,value:t}},tableKeyString:function(e,t){return{type:"TableKeyString",key:e,value:t}},tableValue:function(e){return{type:"TableValue",value:e}},tableConstructorExpression:function(e){return{type:"TableConstructorExpression",fields:e}},binaryExpression:function(e,t,n){var r="and"===e||"or"===e?"LogicalExpression":"BinaryExpression";return{type:r,operator:e,left:t,right:n}},unaryExpression:function(e,t){return{type:"UnaryExpression",operator:e,argument:t}},memberExpression:function(e,t,n){return{type:"MemberExpression",indexer:t,identifier:n,base:e}},indexExpression:function(e,t){return{type:"IndexExpression",base:e,index:t}},callExpression:function(e,t){return{type:"CallExpression",base:e,arguments:t}},tableCallExpression:function(e,t){return{type:"TableCallExpression",base:e,arguments:t}},stringCallExpression:function(e,t){return{type:"StringCallExpression",base:e,argument:t}},comment:function(e,t){return{type:"Comment",value:e,raw:t}}},Dt=Array.prototype.slice,Pt=Object.prototype.toString,Ht=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},Bt,jt,Ft,It,qt,Rt,Ut,zt;e.lex=a;var Wt,Xt,Vt,$t=[],Jt;R.prototype.complete=function(){bt.locations&&(this.loc.end.line=Ft.line,this.loc.end.column=Ft.range[1]-Ft.lineStart),bt.ranges&&(this.range[1]=Ft.range[1])},e.parse=vt,e.write=mt,e.end=gt})})
Exemplo n.º 18
0
Arquivo: mode-r.js Projeto: att/rcloud
   (function()
   {
      oop.implement(this, RMatchingBraceOutdent);

      this.tokenRe = new RegExp("^["
          + unicode.packages.L
          + unicode.packages.Mn + unicode.packages.Mc
          + unicode.packages.Nd
          + unicode.packages.Pc + "._]+", "g"
      );

      this.nonTokenRe = new RegExp("^(?:[^"
          + unicode.packages.L
          + unicode.packages.Mn + unicode.packages.Mc
          + unicode.packages.Nd
          + unicode.packages.Pc + "._]|\s])+", "g"
      );

      this.$complements = {
               "(": ")",
               "[": "]",
               '"': '"',
               "'": "'",
               "{": "}"
            };
      this.$reOpen = /^[(["'{]$/;
      this.$reClose = /^[)\]"'}]$/;

      this.getNextLineIndent = function(state, line, tab, tabSize, row)
      {
         return this.codeModel.getNextLineIndent(row, line, state, tab, tabSize);
      };

      this.allowAutoInsert = this.smartAllowAutoInsert;

      this.getIndentForOpenBrace = function(openBracePos)
      {
         return this.codeModel.getIndentForOpenBrace(openBracePos);
      };

      this.$getIndent = function(line) {
         var match = line.match(/^(\s+)/);
         if (match) {
            return match[1];
         }

         return "";
      };

      this.transformAction = function(state, action, editor, session, text) {
         if (action === 'insertion' && text === "\n") {

            // If newline in a doxygen comment, continue the comment
            var pos = editor.getSelectionRange().start;
            var match = /^((\s*#+')\s*)/.exec(session.doc.getLine(pos.row));
            if (match && editor.getSelectionRange().start.column >= match[2].length) {
               return {text: "\n" + match[1]};
            }
         }
         return false;
      };
      
      this.lineCommentStart = ["#"];
      
      this.getCompletionsAsync = function(state, session, pos, callback) {
        if(this.$completer) {
          this.$completer.getCompletions(null, session, pos, callback);
        } else {
          callback(null, []);
        }
      };
      
      this.$id = "ace/mode/r";
   }).call(Mode.prototype);
Exemplo n.º 19
0
(function(){

    oop.implement(this, EventEmitter);

    /**
     *
     **/
    this.setDataProvider = function(provider) {
        if (this.provider) {
            var oldProvider = this.provider;
            // this.session.off("changeScrollLeft", this.$onScrollLeftChange);

            this.selection.off("changeCaret", this.$onCaretChange);
            this.selection.off("change", this.$onSelectionChange);
            
            oldProvider.off("changeClass", this.$onChangeClass);
            oldProvider.off("expand", this.$redraw);
            oldProvider.off("collapse", this.$redraw);
            oldProvider.off("change", this.$redraw);
            oldProvider.off("changeScrollTop", this.$onScrollTopChange);
            oldProvider.off("changeScrollLeft", this.$onScrollLeftChange);
        }

        this.provider = provider;
        this.model = provider; // TODO remove provider in favor of model
        if (provider) {
            this.renderer.setDataProvider(provider);
    
            // this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
            // this.session.on("changeScrollLeft", this.$onScrollLeftChange);
            
            if (!this.$redraw) this.$redraw = this.redraw.bind(this);
            
            this.provider.on("expand", this.$redraw);
            this.provider.on("collapse", this.$redraw);
            this.provider.on("change", this.$redraw);
    
            // FIXME
            if (!this.provider.selection) {
                this.provider.selection = new Selection(this.provider);
            }
            
            this.selection = this.provider.selection;
            
            this.$onCaretChange = this.onCaretChange.bind(this);
            this.selection.on("changeCaret", this.$onCaretChange);
            this.$onChangeClass = this.$onChangeClass.bind(this);
            this.provider.on("changeClass", this.$onChangeClass);
    
            this.$onSelectionChange = this.onSelectionChange.bind(this);
            this.selection.on("change", this.$onSelectionChange);
            
            
            this.$onScrollTopChange = this.onScrollTopChange.bind(this);
            this.provider.on("changeScrollTop", this.$onScrollTopChange);
    
            this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
            this.provider.on("changeScrollLeft", this.$onScrollLeftChange);
            
            this.$blockScrolling += 1;
            this.onCaretChange();
            this.$blockScrolling -= 1;
    
            this.onScrollTopChange();
            this.onScrollLeftChange();
            this.onSelectionChange();
            this.renderer.updateFull();
        }

        this._emit("changeDataProvider", {
            provider: provider,
            oldProvider: oldProvider
        });
    };
    
    this.redraw = function() {
        this.renderer.updateFull();
    };
    
    this.getLength = function(){
        return 0; // this.renderer.$treeLayer.length;
    };
    
    this.getLine = function(row){
        return {
            length : 0 // this.renderer.$horHeadingLayer.length - 1
        };
    };

    /**
     * Returns the current session being used.
     **/
    this.getDataProvider = function() {
        return this.provider;
    };

    /**
     *
     * Returns the currently highlighted selection.
     * @returns {String} The highlighted selection
     **/
    this.getSelection = function() {
        return this.selection;
    };

    /**
     * {:VirtualRenderer.onResize}
     * @param {Boolean} force If `true`, recomputes the size, even if the height and width haven't changed
     *
     *
     * @related VirtualRenderer.onResize
     **/
    this.resize = function(force) {
        this.renderer.onResize(force);
    };

    /**
     *
     * Brings the current `textInput` into focus.
     **/
    this.focus = function(once) {
        // Safari needs the timeout
        // iOS and Firefox need it called immediately
        // to be on the save side we do both
        var _self = this;
        once || setTimeout(function() {
            _self.textInput.focus();
        });
        this.textInput.focus();
    };

    /**
     * Returns `true` if the current `textInput` is in focus.
     * @return {Boolean}
     **/
    this.isFocused = function() {
        return this.textInput.isFocused();
    };

    /**
     *
     * Blurs the current `textInput`.
     **/
    this.blur = function() {
        this.textInput.blur();
    };

    /**
     * Emitted once the editor comes into focus.
     * @event focus
     *
     *
     **/
    this.onFocus = function() {
        if (this.$isFocused)
            return;
        this.$isFocused = true;
        this.renderer.visualizeFocus();
        this._emit("focus");
    };

    /**
     * Emitted once the editor has been blurred.
     * @event blur
     *
     *
     **/
    this.onBlur = function() {
        if (!this.$isFocused)
            return;
        this.$isFocused = false;
        this.renderer.visualizeBlur();
        this._emit("blur");
    };

    this.onScrollTopChange = function() {
        this.renderer.scrollToY(this.provider.getScrollTop());
    };

    this.onScrollLeftChange = function() {
        this.renderer.scrollToX(this.renderer.getScrollLeft());
    };
    
    this.$onChangeClass = function() {
        this.renderer.updateCaret();
    };

    /**
     * Emitted when the selection changes.
     *
     **/
    this.onCaretChange = function() {
        this.$onChangeClass();

        if (!this.$blockScrolling)
            this.selectionChanged = true;

        this._emit("changeSelection");
    };
    
    this.onSelectionChange = function(e) {
        this.onCaretChange();
    };

    this.execCommand = function(command, args) {
        this.commands.exec(command, this, args);
    };

    this.onTextInput = function(text) {
        this.keyBinding.onTextInput(text);
    };

    this.onCommandKey = function(e, hashId, keyCode) {
        this.keyBinding.onCommandKey(e, hashId, keyCode);
    };
    
    this.insertSting = function(str) {
        if (this.startFilter) 
            return this.startFilter(str);
        
        quickSearch(this, str);    
    };
    
    this.setTheme = function(theme) {
        this.renderer.setTheme(theme);
    };

    /**
     * Returns an object indicating the currently selected rows. The object looks like this:
     *
     * ```json
     * { first: range.start.row, last: range.end.row }
     * ```
     *
     * @returns {Object}
     **/
    this.$getSelectedRows = function() {
        var range = this.getSelectionRange().collapseRows();

        return {
            first: range.start.row,
            last: range.end.row
        };
    };

    /**
     * {:VirtualRenderer.getVisibleNodes}
     * @param {Number} tolerance fraction of the node allowed to be hidden while node still considered visible (default 1/3)
     * @returns {Array}
     * @related VirtualRenderer.getVisibleNodes
     **/
    this.getVisibleNodes = function(tolerance) {
        return this.renderer.getVisibleNodes(tolerance);
    };
    /**
     * Indicates if the node is currently visible on the screen.
     * @param {Object} node The node to check
     * @param {Number} tolerance fraction of the node allowed to be hidden while node still considered visible (default 1/3)
     *
     * @returns {Boolean}
     **/
    this.isNodeVisible = function(node, tolerance) {
        return this.renderer.isNodeVisible(node, tolerance);
    };

    this.$moveByPage = function(dir, select) {
        var renderer = this.renderer;
        var config = this.renderer.layerConfig;
        config.lineHeight = this.provider.rowHeight;
        var rows = dir * Math.floor(config.height / config.lineHeight);

        this.$blockScrolling++;
        this.selection.moveSelection(rows, select);
        this.$blockScrolling--;

        var scrollTop = renderer.scrollTop;

        renderer.scrollBy(0, rows * config.lineHeight);
        if (select != null)
            renderer.scrollCaretIntoView(null, 0.5);

        renderer.animateScrolling(scrollTop);
    };

    /**
     * Selects the text from the current position of the document until where a "page down" finishes.
     **/
    this.selectPageDown = function() {
        this.$moveByPage(1, true);
    };

    /**
     * Selects the text from the current position of the document until where a "page up" finishes.
     **/
    this.selectPageUp = function() {
        this.$moveByPage(-1, true);
    };

    /**
     * Shifts the document to wherever "page down" is, as well as moving the cursor position.
     **/
    this.gotoPageDown = function() {
       this.$moveByPage(1, false);
    };

    /**
     * Shifts the document to wherever "page up" is, as well as moving the cursor position.
     **/
    this.gotoPageUp = function() {
        this.$moveByPage(-1, false);
    };

    /**
     * Scrolls the document to wherever "page down" is, without changing the cursor position.
     **/
    this.scrollPageDown = function() {
        this.$moveByPage(1);
    };

    /**
     * Scrolls the document to wherever "page up" is, without changing the cursor position.
     **/
    this.scrollPageUp = function() {
        this.$moveByPage(-1);
    };

    /**
     * Scrolls to a row. If `center` is `true`, it puts the row in middle of screen (or attempts to).
     * @param {Number} row The row to scroll to
     * @param {Boolean} center If `true`
     * @param {Boolean} animate If `true` animates scrolling
     * @param {Function} callback Function to be called when the animation has finished
     *
     *
     * @related VirtualRenderer.scrollToRow
     **/
    this.scrollToRow = function(row, center, animate, callback) {
        this.renderer.scrollToRow(row, center, animate, callback);
    };

    /**
     * Attempts to center the current selection on the screen.
     **/
    this.centerSelection = function() {
        var range = this.getSelectionRange();
        var pos = {
            row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2),
            column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2)
        };
        this.renderer.alignCaret(pos, 0.5);
    };

    /**
     * Gets the current position of the Caret.
     * @returns {Object} An object that looks something like this:
     *
     * ```json
     * { row: currRow, column: currCol }
     * ```
     *
     * @related Selection.getCursor
     **/
    this.getCursorPosition = function() {
        return this.selection.getCursor();
    };

    /**
     * Returns the screen position of the Caret.
     * @returns {Number}
     **/
    this.getCursorPositionScreen = function() {
        return this.session.documentToScreenPosition(this.getCursorPosition());
    };

    /**
     * {:Selection.getRange}
     * @returns {Range}
     * @related Selection.getRange
     **/
    this.getSelectionRange = function() {
        return this.selection.getRange();
    };


    /**
     * Selects all the text in editor.
     * @related Selection.selectAll
     **/
    this.selectAll = function() {
        this.$blockScrolling += 1;
        this.selection.selectAll();
        this.$blockScrolling -= 1;
    };

    /**
     * {:Selection.clearSelection}
     * @related Selection.clearSelection
     **/
    this.clearSelection = function() {
        this.selection.clearSelection();
    };

    /**
     * Moves the Caret to the specified row and column. Note that this does not de-select the current selection.
     * @param {Number} row The new row number
     * @param {Number} column The new column number
     *
     *
     * @related Selection.moveCaretTo
     **/
    this.moveCaretTo = function(row, column) {
        this.selection.moveCaretTo(row, column);
    };

    /**
     * Moves the Caret to the position indicated by `pos.row` and `pos.column`.
     * @param {Object} pos An object with two properties, row and column
     *
     *
     * @related Selection.moveCaretToPosition
     **/
    this.moveCaretToPosition = function(pos) {
        this.selection.moveCaretToPosition(pos);
    };

    /**
     * Moves the Caret to the specified row number, and also into the indiciated column.
     * @param {Number} rowNumber The row number to go to
     * @param {Number} column A column number to go to
     * @param {Boolean} animate If `true` animates scolling
     *
     **/
    this.gotoRow = function(rowNumber, column, animate) {
        this.selection.clearSelection();
        
        if (column === undefined)
            column = this.selection.getCursor().column;

        this.$blockScrolling += 1;
        this.moveCaretTo(rowNumber - 1, column || 0);
        this.$blockScrolling -= 1;

        if (!this.isRowFullyVisible(rowNumber - 1))
            this.scrollToRow(rowNumber - 1, true, animate);
    };

    /**
     * Moves the Caret to the specified row and column. Note that this does de-select the current selection.
     * @param {Number} row The new row number
     * @param {Number} column The new column number
     *
     *
     * @related Editor.moveCaretTo
     **/
    this.navigateTo = function(row, column) {
        this.clearSelection();
        this.moveCaretTo(row, column);
    };

    /**
     * Moves the Caret up in the document the specified number of times. Note that this does de-select the current selection.
     * @param {Number} times The number of times to change navigation
     *
     *
     **/
    this.navigateUp = function() {
        var node = this.provider.navigate("up");
        node && this.selection.setSelection(node);
        this.$scrollIntoView();
    };

    /**
     * Moves the Caret down in the document the specified number of times. Note that this does de-select the current selection.
     * @param {Number} times The number of times to change navigation
     *
     *
     **/
    this.navigateDown = function() {
        var node = this.provider.navigate("down");
        node && this.selection.setSelection(node);
    };

    /**
     * Moves the Caret left in the document the specified number of times. Note that this does de-select the current selection.
     **/
    this.navigateLevelUp = function(toggleNode) {
        var node = this.selection.getCursor();
        if (!node) {
            // continue
        } else if (toggleNode && this.provider.isOpen(node)) {
            this.provider.close(node);
        } else {
            this.selection.setSelection(node.parent);
        }
    };

    /**
     * Moves the Caret right in the document the specified number of times. Note that this does de-select the current selection.
     **/
    this.navigateLevelDown = function() {
        var node = this.selection.getCursor();
        var hasChildren = this.provider.hasChildren(node);
        if (!hasChildren || this.provider.isOpen(node))
            return this.selection.moveSelection(1);
        
        this.provider.open(node);
    };
    
    this.navigateStart = function() {
        var node = this.getFirstNode();
        this.selection.setSelection(node);
    };
    
    this.navigateEnd = function() {
        var node = this.getLastNode();
        this.selection.setSelection(node);
    };
    this.getFirstNode = function() {
        var index = this.provider.getMinIndex();
        return this.provider.getNodeAtIndex(index);
    };
    this.getLastNode = function() {
        var index = this.provider.getMaxIndex();
        return this.provider.getNodeAtIndex(index);
    };
    
    this.$scrollIntoView = function(node) {
        this.renderer.scrollCaretIntoView();
    };
    
    this.select = function(node) {
        this.selection.setSelection(node);
    };
    
    this.getCopyText = function(node) {
        return "";
    };
    this.onPaste = function(node) {
        return "";
    };

    this.reveal = function(node, animate) {
        var provider = this.provider;
        var parent = node.parent;
        while (parent) {
            if (!provider.isOpen(parent))
                provider.expand(parent);
            parent = parent.parent;
        }
        
        this.select(node);
        var scrollTop = this.renderer.scrollTop;
        this.renderer.scrollCaretIntoView(node, 0.5);
        if (animate !== false)
            this.renderer.animateScrolling(scrollTop);
    };
    
    /**
     * {:UndoManager.undo}
     * @related UndoManager.undo
     **/
    this.undo = function() {
        this.$blockScrolling++;
        this.session.getUndoManager().undo();
        this.$blockScrolling--;
        this.renderer.scrollCaretIntoView(null, 0.5);
    };

    /**
     * {:UndoManager.redo}
     * @related UndoManager.redo
     **/
    this.redo = function() {
        this.$blockScrolling++;
        this.session.getUndoManager().redo();
        this.$blockScrolling--;
        this.renderer.scrollCaretIntoView(null, 0.5);
    };
    
    /**
     * Returns `true` if the editor is set to read-only mode.
     * @returns {Boolean}
     **/
    this.getReadOnly = function() {
        return this.getOption("readOnly");
    };

    /**
     *
     * Cleans up the entire editor.
     **/
    this.destroy = function() {
        this.renderer.destroy();
        this._emit("destroy", this);
    };
    
    this.setHorHeadingVisible = function(value){
        this.renderer.setHorHeadingVisible(value);
    };
    
    this.setVerHeadingVisible = function(value){
        this.renderer.setVerHeadingVisible(value);
    };
    
    this.enable = function() {
        this.$disabled = false;
        this.container.style.pointerEvents = "";
        this.container.style.opacity = "";
    };
    
    this.disable = function() {
        this.$disabled = true;
        this.container.style.pointerEvents = "none";
        this.container.style.opacity = "0.9";
        if (this.isFocused())
            this.blur();
    };

}).call(Tree.prototype);
Exemplo n.º 20
0
(function() {

    oop.implement(this, EventEmitter);
        
    this.$characterSize = {width: 0, height: 0};
    
    this.$testFractionalRect = function() {
        var el = dom.createElement("div");
        this.$setMeasureNodeStyles(el.style);
        el.style.width = "0.2px";
        document.documentElement.appendChild(el);
        var w = el.getBoundingClientRect().width;
        if (w > 0 && w < 1)
            CHAR_COUNT = 50;
        else
            CHAR_COUNT = 100;
        el.parentNode.removeChild(el);
    };
    
    this.$setMeasureNodeStyles = function(style, isRoot) {
        style.width = style.height = "auto";
        style.left = style.top = "0px";
        style.visibility = "hidden";
        style.position = "absolute";
        style.whiteSpace = "pre";

        if (useragent.isIE < 8) {
            style["font-family"] = "inherit";
        } else {
            style.font = "inherit";
        }
        style.overflow = isRoot ? "hidden" : "visible";
    };

    this.checkForSizeChanges = function() {
        var size = this.$measureSizes();
        if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
            this.$measureNode.style.fontWeight = "bold";
            var boldSize = this.$measureSizes();
            this.$measureNode.style.fontWeight = "";
            this.$characterSize = size;
            this.charSizes = Object.create(null);
            this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height;
            this._emit("changeCharacterSize", {data: size});
        }
    };

    this.$pollSizeChanges = function() {
        if (this.$pollSizeChangesTimer)
            return this.$pollSizeChangesTimer;
        var self = this;
        return this.$pollSizeChangesTimer = setInterval(function() {
            self.checkForSizeChanges();
        }, 500);
    };
    
    this.setPolling = function(val) {
        if (val) {
            this.$pollSizeChanges();
        } else if (this.$pollSizeChangesTimer) {
            clearInterval(this.$pollSizeChangesTimer);
            this.$pollSizeChangesTimer = 0;
        }
    };

    this.$measureSizes = function() {
        if (CHAR_COUNT === 50) {
            var rect = null;
            try { 
               rect = this.$measureNode.getBoundingClientRect();
            } catch(e) {
               rect = {width: 0, height:0 };
            };
            var size = {
                height: rect.height,
                width: rect.width / CHAR_COUNT
            };
        } else {
            var size = {
                height: this.$measureNode.clientHeight,
                width: this.$measureNode.clientWidth / CHAR_COUNT
            };
        }
        if (size.width === 0 || size.height === 0)
            return null;
        return size;
    };

    this.$measureCharWidth = function(ch) {
        this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT);
        var rect = this.$main.getBoundingClientRect();
        return rect.width / CHAR_COUNT;
    };
    
    this.getCharacterWidth = function(ch) {
        var w = this.charSizes[ch];
        if (w === undefined) {
            this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width;
        }
        return w;
    };

    this.destroy = function() {
        clearInterval(this.$pollSizeChangesTimer);
        if (this.el && this.el.parentNode)
            this.el.parentNode.removeChild(this.el);
    };

}).call(FontMetrics.prototype);
Exemplo n.º 21
0
(function() {

    oop.implement(this, EventEmitter);

    this.exec = function(command, editor, args) {
        if (Array.isArray(command)) {
            for (var i = command.length; i--; ) {
                if (this.exec(command[i], editor, args)) return true;
            }
            return false;
        }
        
        if (typeof command === "string")
            command = this.commands[command];

        if (!command)
            return false;

        if (editor && editor.$readOnly && !command.readOnly)
            return false;

        var e = {editor: editor, command: command, args: args};
        e.returnValue = this._emit("exec", e);
        this._signal("afterExec", e);

        return e.returnValue === false ? false : true;
    };

    this.toggleRecording = function(editor) {
        if (this.$inReplay)
            return;

        editor && editor._emit("changeStatus");
        if (this.recording) {
            this.macro.pop();
            this.removeEventListener("exec", this.$addCommandToMacro);

            if (!this.macro.length)
                this.macro = this.oldMacro;

            return this.recording = false;
        }
        if (!this.$addCommandToMacro) {
            this.$addCommandToMacro = function(e) {
                this.macro.push([e.command, e.args]);
            }.bind(this);
        }

        this.oldMacro = this.macro;
        this.macro = [];
        this.on("exec", this.$addCommandToMacro);
        return this.recording = true;
    };

    this.replay = function(editor) {
        if (this.$inReplay || !this.macro)
            return;

        if (this.recording)
            return this.toggleRecording(editor);

        try {
            this.$inReplay = true;
            this.macro.forEach(function(x) {
                if (typeof x == "string")
                    this.exec(x, editor);
                else
                    this.exec(x[0], editor, x[1]);
            }, this);
        } finally {
            this.$inReplay = false;
        }
    };

    this.trimMacro = function(m) {
        return m.map(function(x){
            if (typeof x[0] != "string")
                x[0] = x[0].name;
            if (!x[1])
                x = x[0];
            return x;
        });
    };

}).call(CommandManager.prototype);
Exemplo n.º 22
0
    exports.AutoComplete = function (editor, script, compilationService, typeScriptService) {

        var self = this;
        this.ts = typeScriptService;

        oop.implement(self, EventEmitter);
        this.handler = new HashHandler();
        this.view = new AutoCompleteView(editor, self);
        this.scriptName = script;
        this._active = false;
        this.inputText = ''; //TODO imporve name

        this.isActive = function () {
            return self._active;
        };

        this.setScriptName = function (name) {
            self.scriptName = name;
        };

        this.show = function () {
            self.listElement = self.view.listElement;
            editor.container.appendChild(self.view.wrap);
            self.listElement.innerHTML = '';
        };

        this.hide = function () {
            self.view.hide();
        }

        this.compilation = function (cursor) {
            var compilationInfo = compilationService.getCursorCompilation(self.scriptName, cursor);
            if (typeof compilationInfo === "undefined")
                return;

            var text = compilationService.matchText;
            var coords = editor.renderer.textToScreenCoordinates(cursor.row, cursor.column - text.length);

            self.view.setPosition(coords);
            self.inputText = text;

            var compilations = compilationInfo.entries;


            if (!compilationService.isMemberCompletion(self.scriptName, cursor)) {
                var snippets = snippetManager.files["ace/mode/typescript"].snippets;
                for (var i = 0; i < snippets.length; i++) {
                    compilations.push({
                        kind: "snippet",
                        kindModifiers: "",
                        name: snippets[i].name,
                        sortText: "0"
                    });
                }
            }

            if (self.inputText.length > 0) {
                compilations = compilationInfo.entries.filter(function (elm) {
                    return elm.name.toLowerCase().indexOf(self.inputText.toLowerCase()) == 0;
                });
            }

            var matchFunc = function (elm) {
                return elm.name.indexOf(self.inputText) == 0 ? 1 : 0;
            };

            var matchCompare = function (a, b) {
                return matchFunc(b) - matchFunc(a);
            };

            var textCompare = function (a, b) {
                if (a.name == b.name) {
                    return 0;
                } else {
                    return (a.name > b.name) ? 1 : -1;
                }
            };
            var compare = function (a, b) {
                var ret = matchCompare(a, b);
                return (ret != 0) ? ret : textCompare(a, b);
            };

            compilations = compilations.sort(compare);

            self.showCompilation(compilations);

            return compilations.length;
        };

        this.refreshCompilation = function (e) {
            var cursor = editor.getCursorPosition();
            if (e.action == "insert") {
                cursor.column += 1;
            } else if (e.action == "remove") {
                if (e.lines[0] == '\n') {
                    self.deactivate();
                    return;
                }
            }

            self.compilation(cursor);
        };

        this.escapeHTML = function (html) {
            return html.replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        }

        this.showCompilation = function (infos) {
            if (infos.length > 0) {
                var cursor = editor.getCursorPosition();

                var count = 0;
                self.view.show();
                var html = '';
                for (var n in infos) {
                    var info = infos[n];
                    var name = '<span class="label-name">' + info.name + '</span>';

                    var description = "";
                    var documentation = "";
                    if (count < 50 && info.kind != "snippet") { // limit the amount of details to prevent lag
                        var details = compilationService.getCompilationDetails(self.scriptName, cursor, info.name);
                        if (typeof details !== "undefined") {
                            details.displayParts.forEach(function (el) { description += el.text; });

                            if (details.documentation)
                                details.documentation.forEach(function (el) { documentation += el.text; });
                            count++;
                        }
                    }

                    var type = '<span class="label-type">' + self.escapeHTML(description) + '</span>';

                    var modifiers = info.kindModifiers.split(',');
                    for (var i = 0; i < modifiers.length; i++) {
                        modifiers[i] = "label-modifier-" + modifiers[i];
                    }
                    //var accessors = modifiers.join(" ");
                    var kindVal = (info.kind + "").replace(" ", "-");
                    var kind = '<span class="label-kind label-kind-' + kindVal + '">' + '</span>';
                    var overlay = "";
                    for (var i = 0; i < modifiers.length; i++) {
                        overlay += '<span class="label-overlay ' + modifiers[i] + '"></span>';
                    }

                    documentation = documentation.replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

                    html += '<li class="label-autocomplete" data-name="' + info.name + '" data-kind="' + info.kind + '" data-doc="' + documentation + '">' + kind + name + type + overlay + '</li>';
                }
                self.listElement.innerHTML = html;
                self.view.ensureFocus();
            } else {
                self.view.hide();
            }
        };

        this.active = function () {
            self.show();
            var count = self.compilation(editor.getCursorPosition());
            if (!(count > 0)) {
                self.hide();
                return;
            }
            editor.keyBinding.addKeyboardHandler(self.handler);
        };

        this.deactivate = function () {
            editor.keyBinding.removeKeyboardHandler(self.handler);
        };

        this.handler.attach = function () {
            editor.addEventListener("change", self.refreshCompilation);
            self._emit("attach", { sender: self });
            self._active = true;
        };

        this.handler.detach = function () {
            editor.removeEventListener("change", self.refreshCompilation);
            self.view.hide();
            self._emit("detach", { sender: self });
            self._active = false;
        };

        this.handler.handleKeyboard = function (data, hashId, key, keyCode) {
            if (hashId == -1) {

                if (" -=,[]_/()!';:<>".indexOf(key) != -1) { //TODO
                    self.deactivate();
                }
                return null;
            }

            var command = self.handler.findKeyCommand(hashId, key);

            if (!command) {

                var defaultCommand = editor.commands.findKeyCommand(hashId, key);
                if (defaultCommand) {
                    if (defaultCommand.name == "backspace") {
                        return null;
                    }
                    self.deactivate();
                }
                return null;
            }

            if (typeof command != "string") {
                var args = command.args;
                command = command.command;
            }

            if (typeof command == "string") {
                command = this.commands[command];
            }

            return { command: command, args: args };
        };


        exports.Keybinding = {
            "Up|Ctrl-p": "focusprev",
            "Down|Ctrl-n": "focusnext",
            "PageUp": "focusprevpage",
            "PageDown": "focusnextpage",
            "esc|Ctrl-g": "cancel",
            "Return|Tab": "insertComplete"
        };

        this.handler.bindKeys(exports.Keybinding);

        this.handler.addCommands({
            focusnext: function (editor) {
                self.view.focusNext();
            },
            focusprev: function (editor) {
                self.view.focusPrev();
            },
            focusnextpage: function (editor) {
                for (var i = 0; i < 12; i++)
                    self.view.focusNext();
            },
            focusprevpage: function (editor) {
                for (var i = 0; i < 12; i++)
                    self.view.focusPrev();
            },
            cancel: function (editor) {
                self.deactivate();
            },
            insertComplete: function (editor) {
                editor.removeEventListener("change", self.refreshCompilation);
                var curr = self.view.current();

                for (var i = 0; i < self.inputText.length; i++) {
                    editor.remove("left");
                }

                if (curr) {
                    editor.insert($(curr).data("name"));

                    if ($(curr).data("kind") == "snippet") {
                        snippetManager.expandWithTab(editor);
                    }
                }
                self.deactivate();

            }
        });
    };
Exemplo n.º 23
0
(function() {
    this.rowHeight = undefined;
    this.rowHeightInner = undefined;
    this.$indentSize = 10;
    
    oop.implement(this, Scrollable);

    this.$sortNodes = true;
    
    this.setRoot = function(root){
        if (Array.isArray(root))
            root = {items: root};
        
        this.root = root || {};
        
        if (this.root.$depth == undefined) {
            this.root.$depth = -1;
        }
        if (this.root.$depth < 0) {
            this.visibleItems = [];
            this.open(this.root);
            this.visibleItems.unshift();
        } else {
            this.visibleItems = [this.root];
        }
        this.$selectedNode = this.root;
        
        this._signal("setRoot");
        this._signal("change");
    };
    
    this.open = 
    this.expand = function(node, deep, silent, justLoaded) {
        if (typeof deep != "number")
            deep = deep ? 100 : 0;
        if (!node)
            return;
        
        var items = this.visibleItems;
        if (this.isOpen(node) && (node !== this.root || items.length))
            return;
        var ch = this.getChildren(node);
        if (this.loadChildren && this.shouldLoadChildren(node, ch)) {
            var timer = setTimeout(function() {
                node.status = "loading";
                this._signal("change", node);
            }.bind(this), 100);
            this.loadChildren(node, function(err, ch) {
                clearTimeout(timer);
                this.collapse(node, null, true);
                node.status = "loaded";
                if (!err)
                    this.expand(node, null, false, true);
            }.bind(this));
            this.setOpen(node, true);
            return;
        }
        this.setOpen(node, true);
        var i = items.indexOf(node);
        if (!ch) {
            this._signal("change", node);
            return;
        }
        if (i === -1 && items.length || this.forceEmpty)
            return;
        ch = [i + 1, 0].concat(ch);
        items.splice.apply(items, ch);
        
        for (var j = 2; j < ch.length; j++) {
            var childNode = ch[j];
            if (this.isOpen(childNode)) {
                this.setOpen(childNode, false);
                this.open(childNode, deep - 1);
            } else if (deep > 0) {
                this.open(childNode, deep - 1);
            }
        }
        
        if (justLoaded)
            node.justLoaded = true;
        
        this.rows = items.length;
        silent || this._signal("expand", node);
    };
    
    this.close =
    this.collapse = function(node, deep, silent) {
        if (typeof deep != "number")
            deep = deep ? 1000 : 0;
        var items = this.visibleItems;
        var isRoot = node === this.root;
        if (isRoot) {
            this.setOpen(node, false);
            if (deep) {
                for (var i = 0; i < items.length; i++) {
                    var ch = items[i];
                    if (!ch.isRoot)
                    if (this.isOpen(ch) && ch.$depth - node.$depth < deep) {
                        this.setOpen(ch, false);
                        silent || this._signal("collapse", ch);
                    }
                }
            }
            items.length = 0;
            if (isRoot)
                this.open(this.root, 0, silent);
            return;
        }

        if (!node || !this.isOpen(node))
            return;
        var i = items.indexOf(node);
        if (i === -1)
            return;
        var thisDepth = node.$depth;
        var deletecount = 0;
        for (var t = i + 1; t < items.length; t++) {
            if (items[t].$depth > thisDepth)
                deletecount++;
            else
                break;
        }
        
        if (deep) {
            for (var j = 0; j < deletecount; j++) {
                var ch = items[j + i];
                if (this.isOpen(ch) && ch.$depth - node.$depth < deep) {
                    this.setOpen(ch, false);
                    silent || this._signal("collapse", ch);
                }
            }
        }
        items.splice(i + 1, deletecount);
        this.setOpen(node, false);
        silent || this._signal("collapse", node);
        
        if (isRoot)
            this.open(this.root, 0, silent);
    };
    
    this.toggleNode = function(node, deep, silent) {
        if (node && this.isOpen(node))
            this.close(node, deep, silent);
        else
            this.open(node, deep, silent);
    };
        
    this.sort = function(children, compare) {
        if (!compare) {
            compare = alphanumCompare;
        }
        return children.sort(function(a, b) {
            var aChildren = a.children || a.map;
            var bChildren = b.children || b.map;
            if (aChildren && !bChildren) return -1;
            if (!aChildren && bChildren) return 1;
            
            return compare(a.label || "", b.label || "");
        });
    };
    
    this.setFilter = function(fn) {
        this.$filterFn = fn;
        this.setRoot(this.root);
    };
    this.getChildren = function(node) {
        var children = node.children;
        if (!children) {
            if (node.status === "pending")
                return;
            if (node.map) {
                children = Object.keys(node.map).map(function(key) {
                    var ch = node.map[key];
                    ch.parent = node;
                    return ch;
                });
            } else if (node.items) {
                children = node.items;
            }
            if (children) {
                node.children = children;
            }
        }
        var ch = children && children[0] && children[0];
        if (ch) {
            var d = (node.$depth + 1) || 0;
            children.forEach(function(n) {
                 n.$depth = d;
                 n.parent = node;
            });
        }
        
        if (this.$filterFn) {
            children = children && children.filter(this.$filterFn);
        }

        if (this.$sortNodes && !node.$sorted) {
            children && this.sort(children);
        }
        return children;
    };
    this.loadChildren = null;
    this.shouldLoadChildren = function(node, ch) {
        return node.status === "pending";
    };
    
    this.hasChildren = function(node) {
        if (node.children)
            return node.children.length !== 0;
        return node.map
            || node.items && node.items.length;
    };
    
    this.findNodeByPath = function() {
    
    };
    
    this.getSibling = function(node, dir) {
        if (!dir) dir = 1;
        var parent = node.parent;
        var ch = this.getChildren(parent);
        var pos = ch.indexOf(node);
        return ch[pos + dir];
    };
    
    this.getNodeAtIndex = function(i) {
        return this.visibleItems[i];
    };
    
    this.getIndexForNode = function(node) {
        return this.visibleItems.indexOf(node);
    };
    
    this.getMinIndex = function() {return 0};
    this.getMaxIndex = function() {return this.visibleItems.length - 1};
    
    this.setOpen = function(node, val) {
        return node.isOpen = val;
    };
    this.isOpen = function(node) {
        return node.isOpen;
    };
    this.isVisible = function(node) {
        return this.visibleItems.indexOf(node) !== -1;
    };
    this.isSelected = function(node) {
        return node.isSelected;
    };
    this.setSelected = function(node, val) {
        return node.isSelected = !!val;
    };
    this.isSelectable = function(node) {
        return !node || !(node.noSelect || node.$depth < 0);
    };
    
    this.isAncestor = function(node, child) {
        do {
            if (child == node)
                return true;
        } while (child = child.parent);
        return false;
    };
    
    this.setAttribute = function(node, name, value) {
        node[name] = value;
        this._signal("change", node);
    };
    
    this.getDataRange = function(rows, columns, callback) {
        var view = this.visibleItems.slice(rows.start, rows.start + rows.length);        
        callback(null, view, false);
        return view;
    };
    
    this.getRange = function(top, bottom) {
        var start = Math.floor(top / this.rowHeight);
        var end = Math.ceil(bottom / this.rowHeight) + 1;
        var range = this.visibleItems.slice(start, end);
        range.count = start;
        range.size = this.rowHeight * range.count;
        return range;
    };
    this.getTotalHeight = function(top, bottom) {
        return this.rowHeight * this.visibleItems.length;
    };
    
    this.getNodePosition = function(node) {
        var i = this.visibleItems.indexOf(node);
        if (i == -1 && node && node.parent) {
            i = this.visibleItems.indexOf(node.parent);
        }
        var top = i * this.rowHeight;
        var height = this.rowHeight;
        return {top: top, height: height};
    };
    
    this.findItemAtOffset = function(offset, clip) {
        var index = Math.floor(offset / this.rowHeight);
        if (clip) 
            index = Math.min(Math.max(0, index), this.visibleItems.length - 1);
        return this.visibleItems[index];
    };
    
    this.getIconHTML = function(node) {
        return "";
    };
    this.getClassName = function(node) {
        return (node.className || "") + (node.status == "loading" ? " loading" : "");
    };
    this.setClass = function(node, name, include) {
        node.className = node.className || "";
        dom.setCssClass(node, name, include);
        this._signal("changeClass");
    };
    this.redrawNode = null;
    this.getCaptionHTML = function(node) {
        return escapeHTML(node.label || node.name || (typeof node == "string" ? node : ""));
    };
    this.getContentHTML = null;
    this.getEmptyMessage = function() { return this.emptyMessage || "" };
    this.getText = function(node) {
        return node.label || node.name || "";
    };
    this.getRowIndent = function(node){
        return node.$depth;
    };
    this.hideAllNodes = function(){
        this.visibleItems = [];
        this.forceEmpty   = true;
        this.setRoot(this.root);
    };
    this.showAllNodes = function(){
        this.forceEmpty   = false;
        this.setRoot(this.root);
    };
    
}).call(DataProvider.prototype);
Exemplo n.º 24
0
  (function() {

    oop.implement(this, EventEmitter);

    /**
     * Binary searches for the smallest index at which `comment` could
     * be inserted into `list` and still maintain the ordering.
     *
     * Note that this function was adapted from `_.sortedIndex` in order
     * to support a comparator function.
     *
     * @param {Comment[]} list The list of comments
     * @param {Comment} comment The comment
     *
     * @returns The smallest index such that the comment could be
     *    inserted at and still maintain the list ordering
     *
     * @memberof List
     * @method sortedIndex
     */
    function sortedIndex(list, comment) {
      var low = 0
        , high = list.length;

      while (low < high) {
        var mid = (low + high) >>> 1
          , midComment = list[mid];

        if (comment.range.compareRange(midComment.range) < 0) {
          low = mid + 1;
        } else {
          high = mid;
        }
      }

      return low;
    };

    /**
     * Adds `comment` to the list while maintaining its order.
     *
     * @param {Comment} comment The comment to add
     *
     * @memberof List
     * @instance
     * @method addComment
     */
    this.addComment = function(comment) {
      var index = sortedIndex(this.list, comment);

      this.list.splice(index, 0, comment);
      comment.index = index;

      for (var i = index + 1; i < this.list.length; i++) {
        var c = this.list[i];
        c.index += 1;
      }

      this._signal('addComment', index);
    };

    /**
     * Removes `comment` from the list while maintaining its order.
     *
     * @param {Comment} comment The comment to remove
     *
     * @memberof List
     * @instance
     * @method removeComment
     */
    this.removeComment = function(comment) {
      var index = sortedIndex(this.list, comment);

      while (comment !== this.list[index]) {
        index++;
      }

      this.list.splice(index, 1);
      comment.index = null;

      for (var i = index; i < this.list.length; i++) {
        var c = this.list[i];
        c.index -= 1;
      }

      this._signal('removeComment', index);
    };

  }).call(List.prototype);