Merge branch 'master' into vice

This commit is contained in:
Irakli Gozalishvili 2011-01-26 00:35:25 +01:00
commit 7426e54448
33 changed files with 9182 additions and 335 deletions

View file

@ -12,6 +12,20 @@
overflow-y: hidden;
}
.ace_content {
position: absolute;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
.ace_composition {
position: absolute;
background: #555;
color: #DDD;
z-index: 4;
}
.ace_gutter {
position: absolute;
overflow-x: hidden;
@ -61,8 +75,14 @@
color: black;
}
.ace_cjk {
display: inline-block;
text-align: center;
}
.ace_cursor-layer {
cursor: text;
pointer-events: none;
}
.ace_cursor {

View file

@ -52,16 +52,14 @@ var EditSession = function(text, mode) {
this.selection = new Selection(this);
this.$breakpoints = [];
this.listeners = [];
if (mode) {
this.setMode(mode);
}
if (text instanceof Document) {
this.setDocument(text)
} else {
this.setDocument(new Document(text));
}
if (mode)
this.setMode(mode);
};
@ -198,6 +196,41 @@ var EditSession = function(text, mode) {
this._dispatchEvent("changeBreakpoint", {});
};
this.getBreakpoints = function() {
return this.$breakpoints;
};
/**
* Error:
* {
* row: 12,
* column: 2, //can be undefined
* text: "Missing argument",
* type: "error" // or "warning" or "info"
* }
*/
this.setAnnotations = function(annotations) {
this.$annotations = [];
for (var i=0; i<annotations.length; i++) {
var annotation = annotations[i];
var row = annotation.row;
if (this.$annotations[row])
this.$annotations[row].push(annotation);
else
this.$annotations[row] = [annotation];
}
this._dispatchEvent("changeAnnotation", {});
};
this.getAnnotations = function() {
return this.$annotations;
};
this.clearAnnotations = function() {
this.$annotations = [];
this._dispatchEvent("changeAnnotation", {});
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r?\n)/m);
if (match) {
@ -208,8 +241,7 @@ var EditSession = function(text, mode) {
};
this.tokenRe = /^[\w\d]+/g;
this.nonTokenRe = /^[^\w\d]+/g;
this.nonTokenRe = /^(?:[^\w\d|[\u3040-\u309F]|[\u30A0-\u30FF]|[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF])+/g
this.getWordRange = function(row, column) {
var line = this.getLine(row);
@ -253,6 +285,12 @@ var EditSession = function(text, mode) {
this.setMode = function(mode) {
if (this.$mode === mode) return;
if (this.$worker)
this.$worker.terminate();
if (window.Worker)
this.$worker = mode.createWorker(this);
this.$mode = mode;
this._dispatchEvent("changeMode");
};
@ -492,9 +530,9 @@ var EditSession = function(text, mode) {
var lastDelta = deltas[deltas.length-1];
this.selection.clearSelection();
if (firstDelta.action == "insertText" || firstDelta.action == "insertLines")
if (firstDelta.action == "insertText" || firstDelta.action == "insertLines")
this.selection.moveCursorToPosition(firstDelta.range.start);
if (firstDelta.action == "removeText" || firstDelta.action == "removeLines")
if (firstDelta.action == "removeText" || firstDelta.action == "removeLines")
this.selection.setSelectionRange(Range.fromPoints(firstDelta.range.start, lastDelta.range.end));
},
@ -511,9 +549,9 @@ var EditSession = function(text, mode) {
var lastDelta = deltas[deltas.length-1];
this.selection.clearSelection();
if (firstDelta.action == "insertText" || firstDelta.action == "insertLines")
if (firstDelta.action == "insertText" || firstDelta.action == "insertLines")
this.selection.setSelectionRange(Range.fromPoints(firstDelta.range.start, lastDelta.range.end));
if (firstDelta.action == "removeText" || firstDelta.action == "removeLines")
if (firstDelta.action == "removeText" || firstDelta.action == "removeLines")
this.selection.moveCursorToPosition(firstDelta.range.start);
},
@ -594,19 +632,32 @@ var EditSession = function(text, mode) {
var screenColumn = 0;
var remaining = docColumn;
var line = this.getLine(row).split("\t");
for (var i=0; i<line.length; i++) {
var len = line[i].length;
if (remaining > len) {
remaining -= (len + 1);
screenColumn += len + tabSize;
}
else {
screenColumn += remaining;
break;
}
}
var line = this.getLine(row);
for (var i=0; i<line.length; i++) {
var c = line.charCodeAt(i);
if (remaining > 0) {
remaining -= 1;
// tab
if (c == 9) {
screenColumn += tabSize;
}
// CJK characters
else if (
c >= 0x3040 && c <= 0x309F || // Hiragana
c >= 0x30A0 && c <= 0x30FF || // Katakana
c >= 0x4E00 && c <= 0x9FFF || // Single CJK ideographs
c >= 0xF900 && c <= 0xFAFF ||
c >= 0x3400 && c <= 0x4DBF
) {
screenColumn += 2;
} else {
screenColumn += 1;
}
} else {
break;
}
}
return screenColumn;
};
@ -616,23 +667,44 @@ var EditSession = function(text, mode) {
var docColumn = 0;
var remaining = screenColumn;
var line = this.getLine(row).split("\t");
for (var i=0; i<line.length; i++) {
var len = line[i].length;
if (remaining >= len + tabSize) {
remaining -= (len + tabSize);
docColumn += (len + 1);
}
else if (remaining > len){
docColumn += len;
break;
}
else {
docColumn += remaining;
break;
}
}
var line = this.getLine(row);
for(var i=0; i<line.length; i++) {
var c = line.charCodeAt(i);
if (remaining > 0) {
docColumn += 1;
// tab
if (c == 9) {
if (remaining >= tabSize) {
remaining -= tabSize;
} else {
remaining = 0;
docColumn -= 1;
}
}
// CJK characters
else if (
c >= 0x3040 && c <= 0x309F || // Hiragana
c >= 0x30A0 && c <= 0x30FF || // Katakana
c >= 0x4E00 && c <= 0x9FFF || // Single CJK ideographs
c >= 0xF900 && c <= 0xFAFF ||
c >= 0x3400 && c <= 0x4DBF
) {
if (remaining >= 2) {
remaining -= 2;
} else {
remaining = 0;
docColumn -= 1;
}
} else {
remaining -= 1;
}
} else {
break;
}
}
return docColumn;
};

View file

@ -57,7 +57,7 @@ var Editor =function(renderer, session) {
this.keyBinding = new KeyBinding(this);
var self = this;
event.addListener(container, "mousedown", function(e) {
setTimeout(function() {self.focus();});
self.focus();
return event.preventDefault(e);
});
event.addListener(container, "selectstart", function(e) {
@ -122,10 +122,12 @@ var Editor =function(renderer, session) {
if (this.session == session) return;
if (this.session) {
var oldSession = this.session;
this.session.removeEventListener("change", this.$onDocumentChange);
this.session.removeEventListener("changeMode", this.$onDocumentModeChange);
this.session.removeEventListener("changeTabSize", this.$onDocumentChangeTabSize);
this.session.removeEventListener("changeBreakpoint", this.$onDocumentChangeBreakpoint);
this.session.removeEventListener("changeAnnotation", this.$onDocumentChangeAnnotation);
var selection = this.session.getSelection();
selection.removeEventListener("changeCursor", this.$onCursorChange);
@ -148,6 +150,9 @@ var Editor =function(renderer, session) {
this.$onDocumentChangeBreakpoint = this.onDocumentChangeBreakpoint.bind(this);
this.session.addEventListener("changeBreakpoint", this.$onDocumentChangeBreakpoint);
this.$onDocumentChangeAnnotation = this.onDocumentChangeAnnotation.bind(this);
this.session.addEventListener("changeAnnotation", this.$onDocumentChangeAnnotation);
this.selection = session.getSelection();
this.$desiredColumn = 0;
@ -165,8 +170,14 @@ var Editor =function(renderer, session) {
this.onCursorChange();
this.onSelectionChange();
this.onDocumentChangeBreakpoint();
this.onDocumentChangeAnnotation();
this.renderer.scrollToRow(session.getScrollTopRow());
this.renderer.updateFull();
this._dispatchEvent("changeSession", {
session: session,
oldSession: oldSession
});
};
this.getSession = function() {
@ -289,6 +300,10 @@ var Editor =function(renderer, session) {
this.renderer.setBreakpoints(this.session.getBreakpoints());
};
this.onDocumentChangeAnnotation = function() {
this.renderer.setAnnotations(this.session.getAnnotations());
};
this.onDocumentModeChange = function() {
var mode = this.session.getMode();
if (this.mode == mode)

View file

@ -43,11 +43,34 @@ var TextInput = function(parentNode, host) {
var text = document.createElement("textarea");
var style = text.style;
style.position = "absolute";
style.position = "fixed";
style.left = "-10000px";
style.top = "-10000px";
parentNode.appendChild(text);
// move text input over the cursor
// this is required for iOS and IME
style.left = "0px";
style.top = "0px";
style.zIndex = -1;
style.opacity = 0;
style.width = "10px";
style.height = "30px";
var changeCursor = function() {
var cursor = host.getCursorPosition();
var pos = host.renderer.textToScreenCoordinates(cursor.row, cursor.column);
var epos = parentNode.getBoundingClientRect();
style.left = (pos.pageX - epos.left - 6) + "px";
style.top = (pos.pageY - epos.top + 52) + "px";
};
host.addEventListener("changeSession", function(e) {
if (e.oldSession)
e.oldSession.getSelection().removeEventListener("changeCursor", changeCursor);
e.session.getSelection().addEventListener("changeCursor", changeCursor);
});
var PLACEHOLDER = String.fromCharCode(0);
sendText();

View file

@ -45,6 +45,7 @@ var Gutter = function(parentEl) {
parentEl.appendChild(this.element);
this.$breakpoints = [];
this.$annotations = [];
this.$decorations = [];
};
@ -57,22 +58,49 @@ var Gutter = function(parentEl) {
}
this.removeGutterDecoration = function(row, className){
this.$decorations[row] =
this.$decorations[row].replace(" ace_" + className, "");
}
this.$decorations[row] = this.$decorations[row].replace(" ace_" + className, "");
};
this.setBreakpoints = function(rows) {
this.$breakpoints = rows.concat();
};
this.setAnnotations = function(annotations) {
// iterate over sparse array
this.$annotations = [];
for (var row in annotations) {
var rowInfo = this.$annotations[row] = {
text: []
};
var rowAnnotations = annotations[row];
for (var i=0; i<rowAnnotations.length; i++) {
var annotation = rowAnnotations[i];
rowInfo.text.push(annotation.text.replace(/"/g, "&quot;").replace(/'/g, "&rsquo;").replace(/</, "&lt;"));
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.update = function(config) {
this.$config = config;
var html = [];
for ( var i = config.firstRow; i <= config.lastRow; i++) {
var annotation = this.$annotations[i] || {
className: "",
text: []
};
html.push("<div class='ace_gutter-cell",
this.$decorations[i] || "",
this.$breakpoints[i] ? " ace_breakpoint" : "",
this.$breakpoints[i] ? " ace_breakpoint " : " ",
annotation.className,
"' title='", annotation.text.join("\n"),
"' style='height:", config.lineHeight, "px;'>", (i+1), "</div>");
html.push("</div>");
}

View file

@ -248,19 +248,26 @@ var Text = function(parentEl) {
};
this.$renderLine = function(stringBuilder, row, tokens) {
// if (this.showInvisibles) {
// var self = this;
// var spaceRe = /[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]+/g;
// var spaceReplace = function(space) {
// var space = new Array(space.length+1).join(self.SPACE_CHAR);
// return "<span class='ace_invisible'>" + space + "</span>";
// };
// }
// else {
if (this.showInvisibles) {
var self = this;
var spaceRe = /( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])/g;
var spaceReplace = function(space) {
if (space.charCodeAt(0) == 32)
return new Array(space.length+1).join("&nbsp;");
else {
var space = new Array(space.length+1).join(self.SPACE_CHAR);
return "<span class='ace_invisible'>" + space + "</span>";
}
};
}
else {
var spaceRe = /[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/g;
var spaceReplace = "&nbsp;";
// }
}
var characterWidth = this.config.characterWidth;
for ( var i = 0; i < tokens.length; i++) {
var token = tokens[i];
@ -268,8 +275,11 @@ var Text = function(parentEl) {
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(spaceRe, spaceReplace)
.replace(/\t/g, this.$tabString);
.replace(/\t/g, this.$tabString)
.replace(/[\u3040-\u309F]|[\u30A0-\u30FF]|[\u4E00-\u9FFF\uF900-\uFAFF\u3400-\u4DBF]/g, function(c) {
return "<span class='ace_cjk' style='width:" + (characterWidth * 2) + "px'>" + c + "</span>"
});
if (!this.$textToken[token.type]) {
var classes = "ace_" + token.type.replace(/\./g, " ace_");
stringBuilder.push("<span class='", classes, "'>", output, "</span>");

View file

@ -44,14 +44,14 @@ var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightR
var CssHighlightRules = function() {
var properties = lang.arrayToMap(
("azimuth|background-attachment|background-color|background-image|" +
("-moz-box-sizing|-webkit-box-sizing|azimuth|background-attachment|background-color|background-image|" +
"background-position|background-repeat|background|border-bottom-color|" +
"border-bottom-style|border-bottom-width|border-bottom|border-collapse|" +
"border-color|border-left-color|border-left-style|border-left-width|" +
"border-left|border-right-color|border-right-style|border-right-width|" +
"border-right|border-spacing|border-style|border-top-color|" +
"border-top-style|border-top-width|border-top|border-width|border|" +
"bottom|caption-side|clear|clip|color|content|counter-increment|" +
"bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" +
"counter-reset|cue-after|cue-before|cue|cursor|direction|display|" +
"elevation|empty-cells|float|font-family|font-size-adjust|font-size|" +
"font-stretch|font-style|font-variant|font-weight|font|height|left|" +
@ -76,8 +76,8 @@ var CssHighlightRules = function() {
var constants = lang.arrayToMap(
("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" +
"block|bold|bolder|both|bottom|break-all|break-word|capitalize|center|" +
"char|circle|cjk-ideographic|col-resize|collapse|crosshair|dashed|" +
"block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" +
"char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" +
"decimal-leading-zero|decimal|default|disabled|disc|" +
"distribute-all-lines|distribute-letter|distribute-space|" +
"distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" +

View file

@ -43,6 +43,7 @@ var Tokenizer = require("ace/tokenizer").Tokenizer;
var JavaScriptHighlightRules = require("ace/mode/javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = require("ace/mode/matching_brace_outdent").MatchingBraceOutdent;
var Range = require("ace/range").Range;
var WorkerClient = require("ace/worker/worker_client").WorkerClient;
var Mode = function() {
this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules());
@ -120,6 +121,47 @@ oop.inherits(Mode, TextMode);
this.autoOutdent = function(state, doc, row) {
return this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var doc = session.getDocument();
var worker = new WorkerClient("../..", ["ace", "pilot"], "ace/mode/javascript_worker", "JavaScriptWorker");
worker.call("setValue", [doc.getValue()]);
doc.on("change", function(e) {
e.range = {
start: e.data.range.start,
end: e.data.range.end
};
worker.emit("change", e);
});
worker.on("jslint", function(results) {
var errors = [];
for (var i=0; i<results.data.length; i++) {
var error = results.data[i];
if (error)
errors.push({
row: error.line-1,
column: error.character-1,
text: error.reason,
type: "warning",
lint: error
})
}
session.setAnnotations(errors)
});
worker.on("narcissus", function(e) {
session.setAnnotations([e.data]);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
}).call(Mode.prototype);

View file

@ -0,0 +1,47 @@
define(function(require, exports, module) {
var oop = require("pilot/oop");
var Mirror = require("ace/worker/mirror").Mirror;
var lint = require("ace/worker/jslint").JSLINT;
var JavaScriptWorker = exports.JavaScriptWorker = function(sender) {
Mirror.call(this, sender);
this.setTimeout(500);
};
oop.inherits(JavaScriptWorker, Mirror);
(function() {
this.onUpdate = function() {
var value = this.doc.getValue();
var start = new Date();
var parser = require("ace/narcissus/jsparse");
try {
parser.parse(value);
} catch(e) {
console.log("narcissus")
console.log(e);
sender.emit("narcissus", {
row: e.lineno-1,
column: null, // TODO convert e.cursor
text: e.message,
type: "error"
});
return;
} finally {
console.log("parse time: " + (new Date() - start));
}
var start = new Date();
console.log("jslint")
lint(value, {undef: false, onevar: false, passfail: false});
this.sender.emit("jslint", lint.errors);
console.log("lint time: " + (new Date() - start));
}
}).call(JavaScriptWorker.prototype);
});

View file

@ -73,6 +73,10 @@ var Mode = function() {
return "";
};
this.createWorker = function(session) {
return null;
};
}).call(Mode.prototype);

375
lib/ace/narcissus/jsdefs.js Normal file
View file

@ -0,0 +1,375 @@
/* vim: set sw=4 ts=4 et tw=78: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Narcissus JavaScript engine.
*
* The Initial Developer of the Original Code is
* Brendan Eich <brendan@mozilla.org>.
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Tom Austin <taustin@ucsc.edu>
* Brendan Eich <brendan@mozilla.org>
* Shu-Yu Guo <shu@rfrn.org>
* Dave Herman <dherman@mozilla.com>
* Dimitris Vardoulakis <dimvar@ccs.neu.edu>
* Patrick Walton <pcwalton@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* Narcissus - JS implemented in JS.
*
* Well-known constants and lookup tables. Many consts are generated from the
* tokens table via eval to minimize redundancy, so consumers must be compiled
* separately to take advantage of the simple switch-case constant propagation
* done by SpiderMonkey.
*/
define(function(require, exports, module) {
exports.options = {
version: 185,
};
(function() {
exports.hostGlobal = this
})();
var tokens = [
// End of source.
"END",
// Operators and punctuators. Some pair-wise order matters, e.g. (+, -)
// and (UNARY_PLUS, UNARY_MINUS).
"\n", ";",
",",
"=",
"?", ":", "CONDITIONAL",
"||",
"&&",
"|",
"^",
"&",
"==", "!=", "===", "!==",
"<", "<=", ">=", ">",
"<<", ">>", ">>>",
"+", "-",
"*", "/", "%",
"!", "~", "UNARY_PLUS", "UNARY_MINUS",
"++", "--",
".",
"[", "]",
"{", "}",
"(", ")",
// Nonterminal tree node type codes.
"SCRIPT", "BLOCK", "LABEL", "FOR_IN", "CALL", "NEW_WITH_ARGS", "INDEX",
"ARRAY_INIT", "OBJECT_INIT", "PROPERTY_INIT", "GETTER", "SETTER",
"GROUP", "LIST", "LET_BLOCK", "ARRAY_COMP", "GENERATOR", "COMP_TAIL",
// Terminals.
"IDENTIFIER", "NUMBER", "STRING", "REGEXP",
// Keywords.
"break",
"case", "catch", "const", "continue",
"debugger", "default", "delete", "do",
"else",
"false", "finally", "for", "function",
"if", "in", "instanceof",
"let",
"new", "null",
"return",
"switch",
"this", "throw", "true", "try", "typeof",
"var", "void",
"yield",
"while", "with",
];
var statementStartTokens = [
"break",
"const", "continue",
"debugger", "do",
"for",
"if",
"return",
"switch",
"throw", "try",
"var",
"yield",
"while", "with",
];
// Operator and punctuator mapping from token to tree node type name.
// NB: because the lexer doesn't backtrack, all token prefixes must themselves
// be valid tokens (e.g. !== is acceptable because its prefixes are the valid
// tokens != and !).
var opTypeNames = {
'\n': "NEWLINE",
';': "SEMICOLON",
',': "COMMA",
'?': "HOOK",
':': "COLON",
'||': "OR",
'&&': "AND",
'|': "BITWISE_OR",
'^': "BITWISE_XOR",
'&': "BITWISE_AND",
'===': "STRICT_EQ",
'==': "EQ",
'=': "ASSIGN",
'!==': "STRICT_NE",
'!=': "NE",
'<<': "LSH",
'<=': "LE",
'<': "LT",
'>>>': "URSH",
'>>': "RSH",
'>=': "GE",
'>': "GT",
'++': "INCREMENT",
'--': "DECREMENT",
'+': "PLUS",
'-': "MINUS",
'*': "MUL",
'/': "DIV",
'%': "MOD",
'!': "NOT",
'~': "BITWISE_NOT",
'.': "DOT",
'[': "LEFT_BRACKET",
']': "RIGHT_BRACKET",
'{': "LEFT_CURLY",
'}': "RIGHT_CURLY",
'(': "LEFT_PAREN",
')': "RIGHT_PAREN"
};
// Hash of keyword identifier to tokens index. NB: we must null __proto__ to
// avoid toString, etc. namespace pollution.
var keywords = {__proto__: null};
// Define const END, etc., based on the token names. Also map name to index.
var tokenIds = {};
// Building up a string to be eval'd in different contexts.
var consts = "const ";
for (var i = 0, j = tokens.length; i < j; i++) {
if (i > 0)
consts += ", ";
var t = tokens[i];
var name;
if (/^[a-z]/.test(t)) {
name = t.toUpperCase();
keywords[t] = i;
} else {
name = (/^\W/.test(t) ? opTypeNames[t] : t);
}
consts += name + " = " + i;
tokenIds[name] = i;
tokens[t] = i;
}
consts += ";";
var isStatementStartCode = {__proto__: null};
for (i = 0, j = statementStartTokens.length; i < j; i++)
isStatementStartCode[keywords[statementStartTokens[i]]] = true;
// Map assignment operators to their indexes in the tokens array.
var assignOps = ['|', '^', '&', '<<', '>>', '>>>', '+', '-', '*', '/', '%'];
for (i = 0, j = assignOps.length; i < j; i++) {
t = assignOps[i];
assignOps[t] = tokens[t];
}
function defineGetter(obj, prop, fn, dontDelete, dontEnum) {
Object.defineProperty(obj, prop,
{ get: fn, configurable: !dontDelete, enumerable: !dontEnum });
}
function defineProperty(obj, prop, val, dontDelete, readOnly, dontEnum) {
Object.defineProperty(obj, prop,
{ value: val, writable: !readOnly, configurable: !dontDelete,
enumerable: !dontEnum });
}
// Returns true if fn is a native function. (Note: SpiderMonkey specific.)
function isNativeCode(fn) {
// Relies on the toString method to identify native code.
return ((typeof fn) === "function") && fn.toString().match(/\[native code\]/);
}
function getPropertyDescriptor(obj, name) {
while (obj) {
if (({}).hasOwnProperty.call(obj, name))
return Object.getOwnPropertyDescriptor(obj, name);
obj = Object.getPrototypeOf(obj);
}
}
function getOwnProperties(obj) {
var map = {};
for (var name in Object.getOwnPropertyNames(obj))
map[name] = Object.getOwnPropertyDescriptor(obj, name);
return map;
}
function makePassthruHandler(obj) {
// Handler copied from
// http://wiki.ecmascript.org/doku.php?id=harmony:proxies&s=proxy%20object#examplea_no-op_forwarding_proxy
return {
getOwnPropertyDescriptor: function(name) {
var desc = Object.getOwnPropertyDescriptor(obj, name);
// a trapping proxy's properties must always be configurable
desc.configurable = true;
return desc;
},
getPropertyDescriptor: function(name) {
var desc = getPropertyDescriptor(obj, name);
// a trapping proxy's properties must always be configurable
desc.configurable = true;
return desc;
},
getOwnPropertyNames: function() {
return Object.getOwnPropertyNames(obj);
},
defineProperty: function(name, desc) {
Object.defineProperty(obj, name, desc);
},
"delete": function(name) { return delete obj[name]; },
fix: function() {
if (Object.isFrozen(obj)) {
return getOwnProperties(obj);
}
// As long as obj is not frozen, the proxy won't allow itself to be fixed.
return undefined; // will cause a TypeError to be thrown
},
has: function(name) { return name in obj; },
hasOwn: function(name) { return ({}).hasOwnProperty.call(obj, name); },
get: function(receiver, name) { return obj[name]; },
// bad behavior when set fails in non-strict mode
set: function(receiver, name, val) { obj[name] = val; return true; },
enumerate: function() {
var result = [];
for (name in obj) { result.push(name); };
return result;
},
keys: function() { return Object.keys(obj); }
};
}
// default function used when looking for a property in the global object
function noPropFound() { return undefined; }
var hasOwnProperty = ({}).hasOwnProperty;
function StringMap() {
this.table = Object.create(null, {});
this.size = 0;
}
StringMap.prototype = {
has: function(x) { return hasOwnProperty.call(this.table, x); },
set: function(x, v) {
if (!hasOwnProperty.call(this.table, x))
this.size++;
this.table[x] = v;
},
get: function(x) { return this.table[x]; },
getDef: function(x, thunk) {
if (!hasOwnProperty.call(this.table, x)) {
this.size++;
this.table[x] = thunk();
}
return this.table[x];
},
forEach: function(f) {
var table = this.table;
for (var key in table)
f.call(this, key, table[key]);
},
toString: function() { return "[object StringMap]" }
};
// non-destructive stack
function Stack(elts) {
this.elts = elts || null;
}
Stack.prototype = {
push: function(x) {
return new Stack({ top: x, rest: this.elts });
},
top: function() {
if (!this.elts)
throw new Error("empty stack");
return this.elts.top;
},
isEmpty: function() {
return this.top === null;
},
find: function(test) {
for (var elts = this.elts; elts; elts = elts.rest) {
if (test(elts.top))
return elts.top;
}
return null;
},
has: function(x) {
return Boolean(this.find(function(elt) { return elt === x }));
},
forEach: function(f) {
for (var elts = this.elts; elts; elts = elts.rest) {
f(elts.top);
}
}
};
exports.tokens = tokens;
exports.opTypeNames = opTypeNames;
exports.keywords = keywords;
exports.isStatementStartCode = isStatementStartCode;
exports.tokenIds = tokenIds;
exports.consts = consts;
exports.assignOps = assignOps;
exports.defineGetter = defineGetter;
exports.defineProperty = defineProperty;
exports.isNativeCode = isNativeCode;
exports.makePassthruHandler = makePassthruHandler;
exports.noPropFound = noPropFound;
exports.StringMap = StringMap;
exports.Stack = Stack;
});

460
lib/ace/narcissus/jslex.js Normal file
View file

@ -0,0 +1,460 @@
/* vim: set sw=4 ts=4 et tw=78: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Narcissus JavaScript engine.
*
* The Initial Developer of the Original Code is
* Brendan Eich <brendan@mozilla.org>.
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Tom Austin <taustin@ucsc.edu>
* Brendan Eich <brendan@mozilla.org>
* Shu-Yu Guo <shu@rfrn.org>
* Dave Herman <dherman@mozilla.com>
* Dimitris Vardoulakis <dimvar@ccs.neu.edu>
* Patrick Walton <pcwalton@mozilla.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* Narcissus - JS implemented in JS.
*
* Lexical scanner.
*/
define(function(require, exports, module) {
var definitions = require("ace/narcissus/jsdefs");
// Set constants in the local scope.
eval(definitions.consts);
// Build up a trie of operator tokens.
var opTokens = {};
for (var op in definitions.opTypeNames) {
if (op === '\n' || op === '.')
continue;
var node = opTokens;
for (var i = 0; i < op.length; i++) {
var ch = op[i];
if (!(ch in node))
node[ch] = {};
node = node[ch];
node.op = op;
}
}
/*
* Tokenizer :: (source, filename, line number) -> Tokenizer
*/
function Tokenizer(s, f, l) {
this.cursor = 0;
this.source = String(s);
this.tokens = [];
this.tokenIndex = 0;
this.lookahead = 0;
this.scanNewlines = false;
this.unexpectedEOF = false;
this.filename = f || "";
this.lineno = l || 1;
}
Tokenizer.prototype = {
get done() {
// We need to set scanOperand to true here because the first thing
// might be a regexp.
return this.peek(true) === END;
},
get token() {
return this.tokens[this.tokenIndex];
},
match: function (tt, scanOperand) {
return this.get(scanOperand) === tt || this.unget();
},
mustMatch: function (tt) {
if (!this.match(tt)) {
throw this.newSyntaxError("Missing " +
definitions.tokens[tt].toLowerCase());
}
return this.token;
},
peek: function (scanOperand) {
var tt, next;
if (this.lookahead) {
next = this.tokens[(this.tokenIndex + this.lookahead) & 3];
tt = (this.scanNewlines && next.lineno !== this.lineno)
? NEWLINE
: next.type;
} else {
tt = this.get(scanOperand);
this.unget();
}
return tt;
},
peekOnSameLine: function (scanOperand) {
this.scanNewlines = true;
var tt = this.peek(scanOperand);
this.scanNewlines = false;
return tt;
},
// Eat comments and whitespace.
skip: function () {
var input = this.source;
for (;;) {
var ch = input[this.cursor++];
var next = input[this.cursor];
if (ch === '\n' && !this.scanNewlines) {
this.lineno++;
} else if (ch === '/' && next === '*') {
this.cursor++;
for (;;) {
ch = input[this.cursor++];
if (ch === undefined)
throw this.newSyntaxError("Unterminated comment");
if (ch === '*') {
next = input[this.cursor];
if (next === '/') {
this.cursor++;
break;
}
} else if (ch === '\n') {
this.lineno++;
}
}
} else if (ch === '/' && next === '/') {
this.cursor++;
for (;;) {
ch = input[this.cursor++];
if (ch === undefined)
return;
if (ch === '\n') {
this.lineno++;
break;
}
}
} else if (ch !== ' ' && ch !== '\t') {
this.cursor--;
return;
}
}
},
// Lex the exponential part of a number, if present. Return true iff an
// exponential part was found.
lexExponent: function() {
var input = this.source;
var next = input[this.cursor];
if (next === 'e' || next === 'E') {
this.cursor++;
ch = input[this.cursor++];
if (ch === '+' || ch === '-')
ch = input[this.cursor++];
if (ch < '0' || ch > '9')
throw this.newSyntaxError("Missing exponent");
do {
ch = input[this.cursor++];
} while (ch >= '0' && ch <= '9');
this.cursor--;
return true;
}
return false;
},
lexZeroNumber: function (ch) {
var token = this.token, input = this.source;
token.type = NUMBER;
ch = input[this.cursor++];
if (ch === '.') {
do {
ch = input[this.cursor++];
} while (ch >= '0' && ch <= '9');
this.cursor--;
this.lexExponent();
token.value = parseFloat(token.start, this.cursor);
} else if (ch === 'x' || ch === 'X') {
do {
ch = input[this.cursor++];
} while ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') ||
(ch >= 'A' && ch <= 'F'));
this.cursor--;
token.value = parseInt(input.substring(token.start, this.cursor));
} else if (ch >= '0' && ch <= '7') {
do {
ch = input[this.cursor++];
} while (ch >= '0' && ch <= '7');
this.cursor--;
token.value = parseInt(input.substring(token.start, this.cursor));
} else {
this.cursor--;
this.lexExponent(); // 0E1, &c.
token.value = 0;
}
},
lexNumber: function (ch) {
var token = this.token, input = this.source;
token.type = NUMBER;
var floating = false;
do {
ch = input[this.cursor++];
if (ch === '.' && !floating) {
floating = true;
ch = input[this.cursor++];
}
} while (ch >= '0' && ch <= '9');
this.cursor--;
var exponent = this.lexExponent();
floating = floating || exponent;
var str = input.substring(token.start, this.cursor);
token.value = floating ? parseFloat(str) : parseInt(str);
},
lexDot: function (ch) {
var token = this.token, input = this.source;
var next = input[this.cursor];
if (next >= '0' && next <= '9') {
do {
ch = input[this.cursor++];
} while (ch >= '0' && ch <= '9');
this.cursor--;
this.lexExponent();
token.type = NUMBER;
token.value = parseFloat(token.start, this.cursor);
} else {
token.type = DOT;
token.assignOp = null;
token.value = '.';
}
},
lexString: function (ch) {
var token = this.token, input = this.source;
token.type = STRING;
var hasEscapes = false;
var delim = ch;
while ((ch = input[this.cursor++]) !== delim) {
if (this.cursor == input.length)
throw this.newSyntaxError("Unterminated string literal");
if (ch === '\\') {
hasEscapes = true;
if (++this.cursor == input.length)
throw this.newSyntaxError("Unterminated string literal");
}
}
token.value = hasEscapes
? eval(input.substring(token.start, this.cursor))
: input.substring(token.start + 1, this.cursor - 1);
},
lexRegExp: function (ch) {
var token = this.token, input = this.source;
token.type = REGEXP;
do {
ch = input[this.cursor++];
if (ch === '\\') {
this.cursor++;
} else if (ch === '[') {
do {
if (ch === undefined)
throw this.newSyntaxError("Unterminated character class");
if (ch === '\\')
this.cursor++;
ch = input[this.cursor++];
} while (ch !== ']');
} else if (ch === undefined) {
throw this.newSyntaxError("Unterminated regex");
}
} while (ch !== '/');
do {
ch = input[this.cursor++];
} while (ch >= 'a' && ch <= 'z');
this.cursor--;
token.value = eval(input.substring(token.start, this.cursor));
},
lexOp: function (ch) {
var token = this.token, input = this.source;
// A bit ugly, but it seems wasteful to write a trie lookup routine
// for only 3 characters...
var node = opTokens[ch];
var next = input[this.cursor];
if (next in node) {
node = node[next];
this.cursor++;
next = input[this.cursor];
if (next in node) {
node = node[next];
this.cursor++;
next = input[this.cursor];
}
}
var op = node.op;
if (definitions.assignOps[op] && input[this.cursor] === '=') {
this.cursor++;
token.type = ASSIGN;
token.assignOp = definitions.tokenIds[definitions.opTypeNames[op]];
op += '=';
} else {
token.type = definitions.tokenIds[definitions.opTypeNames[op]];
token.assignOp = null;
}
token.value = op;
},
// FIXME: Unicode escape sequences
// FIXME: Unicode identifiers
lexIdent: function (ch) {
var token = this.token, input = this.source;
do {
ch = input[this.cursor++];
} while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch === '$' || ch === '_');
this.cursor--; // Put the non-word character back.
var id = input.substring(token.start, this.cursor);
token.type = definitions.keywords[id] || IDENTIFIER;
token.value = id;
},
/*
* Tokenizer.get :: void -> token type
*
* Consume input *only* if there is no lookahead.
* Dispatch to the appropriate lexing function depending on the input.
*/
get: function (scanOperand) {
var token;
while (this.lookahead) {
--this.lookahead;
this.tokenIndex = (this.tokenIndex + 1) & 3;
token = this.tokens[this.tokenIndex];
if (token.type !== NEWLINE || this.scanNewlines)
return token.type;
}
this.skip();
this.tokenIndex = (this.tokenIndex + 1) & 3;
token = this.tokens[this.tokenIndex];
if (!token)
this.tokens[this.tokenIndex] = token = {};
var input = this.source;
if (this.cursor === input.length)
return token.type = END;
token.start = this.cursor;
token.lineno = this.lineno;
var ch = input[this.cursor++];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '$' || ch === '_') {
this.lexIdent(ch);
} else if (scanOperand && ch === '/') {
this.lexRegExp(ch);
} else if (ch in opTokens) {
this.lexOp(ch);
} else if (ch === '.') {
this.lexDot(ch);
} else if (ch >= '1' && ch <= '9') {
this.lexNumber(ch);
} else if (ch === '0') {
this.lexZeroNumber(ch);
} else if (ch === '"' || ch === "'") {
this.lexString(ch);
} else if (this.scanNewlines && ch === '\n') {
token.type = NEWLINE;
token.value = '\n';
this.lineno++;
} else {
throw this.newSyntaxError("Illegal token");
}
token.end = this.cursor;
return token.type;
},
/*
* Tokenizer.unget :: void -> undefined
*
* Match depends on unget returning undefined.
*/
unget: function () {
if (++this.lookahead === 4) throw "PANIC: too much lookahead!";
this.tokenIndex = (this.tokenIndex - 1) & 3;
},
newSyntaxError: function (m) {
var e = new SyntaxError(m, this.filename, this.lineno);
e.source = this.source;
e.lineno = this.lineno;
e.cursor = this.lookahead
? this.tokens[(this.tokenIndex + this.lookahead) & 3].start
: this.cursor;
return e;
},
};
exports.Tokenizer = Tokenizer;
});

1432
lib/ace/narcissus/jsparse.js Normal file

File diff suppressed because it is too large Load diff

View file

@ -129,5 +129,8 @@ MockRenderer.prototype.showCursor = function() {
MockRenderer.prototype.visualizeFocus = function() {
};
MockRenderer.prototype.setAnnotations = function() {
};
return MockRenderer;
});

View file

@ -68,8 +68,7 @@ var VirtualRenderer = function(container, theme) {
this.container.appendChild(this.scroller);
this.content = document.createElement("div");
this.content.style.cssText = "position:absolute;box-sizing:border-box;" +
"-moz-box-sizing:border-box;-webkit-box-sizing:border-box";
this.content.className = "ace_content";
this.scroller.appendChild(this.content);
this.$gutterLayer = new GutterLayer(this.$gutter);
@ -479,6 +478,11 @@ var VirtualRenderer = function(container, theme) {
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.setAnnotations = function(annotations) {
this.$gutterLayer.setAnnotations(annotations);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.updateCursor = function(position, overwrite) {
this.$cursorLayer.setCursor(position, overwrite);
this.$loop.schedule(this.CHANGE_CURSOR);
@ -591,12 +595,38 @@ var VirtualRenderer = function(container, theme) {
};
this.showComposition = function(position) {
console.log("show composition")
if (!this.$composition) {
this.$composition = document.createElement("div");
this.$composition.className = "ace_composition";
this.content.appendChild(this.$composition);
}
this.$composition.innerHTML = "&nbsp;";
var pos = this.$cursorLayer.getPixelPosition();
var style = this.$composition.style;
style.top = pos.top + "px";
style.left = (pos.left + this.$padding) + "px";
style.height = this.lineHeight + "px";
//style.width = this.characterWidth + "px";
this.hideCursor();
};
this.setCompositionText = function(text) {
this.$composition.innerText = this.$composition.textContent = text;
};
this.hideComposition = function() {
this.showCursor();
if (!this.$composition)
return;
var style = this.$composition.style;
style.top = "-10000px";
style.left = "-10000px";
};
this.setTheme = function(theme) {

90
lib/ace/worker/host.js Normal file
View file

@ -0,0 +1,90 @@
var console = {
log: function(msg) {
postMessage({type: "log", data: msg});
}
};
var window = {
console: console
};
var require = function(name) {
if (require.modules[name])
return require.modules[name].exports;
var chunks = name.split("/");
chunks[0] = require.tlns[chunks[0]] || chunks[0];
path = require.baseUrl + "/" + chunks.join("/") + ".js"
require.id = name;
importScripts(path);
return require.modules[name].exports;
};
require.modules = {};
require.tlns = {};
require.baseUrl;
var define = function(factory) {
var module = {
exports: {}
};
var name = require.id;
var returnExports = factory(require, module.exports, module);
if (returnExports)
module.exports = exports;
require.modules[name] = module;
};
function initBaseUrls(baseUrl, topLevelNamespaces) {
require.baseUrl = baseUrl;
require.tlns = topLevelNamespaces;
}
function initSender() {
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var oop = require("pilot/oop");
var Sender = function() {};
(function() {
oop.implement(this, EventEmitter);
this.callback = function(data, callbackId) {
postMessage({
type: "call",
id: callbackId,
data: data
});
},
this.emit = function(name, data) {
postMessage({
type: "event",
name: name,
data: data
});
}
}).call(Sender.prototype);
return new Sender();
}
var main;
var sender;
onmessage = function(e) {
var msg = e.data;
if (msg.command)
main[msg.command].apply(main, msg.args);
else if (msg.init) {
initBaseUrls(msg.base, msg.tlns);
sender = initSender();
var clazz = require(msg.module)[msg.classname];
main = new clazz(sender);
} else if (msg.event) {
sender._dispatchEvent(msg.event, msg.data);
}
};

5747
lib/ace/worker/jslint.js Normal file

File diff suppressed because it is too large Load diff

43
lib/ace/worker/mirror.js Normal file
View file

@ -0,0 +1,43 @@
define(function(require, exports, module) {
var Document = require("ace/document").Document;
var lang = require("pilot/lang");
var Mirror = exports.Mirror = function(sender) {
this.sender = sender;
var doc = this.doc = new Document("");
var deferredUpdate = this.deferredUpdate = lang.deferredCall(this.onUpdate.bind(this));
var _self = this;
sender.on("change", function(e) {
doc.applyDeltas([e.data]);
deferredUpdate.schedule(_self.$timeout);
})
};
(function() {
this.$timeout = 500;
this.setTimeout = function(timeout) {
this.$timeout = timeout;
};
this.setValue = function(value) {
this.doc.setValue(value);
this.deferredUpdate.schedule(this.$timeout);
};
this.getValue = function(callbackId) {
this.sender.callback(this.doc.getValue(), callbackId);
};
this.onUpdate = function() {
// abstract method
};
}).call(Mirror.prototype);
});

View file

@ -0,0 +1,93 @@
/**
* Ajax.org Code Editor (ACE)
*
* @copyright 2010, Ajax.org Services B.V.
* @license LGPLv3 <http://www.gnu.org/licenses/lgpl-3.0.txt>
* @author Fabian Jakobs <fabian AT ajax DOT org>
*/
define(function(require, exports, module) {
var oop = require("pilot/oop");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var WorkerClient = function(baseUrl, topLevelNamespaces, module, classname) {
this.callbacks = [];
var workerUrl = require.nameToUrl("ace/worker/host", null, "_");
var worker = this.$worker = new Worker(workerUrl);
var tlns = {};
for (var i=0; i<topLevelNamespaces.length; i++) {
var ns = topLevelNamespaces[i];
tlns[ns] = require.nameToUrl(ns, null, "_").replace(/.js$/, "").replace(require.config.baseUrl, "");
}
this.$worker.postMessage({
init : true,
tlns: tlns,
base: baseUrl,
module: module,
classname: classname
});
this.callbackId = 1;
this.callbacks = {};
var _self = this;
this.$worker.onerror = function(e) {
throw e;
};
this.$worker.onmessage = function(e) {
var msg = e.data;
switch(msg.type) {
case "log":
console.log(msg.data);
break;
case "event":
_self._dispatchEvent(msg.name, {data: msg.data});
break;
case "call":
var callback = _self.callbacks[msg.id];
if (callback) {
callback(msg.data);
delete _self.callbacks[msg.id];
}
break;
}
};
};
(function(){
oop.implement(this, EventEmitter);
this.terminate = function() {
this._dispatchEvent("terminate", {});
this.$worker.terminate();
};
this.send = function(cmd, args) {
this.$worker.postMessage({command: cmd, args: args});
};
this.call = function(cmd, args, callback) {
if (callback) {
var id = this.callbackId++;
this.callbacks[id] = callback;
args.push(id);
}
this.send(cmd, args);
};
this.emit = function(event, data) {
this.$worker.postMessage({event: event, data: data});
};
}).call(WorkerClient.prototype);
exports.WorkerClient = WorkerClient;
});