code
stringlengths
1
2.08M
language
stringclasses
1 value
define('ace/mode/groovy', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/groovy_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var JavaScriptMode = require("./javascript").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var GroovyHighlightRules = require("./groovy_highlight_rules").GroovyHighlightRules; var Mode = function() { JavaScriptMode.call(this); this.$tokenizer = new Tokenizer(new GroovyHighlightRules().getRules()); }; oop.inherits(Mode, JavaScriptMode); (function() { this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); 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); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/groovy_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var GroovyHighlightRules = function() { var keywords = lang.arrayToMap( ("assert|with|abstract|continue|for|new|switch|" + "assert|default|goto|package|synchronized|" + "boolean|do|if|private|this|" + "break|double|implements|protected|throw|" + "byte|else|import|public|throws|" + "case|enum|instanceof|return|transient|" + "catch|extends|int|short|try|" + "char|final|interface|static|void|" + "class|finally|long|strictfp|volatile|" + "def|float|native|super|while").split("|") ); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var langClasses = lang.arrayToMap( ("AbstractMethodError|AssertionError|ClassCircularityError|"+ "ClassFormatError|Deprecated|EnumConstantNotPresentException|"+ "ExceptionInInitializerError|IllegalAccessError|"+ "IllegalThreadStateException|InstantiationError|InternalError|"+ "NegativeArraySizeException|NoSuchFieldError|Override|Process|"+ "ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+ "SuppressWarnings|TypeNotPresentException|UnknownError|"+ "UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+ "InstantiationException|IndexOutOfBoundsException|"+ "ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+ "NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+ "SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+ "InterruptedException|NoSuchMethodException|IllegalAccessException|"+ "UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+ "Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+ "NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+ "NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+ "Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+ "Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+ "StackOverflowError|OutOfMemoryError|VirtualMachineError|"+ "ArrayStoreException|ClassCastException|LinkageError|"+ "NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+ "Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+ "Cloneable|Class|CharSequence|Comparable|String|Object").split("|") ); var importClasses = lang.arrayToMap( ("").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", regex : '"""', next : "qqstring" }, { token : "string", regex : "'''", next : "qstring" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (langClasses.hasOwnProperty(value)) return "support.function"; else if (importClasses.hasOwnProperty(value)) return "support.function"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\?:|\\?\\.|\\*\\.|<=>|=~|==~|\\.@|\\*\\.@|\\.&|as|in|is|!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : /\\(?:u[0-9A-Fa-f]{4}|.|$)/ }, { token : "constant.language.escape", regex : /\$[\w\d]+/ }, { token : "constant.language.escape", regex : /\$\{[^"\}]+\}?/ }, { token : "string", regex : '"{3,5}', next : "start" }, { token : "string", regex : '.+?' } ], "qstring" : [ { token : "constant.language.escape", regex : /\\(?:u[0-9A-Fa-f]{4}|.|$)/ }, { token : "string", regex : "'{3,5}", next : "start" }, { token : "string", regex : ".+?" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(GroovyHighlightRules, TextHighlightRules); exports.GroovyHighlightRules = GroovyHighlightRules; });
JavaScript
define('ace/mode/powershell', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/powershell_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PowershellHighlightRules = require("./powershell_highlight_rules").PowershellHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new PowershellHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/powershell_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PowershellHighlightRules = function() { var keywords = lang.arrayToMap( ("function|if|else|elseif|switch|while|default|for|do|until|break|continue|" + "foreach|return|filter|in|trap|throw|param|begin|process|end").split("|") ); var builtinFunctions = lang.arrayToMap( ("Get-Alias|Import-Alias|New-Alias|Set-Alias|Get-AuthenticodeSignature|Set-AuthenticodeSignature|" + "Set-Location|Get-ChildItem|Clear-Item|Get-Command|Measure-Command|Trace-Command|" + "Add-Computer|Checkpoint-Computer|Remove-Computer|Restart-Computer|Restore-Computer|Stop-Computer|" + "Reset-ComputerMachinePassword|Test-ComputerSecureChannel|Add-Content|Get-Content|Set-Content|Clear-Content|" + "Get-Command|Invoke-Command|Enable-ComputerRestore|Disable-ComputerRestore|Get-ComputerRestorePoint|Test-Connection|" + "ConvertFrom-CSV|ConvertTo-CSV|ConvertTo-Html|ConvertTo-Xml|ConvertFrom-SecureString|ConvertTo-SecureString|" + "Copy-Item|Export-Counter|Get-Counter|Import-Counter|Get-Credential|Get-Culture|" + "Get-ChildItem|Get-Date|Set-Date|Remove-Item|Compare-Object|Get-Event|" + "Get-WinEvent|New-Event|Remove-Event|Unregister-Event|Wait-Event|Clear-EventLog|" + "Get-Eventlog|Limit-EventLog|New-Eventlog|Remove-EventLog|Show-EventLog|Write-EventLog|" + "Get-EventSubscriber|Register-EngineEvent|Register-ObjectEvent|Register-WmiEvent|Get-ExecutionPolicy|Set-ExecutionPolicy|" + "Export-Alias|Export-Clixml|Export-Console|Export-Csv|ForEach-Object|Format-Custom|" + "Format-List|Format-Table|Format-Wide|Export-FormatData|Get-FormatData|Get-Item|" + "Get-ChildItem|Get-Help|Add-History|Clear-History|Get-History|Invoke-History|" + "Get-Host|Read-Host|Write-Host|Get-HotFix|Import-Clixml|Import-Csv|" + "Invoke-Command|Invoke-Expression|Get-Item|Invoke-Item|New-Item|Remove-Item|" + "Set-Item|Clear-ItemProperty|Copy-ItemProperty|Get-ItemProperty|Move-ItemProperty|New-ItemProperty|" + "Remove-ItemProperty|Rename-ItemProperty|Set-ItemProperty|Get-Job|Receive-Job|Remove-Job|" + "Start-Job|Stop-Job|Wait-Job|Stop-Process|Update-List|Get-Location|" + "Pop-Location|Push-Location|Set-Location|Send-MailMessage|Add-Member|Get-Member|" + "Move-Item|Compare-Object|Group-Object|Measure-Object|New-Object|Select-Object|" + "Sort-Object|Where-Object|Out-Default|Out-File|Out-GridView|Out-Host|" + "Out-Null|Out-Printer|Out-String|Convert-Path|Join-Path|Resolve-Path|" + "Split-Path|Test-Path|Get-Pfxcertificate|Pop-Location|Push-Location|Get-Process|" + "Start-Process|Stop-Process|Wait-Process|Enable-PSBreakpoint|Disable-PSBreakpoint|Get-PSBreakpoint|" + "Set-PSBreakpoint|Remove-PSBreakpoint|Get-PSDrive|New-PSDrive|Remove-PSDrive|Get-PSProvider|" + "Set-PSdebug|Enter-PSSession|Exit-PSSession|Export-PSSession|Get-PSSession|Import-PSSession|" + "New-PSSession|Remove-PSSession|Disable-PSSessionConfiguration|Enable-PSSessionConfiguration|Get-PSSessionConfiguration|Register-PSSessionConfiguration|" + "Set-PSSessionConfiguration|Unregister-PSSessionConfiguration|New-PSSessionOption|Add-PsSnapIn|Get-PsSnapin|Remove-PSSnapin|" + "Get-Random|Read-Host|Remove-Item|Rename-Item|Rename-ItemProperty|Select-Object|" + "Select-XML|Send-MailMessage|Get-Service|New-Service|Restart-Service|Resume-Service|" + "Set-Service|Start-Service|Stop-Service|Suspend-Service|Sort-Object|Start-Sleep|" + "ConvertFrom-StringData|Select-String|Tee-Object|New-Timespan|Trace-Command|Get-Tracesource|" + "Set-Tracesource|Start-Transaction|Complete-Transaction|Get-Transaction|Use-Transaction|Undo-Transaction|" + "Start-Transcript|Stop-Transcript|Add-Type|Update-TypeData|Get-Uiculture|Get-Unique|" + "Update-Formatdata|Update-Typedata|Clear-Variable|Get-Variable|New-Variable|Remove-Variable|" + "Set-Variable|New-WebServiceProxy|Where-Object|Write-Debug|Write-Error|Write-Host|" + "Write-Output|Write-Progress|Write-Verbose|Write-Warning|Set-WmiInstance|Invoke-WmiMethod|" + "Get-WmiObject|Remove-WmiObject|Connect-WSMan|Disconnect-WSMan|Test-WSMan|Invoke-WSManAction|" + "Disable-WSManCredSSP|Enable-WSManCredSSP|Get-WSManCredSSP|New-WSManInstance|Get-WSManInstance|Set-WSManInstance|" + "Remove-WSManInstance|Set-WSManQuickConfig|New-WSManSessionOption").split("|")); var binaryOperatorsRe = "eq|ne|ge|gt|lt|le|like|notlike|match|notmatch|replace|contains|notcontains|" + "ieq|ine|ige|igt|ile|ilt|ilike|inotlike|imatch|inotmatch|ireplace|icontains|inotcontains|" + "is|isnot|as|" + "and|or|band|bor|not"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "[$](?:[Tt]rue|[Ff]alse)\\b" }, { token : "constant.language", regex : "[$][Nn]ull\\b" }, { token : "variable.instance", regex : "[$][a-zA-Z][a-zA-Z0-9_]*\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$\\-]*\\b" }, { token : "keyword.operator", regex : "\\-(?:" + binaryOperatorsRe + ")" }, { token : "keyword.operator", regex : "&|\\*|\\+|\\-|\\=|\\+=|\\-=" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; }; oop.inherits(PowershellHighlightRules, TextHighlightRules); exports.PowershellHighlightRules = PowershellHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
"no use strict"; var console = { log: function(msg) { postMessage({type: "log", data: msg}); } }; var window = { console: console }; var normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); var moduleName = base + "/" + moduleName; while(moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; var require = function(parentId, id) { var id = normalizeModule(parentId, id); var module = require.modules[id]; if (module) { if (!module.initialized) { module.exports = module.factory().exports; module.initialized = true; } return module.exports; } var chunks = id.split("/"); chunks[0] = require.tlns[chunks[0]] || chunks[0]; var path = chunks.join("/") + ".js"; require.id = id; importScripts(path); return require(parentId, id); }; require.modules = {}; require.tlns = {}; var define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; } else if (arguments.length == 1) { factory = id; id = require.id; } if (id.indexOf("text!") === 0) return; var req = function(deps, factory) { return require(id, deps, factory); }; require.modules[id] = { factory: function() { var module = { exports: {} }; var returnExports = factory(req, module.exports, module); if (returnExports) module.exports = returnExports; return module; } }; }; function initBaseUrls(topLevelNamespaces) { require.tlns = topLevelNamespaces; } function initSender() { var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter; var oop = require(null, "ace/lib/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.tlns); require(null, "ace/lib/fixoldbrowsers"); sender = initSender(); var clazz = require(null, msg.module)[msg.classname]; main = new clazz(sender); } else if (msg.event && sender) { sender._emit(msg.event, msg.data); } }; // vim:set ts=4 sts=4 sw=4 st: // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { require("./regexp"); require("./es5-shim"); }); define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { //--------------------------------- // Private variables //--------------------------------- var real = { exec: RegExp.prototype.exec, test: RegExp.prototype.test, match: String.prototype.match, replace: String.prototype.replace, split: String.prototype.split }, compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups compliantLastIndexIncrement = function () { var x = /^/g; real.test.call(x, ""); return !x.lastIndex; }(); if (compliantLastIndexIncrement && compliantExecNpcg) return; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match real.replace.call(str.slice(match.index), r2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undefined) match[i] = undefined; } }); } // Attach named capture properties if (this._xregexp && this._xregexp.captureNames) { for (var i = 1; i < match.length; i++) { name = this._xregexp.captureNames[i - 1]; if (name) match[name] = match[i]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } return match; }; // Don't override `test` if it won't change anything if (!compliantLastIndexIncrement) { // Fix browser bug in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the overriden // `exec` would take care of the `lastIndex` fix var match = real.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; return !!match; }; } //--------------------------------- // Private helper functions //--------------------------------- function getNativeFlags (regex) { return (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "") + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 (regex.sticky ? "y" : ""); }; function indexOf (array, item, from) { if (Array.prototype.indexOf) // Use the native array method if available return array.indexOf(item, from); for (var i = from || 0; i < array.length; i++) { if (array[i] === item) return i; } return -1; }; }); // vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA // -- bryanforbes Bryan Forbes XXX TODO License or CLA // -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence // -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License // -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License // -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) // -- iwyg XXX TODO License or CLA // -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License // -- xavierm02 Montillet Xavier XXX TODO License or CLA // -- Raynos Raynos XXX TODO License or CLA // -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License // -- rwldrn Rick Waldron Copyright (C) 2011 MIT License // -- lexer Alexey Zakharov XXX TODO License or CLA /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * * @module */ /*whatsupdoc*/ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") throw new TypeError(); // TODO message // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (result !== null && Object(result) === result) return result; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(slice.call(arguments)) ); } }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); // If JS engine supports accessors creating shortcuts. var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } // // Array // ===== // // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var self = toObject(this), thisp = arguments[1], i = 0, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object context fun.call(thisp, self[i], i, self); } i++; } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var self = toObject(this), length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, self); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, result = [], thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) result.push(self[i]); } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, self)) return false; } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) return true; } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) throw new TypeError(); // TODO message } while (true); } for (; i < length; i++) { if (i in self) result = fun.call(void 0, result, self[i], i, self); } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value, empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) throw new TypeError(); // TODO message } while (true); } do { if (i in this) result = fun.call(void 0, result, self[i], i, self); } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = 0; if (arguments.length > 1) i = toInteger(arguments[1]); // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = length - 1; if (arguments.length > 1) i = Math.min(i, toInteger(arguments[1])); // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) return i; } return -1; }; } // // Object // ====== // // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/kriskowal/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); // If object does not owns property return undefined immediately. if (!owns(object, property)) return; var descriptor, getter, setter; // If object has a property then it's for sure both `enumerable` and // `configurable`. descriptor = { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = { "__proto__": null }; } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) === object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) hasDontEnumBug = false; Object.keys = function keys(object) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError("Object.keys called on a non-object"); var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { Date.prototype.toISOString = function toISOString() { var result, length, value, year; if (!isFinite(this)) throw new RangeError; // the date time string format is specified in 15.9.1.15. result = [this.getUTCMonth() + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = this.getUTCFullYear(); year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two digits. if (value < 10) result[length] = "0" + value; } // pad milliseconds to have three digits. return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; } } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). if (!Date.prototype.toJSON) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be ToPrimitive(O, hint Number). // 3. If tv is a Number and is not finite, return null. // XXX // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof this.toISOString != "function") throw new TypeError(); // TODO message // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return this.toISOString(); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 var Date = function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:\\.(\\d{3}))?" + // milliseconds capture ")?" + "(?:" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) Date[key] = NativeDate[key]; // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { match.shift(); // kill match[0], the full match // parse months, days, hours, minutes, seconds, and milliseconds for (var i = 1; i < 7; i++) { // provide default values if necessary match[i] = +(match[i] || (i < 3 ? 1 : 0)); // match[1] is the month. Months are 0-11 in JavaScript // `Date` objects, but 1-12 in ISO notation, so we // decrement. if (i == 1) match[i]--; } // parse the UTC offset component var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); // compute the explicit time zone offset if specified var offset = 0; if (sign) { // detect invalid offsets and return early if (hourOffset > 23 || minuteOffset > 59) return NaN; // express the provided time zone offset in minutes. The offset is // negative for time zones west of UTC; positive otherwise. offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); } // Date.UTC for years between 0 and 99 converts year to 1900 + year // The Gregorian calendar has a 400-year cycle, so // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years var year = +match[0]; if (0 <= year && year <= 99) { match[0] = year + 400; return NativeDate.UTC.apply(this, match) + offset - 12622780800000; } // compute a new UTC date value, accounting for the optional offset return NativeDate.UTC.apply(this, match) + offset; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // // String // ====== // // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer var toInteger = function (n) { n = +n; if (n !== n) // isNaN n = 0; else if (n !== 0 && n !== (1/0) && n !== -(1/0)) n = (n > 0 || -1) * Math.floor(Math.abs(n)); return n; }; var prepareString = "a"[0] != "a", // ES5 9.9 // http://es5.github.com/#x9.9 toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError(); // TODO message } // If the implementation doesn't support by-index access of // string characters (ex. IE < 7), split the string if (prepareString && typeof o == "string" && o) { return o.split(""); } return Object(o); }; }); define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { var EventEmitter = {}; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry = this._eventRegistry || {}; this._defaultHandlers = this._defaultHandlers || {}; var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; e = e || {}; e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) var listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) { exports.inherits = (function() { var tempCtor = function() {}; return function(ctor, superCtor) { tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor.prototype; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; }()); exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); define('ace/mode/javascript_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/worker/jshint', 'ace/narcissus/parser'], function(require, exports, module) { var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var lint = require("../worker/jshint").JSHINT; var parser = require("../narcissus/parser"); 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(); value = value.replace(/^#!.*\n/, "\n"); // var start = new Date(); try { parser.parse(value); } catch(e) { // console.log("narcissus") // console.log(e); var chunks = e.message.split(":") var message = chunks.pop().trim(); var lineNumber = parseInt(chunks.pop().trim()) - 1; this.sender.emit("narcissus", { row: lineNumber, column: null, // TODO convert e.cursor text: 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); }); define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) { var Document = require("../document").Document; var lang = require("../lib/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); }); define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; /** * new Document([text]) * - text (String | Array): The starting text * * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * **/ var Document = function(text) { this.$lines = []; // There has to be one line at least in the document. If you pass an empty // string to the insert function, nothing will happen. Workaround. if (text.length == 0) { this.$lines = [""]; } else if (Array.isArray(text)) { this.insertLines(0, text); } else { this.insert({row: 0, column:0}, text); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength(); this.remove(new Range(0, 0, len, this.getLine(len-1).length)); this.insert({row: 0, column:0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; // check for IE split bug if ("aaa".split(/a/).length == 0) this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); } else this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; case "auto": return this.$autoNewLine; } }; this.$autoNewLine = "\n"; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { if (range.start.row == range.end.row) { return this.$lines[range.start.row].substring(range.start.column, range.end.column); } else { var lines = this.getLines(range.start.row+1, range.end.row-1); lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column)); lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column)); return lines.join(this.getNewLineCharacter()); } }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length-1).length; } return position; }; this.insert = function(position, text) { if (!text || text.length === 0) return position; position = this.$clipPosition(position); // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); var lines = this.$split(text); var firstLine = lines.splice(0, 1)[0]; var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; position = this.insertInLine(position, firstLine); if (lastLine !== null) { position = this.insertNewLine(position); // terminate first line position = this.insertLines(position.row, lines); position = this.insertInLine(position, lastLine || ""); } return position; }; this.insertLines = function(row, lines) { if (lines.length == 0) return {row: row, column: 0}; // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) // to circumvent that we have to break huge inserts into smaller chunks here if (lines.length > 0xFFFF) { var end = this.insertLines(row, lines.slice(0xFFFF)); lines = lines.slice(0, 0xFFFF); } var args = [row, 0]; args.push.apply(args, lines); this.$lines.splice.apply(this.$lines, args); var range = new Range(row, 0, row + lines.length, 0); var delta = { action: "insertLines", range: range, lines: lines }; this._emit("change", { data: delta }); return end || range.end; }; this.insertNewLine = function(position) { position = this.$clipPosition(position); var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column); this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); var end = { row : position.row + 1, column : 0 }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); return end; }; this.insertInLine = function(position, text) { if (text.length == 0) return position; var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column) + text + line.substring(position.column); var end = { row : position.row, column : position.column + text.length }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: text }; this._emit("change", { data: delta }); return end; }; this.remove = function(range) { // clip to document range.start = this.$clipPosition(range.start); range.end = this.$clipPosition(range.end); if (range.isEmpty()) return range.start; var firstRow = range.start.row; var lastRow = range.end.row; if (range.isMultiLine()) { var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; var lastFullRow = lastRow - 1; if (range.end.column > 0) this.removeInLine(lastRow, 0, range.end.column); if (lastFullRow >= firstFullRow) this.removeLines(firstFullRow, lastFullRow); if (firstFullRow != firstRow) { this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); this.removeNewLine(range.start.row); } } else { this.removeInLine(firstRow, range.start.column, range.end.column); } return range.start; }; this.removeInLine = function(row, startColumn, endColumn) { if (startColumn == endColumn) return; var range = new Range(row, startColumn, row, endColumn); var line = this.getLine(row); var removed = line.substring(startColumn, endColumn); var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); this.$lines.splice(row, 1, newLine); var delta = { action: "removeText", range: range, text: removed }; this._emit("change", { data: delta }); return range.start; }; this.removeLines = function(firstRow, lastRow) { var range = new Range(firstRow, 0, lastRow + 1, 0); var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); var delta = { action: "removeLines", range: range, nl: this.getNewLineCharacter(), lines: removed }; this._emit("change", { data: delta }); return removed; }; this.removeNewLine = function(row) { var firstLine = this.getLine(row); var secondLine = this.getLine(row+1); var range = new Range(row, firstLine.length, row+1, 0); var line = firstLine + secondLine; this.$lines.splice(row, 2, line); var delta = { action: "removeText", range: range, text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); }; this.replace = function(range, text) { if (text.length == 0 && range.isEmpty()) return range.start; // Shortcut: If the text we want to insert is the same as it is already // in the document, we don't have to replace anything. if (text == this.getTextRange(range)) return range.end; this.remove(range); if (text) { var end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "insertText") this.insert(range.start, delta.text); else if (delta.action == "removeLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "removeText") this.remove(range); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "insertText") this.remove(range); else if (delta.action == "removeLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "removeText") this.insert(range.start, delta.text); } }; }).call(Document.prototype); exports.Document = Document; }); define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Range * * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. * **/ /** * new Range(startRow, startColumn, endRow, endColumn) * - startRow (Number): The starting row * - startColumn (Number): The starting column * - endRow (Number): The ending row * - endColumn (Number): The ending column * * Creates a new `Range` object with the given starting and ending row and column points. * **/ var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { /** * Range.isEqual(range) -> Boolean * - range (Range): A range to check against * * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. * **/ this.isEqual = function(range) { return this.start.row == range.start.row && this.end.row == range.end.row && this.start.column == range.start.column && this.end.column == range.end.column }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } } /** related to: Range.compare * Range.comparePoint(p) -> Number * - p (Range): A point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1<br/> * * Checks the row and column points of `p` with the row and column points of the calling range. * * * **/ this.comparePoint = function(p) { return this.compare(p.row, p.column); } /** related to: Range.comparePoint * Range.containsRange(range) -> Boolean * - range (Range): A range to compare with * * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * **/ this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } /** * Range.intersects(range) -> Boolean * - range (Range): A range to compare with * * Returns `true` if passed in `range` intersects with the one calling this method. * **/ this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); } /** * Range.isEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * **/ this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } /** * Range.isStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * **/ this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; } /** * Range.setStart(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } } /** * Range.setEnd(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } } /** related to: Range.compare * Range.inside(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range. * **/ this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's starting points. * **/ this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's ending points. * **/ this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; } /** * Range.compare(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal <br/> * * `-1` if `p.row` is less then the calling range <br/> * * `1` if `p.row` is greater than the calling range <br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> * <br/> * If the ending row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); }; } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } } /** * Range.compareEnd(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } } /** * Range.compareInside(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/> * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/> * <br/> * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. * * Checks the row and column points with the row and column points of the calling range. * * * **/ this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } } /** * Range.clipRows(firstRow, lastRow) -> Range * - firstRow (Number): The starting row * - lastRow (Number): The ending row * * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * **/ this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) { var end = { row: lastRow+1, column: 0 }; } if (this.start.row > lastRow) { var start = { row: lastRow+1, column: 0 }; } if (this.start.row < firstRow) { var start = { row: firstRow, column: 0 }; } if (this.end.row < firstRow) { var end = { row: firstRow, column: 0 }; } return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || 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 Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; exports.Range = Range; }); define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new Anchor(doc, row, column) * - doc (Document): The document to associate with the anchor * - row (Number): The starting row position * - column (Number): The starting column position * * Creates a new `Anchor` and associates it with a document. * **/ var Anchor = exports.Anchor = function(doc, row, column) { this.document = doc; if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); this.$onChange = this.onChange.bind(this); doc.on("change", this.$onChange); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.onChange = function(e) { var delta = e.data; var range = delta.range; if (range.start.row == range.end.row && range.start.row != this.row) return; if (range.start.row > this.row) return; if (range.start.row == this.row && range.start.column > this.column) return; var row = this.row; var column = this.column; if (delta.action === "insertText") { if (range.start.row === row && range.start.column <= column) { if (range.start.row === range.end.row) { column += range.end.column - range.start.column; } else { column -= range.start.column; row += range.end.row - range.start.row; } } else if (range.start.row !== range.end.row && range.start.row < row) { row += range.end.row - range.start.row; } } else if (delta.action === "insertLines") { if (range.start.row <= row) { row += range.end.row - range.start.row; } } else if (delta.action == "removeText") { if (range.start.row == row && range.start.column < column) { if (range.end.column >= column) column = range.start.column; else column = Math.max(0, column - (range.end.column - range.start.column)); } else if (range.start.row !== range.end.row && range.start.row < row) { if (range.end.row == row) { column = Math.max(0, column - range.end.column) + range.start.column; } row -= (range.end.row - range.start.row); } else if (range.end.row == row) { row -= range.end.row - range.start.row; column = Math.max(0, column - range.end.column) + range.start.column; } } else if (delta.action == "removeLines") { if (range.start.row <= row) { if (range.end.row <= row) row -= range.end.row - range.start.row; else { row = range.start.row; column = 0; } } } this.setPosition(row, column, true); }; 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._emit("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("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); }); define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { return new Array(count + 1).join(string); }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function (obj) { if (typeof obj != "object") { return obj; } var copy = obj.constructor(); for (var key in obj) { if (typeof obj[key] == "object") { copy[key] = this.deepCopy(obj[key]); } else { copy[key] = obj[key]; } } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; return deferred; }; }); define('ace/worker/jshint', ['require', 'exports', 'module' ], function(require, exports, module) { /*! * JSHint, by JSHint Community. * * Licensed under the same slightly modified MIT license that JSLint is. * It stops evil-doers everywhere. * * JSHint is a derivative work of JSLint: * * Copyright (c) 2002 Douglas Crockford (www.JSLint.com) * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * The Software shall be used for Good, not Evil. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * JSHint was forked from 2010-12-16 edition of JSLint. * */ /* JSHINT is a global function. It takes two parameters. var myResult = JSHINT(source, option); The first parameter is either a string or an array of strings. If it is a string, it will be split on '\n' or '\r'. If it is an array of strings, it is assumed that each string represents one line. The source can be a JavaScript text or a JSON text. The second parameter is an optional object of options which control the operation of JSHINT. Most of the options are booleans: They are all optional and have a default value of false. One of the options, predef, can be an array of names, which will be used to declare global variables, or an object whose keys are used as global names, with a boolean value that determines if they are assignable. If it checks out, JSHINT returns true. Otherwise, it returns false. If false, you can inspect JSHINT.errors to find out the problems. JSHINT.errors is an array of objects containing these members: { line : The line (relative to 0) at which the lint was found character : The character (relative to 0) at which the lint was found reason : The problem evidence : The text line in which the problem occurred raw : The raw message before the details were inserted a : The first detail b : The second detail c : The third detail d : The fourth detail } If a fatal error was found, a null will be the last element of the JSHINT.errors array. You can request a Function Report, which shows all of the functions and the parameters and vars that they use. This can be used to find implied global variables and other problems. The report is in HTML and can be inserted in an HTML <body>. var myReport = JSHINT.report(limited); If limited is true, then the report will be limited to only errors. You can request a data structure which contains JSHint's results. var myData = JSHINT.data(); It returns a structure with this form: { errors: [ { line: NUMBER, character: NUMBER, reason: STRING, evidence: STRING } ], functions: [ name: STRING, line: NUMBER, last: NUMBER, param: [ STRING ], closure: [ STRING ], var: [ STRING ], exception: [ STRING ], outer: [ STRING ], unused: [ STRING ], global: [ STRING ], label: [ STRING ] ], globals: [ STRING ], member: { STRING: NUMBER }, unused: [ { name: STRING, line: NUMBER } ], implieds: [ { name: STRING, line: NUMBER } ], urls: [ STRING ], json: BOOLEAN } Empty arrays will not be included. */ /*jshint evil: true, nomen: false, onevar: false, regexp: false, strict: true, boss: true, undef: true, maxlen: 100, indent:4 */ /*members "\b", "\t", "\n", "\f", "\r", "!=", "!==", "\"", "%", "(begin)", "(breakage)", "(context)", "(error)", "(global)", "(identifier)", "(last)", "(line)", "(loopage)", "(name)", "(onevar)", "(params)", "(scope)", "(statement)", "(verb)", "*", "+", "++", "-", "--", "\/", "<", "<=", "==", "===", ">", ">=", $, $$, $A, $F, $H, $R, $break, $continue, $w, Abstract, Ajax, __filename, __dirname, ActiveXObject, Array, ArrayBuffer, ArrayBufferView, Audio, Autocompleter, Assets, Boolean, Builder, Buffer, Browser, COM, CScript, Canvas, CustomAnimation, Class, Control, Chain, Color, Cookie, Core, DataView, Date, Debug, Draggable, Draggables, Droppables, Document, DomReady, DOMReady, DOMParser, Drag, E, Enumerator, Enumerable, Element, Elements, Error, Effect, EvalError, Event, Events, FadeAnimation, Field, Flash, Float32Array, Float64Array, Form, FormField, Frame, FormData, Function, Fx, GetObject, Group, Hash, HotKey, HTMLElement, HTMLAnchorElement, HTMLBaseElement, HTMLBlockquoteElement, HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLCanvasElement, HTMLDirectoryElement, HTMLDivElement, HTMLDListElement, HTMLFieldSetElement, HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, HTMLLabelElement, HTMLLayerElement, HTMLLegendElement, HTMLLIElement, HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, HtmlTable, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement, HTMLVideoElement, Iframe, IframeShim, Image, Int16Array, Int32Array, Int8Array, Insertion, InputValidator, JSON, Keyboard, Locale, LN10, LN2, LOG10E, LOG2E, MAX_VALUE, MIN_VALUE, Mask, Math, MenuItem, MessageChannel, MessageEvent, MessagePort, MoveAnimation, MooTools, Native, NEGATIVE_INFINITY, Number, Object, ObjectRange, Option, Options, OverText, PI, POSITIVE_INFINITY, PeriodicalExecuter, Point, Position, Prototype, RangeError, Rectangle, ReferenceError, RegExp, ResizeAnimation, Request, RotateAnimation, SQRT1_2, SQRT2, ScrollBar, ScriptEngine, ScriptEngineBuildVersion, ScriptEngineMajorVersion, ScriptEngineMinorVersion, Scriptaculous, Scroller, Slick, Slider, Selector, SharedWorker, String, Style, SyntaxError, Sortable, Sortables, SortableObserver, Sound, Spinner, System, Swiff, Text, TextArea, Template, Timer, Tips, Type, TypeError, Toggle, Try, "use strict", unescape, URI, URIError, URL, VBArray, WSH, WScript, XDomainRequest, Web, Window, XMLDOM, XMLHttpRequest, XMLSerializer, XPathEvaluator, XPathException, XPathExpression, XPathNamespace, XPathNSResolver, XPathResult, "\\", a, addEventListener, address, alert, apply, applicationCache, arguments, arity, asi, atob, b, basic, basicToken, bitwise, block, blur, boolOptions, boss, browser, btoa, c, call, callee, caller, cases, charAt, charCodeAt, character, clearInterval, clearTimeout, close, closed, closure, comment, condition, confirm, console, constructor, content, couch, create, css, curly, d, data, datalist, dd, debug, decodeURI, decodeURIComponent, defaultStatus, defineClass, deserialize, devel, document, dojo, dijit, dojox, define, else, emit, encodeURI, encodeURIComponent, entityify, eqeqeq, eqnull, errors, es5, escape, esnext, eval, event, evidence, evil, ex, exception, exec, exps, expr, exports, FileReader, first, floor, focus, forin, fragment, frames, from, fromCharCode, fud, funcscope, funct, function, functions, g, gc, getComputedStyle, getRow, getter, getterToken, GLOBAL, global, globals, globalstrict, hasOwnProperty, help, history, i, id, identifier, immed, implieds, importPackage, include, indent, indexOf, init, ins, instanceOf, isAlpha, isApplicationRunning, isArray, isDigit, isFinite, isNaN, iterator, java, join, jshint, JSHINT, json, jquery, jQuery, keys, label, labelled, last, lastsemic, laxbreak, laxcomma, latedef, lbp, led, left, length, line, load, loadClass, localStorage, location, log, loopfunc, m, match, maxerr, maxlen, member,message, meta, module, moveBy, moveTo, mootools, multistr, name, navigator, new, newcap, noarg, node, noempty, nomen, nonew, nonstandard, nud, onbeforeunload, onblur, onerror, onevar, onecase, onfocus, onload, onresize, onunload, open, openDatabase, openURL, opener, opera, options, outer, param, parent, parseFloat, parseInt, passfail, plusplus, predef, print, process, prompt, proto, prototype, prototypejs, provides, push, quit, range, raw, reach, reason, regexp, readFile, readUrl, regexdash, removeEventListener, replace, report, require, reserved, resizeBy, resizeTo, resolvePath, resumeUpdates, respond, rhino, right, runCommand, scroll, screen, scripturl, scrollBy, scrollTo, scrollbar, search, seal, send, serialize, sessionStorage, setInterval, setTimeout, setter, setterToken, shift, slice, smarttabs, sort, spawn, split, stack, status, start, strict, sub, substr, supernew, shadow, supplant, sum, sync, test, toLowerCase, toString, toUpperCase, toint32, token, top, trailing, type, typeOf, Uint16Array, Uint32Array, Uint8Array, undef, undefs, unused, urls, validthis, value, valueOf, var, version, WebSocket, withstmt, white, window, Worker, wsh*/ /*global exports: false */ // We build the application inside a function so that we produce only a single // global variable. That function will be invoked immediately, and its return // value is the JSHINT function itself. var JSHINT = (function () { var anonname, // The guessed name for anonymous functions. // These are operators that should not be used with the ! operator. bang = { '<' : true, '<=' : true, '==' : true, '===': true, '!==': true, '!=' : true, '>' : true, '>=' : true, '+' : true, '-' : true, '*' : true, '/' : true, '%' : true }, // These are the JSHint boolean options. boolOptions = { asi : true, // if automatic semicolon insertion should be tolerated bitwise : true, // if bitwise operators should not be allowed boss : true, // if advanced usage of assignments should be allowed browser : true, // if the standard browser globals should be predefined couch : true, // if CouchDB globals should be predefined curly : true, // if curly braces around all blocks should be required debug : true, // if debugger statements should be allowed devel : true, // if logging globals should be predefined (console, // alert, etc.) dojo : true, // if Dojo Toolkit globals should be predefined eqeqeq : true, // if === should be required eqnull : true, // if == null comparisons should be tolerated es5 : true, // if ES5 syntax should be allowed esnext : true, // if es.next specific syntax should be allowed evil : true, // if eval should be allowed expr : true, // if ExpressionStatement should be allowed as Programs forin : true, // if for in statements must filter funcscope : true, // if only function scope should be used for scope tests globalstrict: true, // if global should be allowed (also // enables 'strict') immed : true, // if immediate invocations must be wrapped in parens iterator : true, // if the `__iterator__` property should be allowed jquery : true, // if jQuery globals should be predefined lastsemic : true, // if semicolons may be ommitted for the trailing // statements inside of a one-line blocks. latedef : true, // if the use before definition should not be tolerated laxbreak : true, // if line breaks should not be checked laxcomma : true, // if line breaks should not be checked around commas loopfunc : true, // if functions should be allowed to be defined within // loops mootools : true, // if MooTools globals should be predefined multistr : true, // allow multiline strings newcap : true, // if constructor names must be capitalized noarg : true, // if arguments.caller and arguments.callee should be // disallowed node : true, // if the Node.js environment globals should be // predefined noempty : true, // if empty blocks should be disallowed nonew : true, // if using `new` for side-effects should be disallowed nonstandard : true, // if non-standard (but widely adopted) globals should // be predefined nomen : true, // if names should be checked onevar : true, // if only one var statement per function should be // allowed onecase : true, // if one case switch statements should be allowed passfail : true, // if the scan should stop on first error plusplus : true, // if increment/decrement should not be allowed proto : true, // if the `__proto__` property should be allowed prototypejs : true, // if Prototype and Scriptaculous globals should be // predefined regexdash : true, // if unescaped first/last dash (-) inside brackets // should be tolerated regexp : true, // if the . should not be allowed in regexp literals rhino : true, // if the Rhino environment globals should be predefined undef : true, // if variables should be declared before used scripturl : true, // if script-targeted URLs should be tolerated shadow : true, // if variable shadowing should be tolerated smarttabs : true, // if smarttabs should be tolerated // (http://www.emacswiki.org/emacs/SmartTabs) strict : true, // require the pragma sub : true, // if all forms of subscript notation are tolerated supernew : true, // if `new function () { ... };` and `new Object;` // should be tolerated trailing : true, // if trailing whitespace rules apply validthis : true, // if 'this' inside a non-constructor function is valid. // This is a function scoped option only. withstmt : true, // if with statements should be allowed white : true, // if strict whitespace rules apply wsh : true // if the Windows Scripting Host environment globals // should be predefined }, // These are the JSHint options that can take any value // (we use this object to detect invalid options) valOptions = { maxlen: false, indent: false, maxerr: false, predef: false }, // browser contains a set of global names which are commonly provided by a // web browser environment. browser = { ArrayBuffer : false, ArrayBufferView : false, Audio : false, addEventListener : false, applicationCache : false, atob : false, blur : false, btoa : false, clearInterval : false, clearTimeout : false, close : false, closed : false, DataView : false, DOMParser : false, defaultStatus : false, document : false, event : false, FileReader : false, Float32Array : false, Float64Array : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement : false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement : false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement : false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Int16Array : false, Int32Array : false, Int8Array : false, Image : false, length : false, localStorage : false, location : false, MessageChannel : false, MessageEvent : false, MessagePort : false, moveBy : false, moveTo : false, name : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, print : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, top : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, WebSocket : false, window : false, Worker : false, XMLHttpRequest : false, XMLSerializer : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }, couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }, devel = { alert : false, confirm : false, console : false, Debug : false, opera : false, prompt : false }, dojo = { dojo : false, dijit : false, dojox : false, define : false, "require" : false }, escapes = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '/' : '\\/', '\\': '\\\\' }, funct, // The current function functionicity = [ 'closure', 'exception', 'global', 'label', 'outer', 'unused', 'var' ], functions, // All of the functions global, // The global scope implied, // Implied globals inblock, indent, jsonmode, jquery = { '$' : false, jQuery : false }, lines, lookahead, member, membersOnly, mootools = { '$' : false, '$$' : false, Assets : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, Iframe : false, IframeShim : false, InputValidator : false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }, nexttoken, node = { __filename : false, __dirname : false, Buffer : false, console : false, exports : false, GLOBAL : false, global : false, module : false, process : false, require : false, setTimeout : false, clearTimeout : false, setInterval : false, clearInterval : false }, noreach, option, predefined, // Global variables defined by option prereg, prevtoken, prototypejs = { '$' : false, '$$' : false, '$A' : false, '$F' : false, '$H' : false, '$R' : false, '$break' : false, '$continue' : false, '$w' : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }, rhino = { defineClass : false, deserialize : false, gc : false, help : false, importPackage: false, "java" : false, load : false, loadClass : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }, scope, // The current scope stack, // standard contains the global names that are provided by the // ECMAScript standard. standard = { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, 'eval' : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, JSON : false, Math : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, String : false, SyntaxError : false, TypeError : false, URIError : false }, // widely adopted global names that are not part of ECMAScript standard nonstandard = { escape : false, unescape : false }, standard_member = { E : true, LN2 : true, LN10 : true, LOG2E : true, LOG10E : true, MAX_VALUE : true, MIN_VALUE : true, NEGATIVE_INFINITY : true, PI : true, POSITIVE_INFINITY : true, SQRT1_2 : true, SQRT2 : true }, directive, syntax = {}, tab, token, urls, useESNextSyntax, warnings, wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; // Regular expressions. Some of these are stupidly long. var ax, cx, tx, nx, nxg, lx, ix, jx, ft; (function () { /*jshint maxlen:300 */ // unsafe comment or string ax = /@cc|<\/?|script|\]\s*\]|<\s*!|&lt/i; // unsafe characters that are silently deleted by one or more browsers cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; // token tx = /^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/(\*(jshint|jslint|members?|global)?|=|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/; // characters in strings that need escapement nx = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; nxg = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // star slash lx = /\*\/|\/\*/; // identifier ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; // javascript url jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i; // catches /* falls through */ comments ft = /^\s*\/\*\s*falls\sthrough\s*\*\/\s*$/; }()); function F() {} // Used by Object.create function is_own(object, name) { // The object.hasOwnProperty method fails when the property under consideration // is named 'hasOwnProperty'. So we have to use this more convoluted form. return Object.prototype.hasOwnProperty.call(object, name); } function checkOption(name, t) { if (valOptions[name] === undefined && boolOptions[name] === undefined) { warning("Bad option: '" + name + "'.", t); } } // Provide critical ES5 functions to ES3. if (typeof Array.isArray !== 'function') { Array.isArray = function (o) { return Object.prototype.toString.apply(o) === '[object Array]'; }; } if (typeof Object.create !== 'function') { Object.create = function (o) { F.prototype = o; return new F(); }; } if (typeof Object.keys !== 'function') { Object.keys = function (o) { var a = [], k; for (k in o) { if (is_own(o, k)) { a.push(k); } } return a; }; } // Non standard methods if (typeof String.prototype.entityify !== 'function') { String.prototype.entityify = function () { return this .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }; } if (typeof String.prototype.isAlpha !== 'function') { String.prototype.isAlpha = function () { return (this >= 'a' && this <= 'z\uffff') || (this >= 'A' && this <= 'Z\uffff'); }; } if (typeof String.prototype.isDigit !== 'function') { String.prototype.isDigit = function () { return (this >= '0' && this <= '9'); }; } if (typeof String.prototype.supplant !== 'function') { String.prototype.supplant = function (o) { return this.replace(/\{([^{}]*)\}/g, function (a, b) { var r = o[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); }; } if (typeof String.prototype.name !== 'function') { String.prototype.name = function () { // If the string looks like an identifier, then we can return it as is. // If the string contains no control characters, no quote characters, and no // backslash characters, then we can simply slap some quotes around it. // Otherwise we must also replace the offending characters with safe // sequences. if (ix.test(this)) { return this; } if (nx.test(this)) { return '"' + this.replace(nxg, function (a) { var c = escapes[a]; if (c) { return c; } return '\\u' + ('0000' + a.charCodeAt().toString(16)).slice(-4); }) + '"'; } return '"' + this + '"'; }; } function combine(t, o) { var n; for (n in o) { if (is_own(o, n)) { t[n] = o[n]; } } } function assume() { if (option.couch) { combine(predefined, couch); } if (option.rhino) { combine(predefined, rhino); } if (option.prototypejs) { combine(predefined, prototypejs); } if (option.node) { combine(predefined, node); option.globalstrict = true; } if (option.devel) { combine(predefined, devel); } if (option.dojo) { combine(predefined, dojo); } if (option.browser) { combine(predefined, browser); } if (option.nonstandard) { combine(predefined, nonstandard); } if (option.jquery) { combine(predefined, jquery); } if (option.mootools) { combine(predefined, mootools); } if (option.wsh) { combine(predefined, wsh); } if (option.esnext) { useESNextSyntax(); } if (option.globalstrict && option.strict !== false) { option.strict = true; } } // Produce an error warning. function quit(message, line, chr) { var percentage = Math.floor((line / lines.length) * 100); throw { name: 'JSHintError', line: line, character: chr, message: message + " (" + percentage + "% scanned).", raw: message }; } function isundef(scope, m, t, a) { return JSHINT.undefs.push([scope, m, t, a]); } function warning(m, t, a, b, c, d) { var ch, l, w; t = t || nexttoken; if (t.id === '(end)') { // `~ t = token; } l = t.line || 0; ch = t.from || 0; w = { id: '(error)', raw: m, evidence: lines[l - 1] || '', line: l, character: ch, a: a, b: b, c: c, d: d }; w.reason = m.supplant(w); JSHINT.errors.push(w); if (option.passfail) { quit('Stopping. ', l, ch); } warnings += 1; if (warnings >= option.maxerr) { quit("Too many errors.", l, ch); } return w; } function warningAt(m, l, ch, a, b, c, d) { return warning(m, { line: l, from: ch }, a, b, c, d); } function error(m, t, a, b, c, d) { var w = warning(m, t, a, b, c, d); } function errorAt(m, l, ch, a, b, c, d) { return error(m, { line: l, from: ch }, a, b, c, d); } // lexical analysis and token construction var lex = (function lex() { var character, from, line, s; // Private lex methods function nextLine() { var at, tw; // trailing whitespace check if (line >= lines.length) return false; character = 1; s = lines[line]; line += 1; // If smarttabs option is used check for spaces followed by tabs only. // Otherwise check for any occurence of mixed tabs and spaces. if (option.smarttabs) at = s.search(/ \t/); else at = s.search(/ \t|\t /); if (at >= 0) warningAt("Mixed spaces and tabs.", line, at + 1); s = s.replace(/\t/g, tab); at = s.search(cx); if (at >= 0) warningAt("Unsafe character.", line, at); if (option.maxlen && option.maxlen < s.length) warningAt("Line too long.", line, s.length); // Check for trailing whitespaces tw = option.trailing && s.match(/^(.*?)\s+$/); if (tw && !/^\s+$/.test(s)) { warningAt("Trailing whitespace.", line, tw[1].length + 1); } return true; } // Produce a token object. The token inherits from a syntax symbol. function it(type, value) { var i, t; if (type === '(color)' || type === '(range)') { t = {type: type}; } else if (type === '(punctuator)' || (type === '(identifier)' && is_own(syntax, value))) { t = syntax[value] || syntax['(error)']; } else { t = syntax[type]; } t = Object.create(t); if (type === '(string)' || type === '(range)') { if (!option.scripturl && jx.test(value)) { warningAt("Script URL.", line, from); } } if (type === '(identifier)') { t.identifier = true; if (value === '__proto__' && !option.proto) { warningAt("The '{a}' property is deprecated.", line, from, value); } else if (value === '__iterator__' && !option.iterator) { warningAt("'{a}' is only available in JavaScript 1.7.", line, from, value); } else if (option.nomen && (value.charAt(0) === '_' || value.charAt(value.length - 1) === '_')) { if (!option.node || token.id === '.' || (value !== '__dirname' && value !== '__filename')) { warningAt("Unexpected {a} in '{b}'.", line, from, "dangling '_'", value); } } } t.value = value; t.line = line; t.character = character; t.from = from; i = t.id; if (i !== '(endline)') { prereg = i && (('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) || i === 'return' || i === 'case'); } return t; } // Public lex methods return { init: function (source) { if (typeof source === 'string') { lines = source .replace(/\r\n/g, '\n') .replace(/\r/g, '\n') .split('\n'); } else { lines = source; } // If the first line is a shebang (#!), make it a blank and move on. // Shebangs are used by Node scripts. if (lines[0] && lines[0].substr(0, 2) === '#!') lines[0] = ''; line = 0; nextLine(); from = 1; }, range: function (begin, end) { var c, value = ''; from = character; if (s.charAt(0) !== begin) { errorAt("Expected '{a}' and instead saw '{b}'.", line, character, begin, s.charAt(0)); } for (;;) { s = s.slice(1); character += 1; c = s.charAt(0); switch (c) { case '': errorAt("Missing '{a}'.", line, character, c); break; case end: s = s.slice(1); character += 1; return it('(range)', value); case '\\': warningAt("Unexpected '{a}'.", line, character, c); } value += c; } }, // token -- this is called by advance to get the next token token: function () { var b, c, captures, d, depth, high, i, l, low, q, t, isLiteral, isInRange, n; function match(x) { var r = x.exec(s), r1; if (r) { l = r[0].length; r1 = r[1]; c = r1.charAt(0); s = s.substr(l); from = character + l - r1.length; character += l; return r1; } } function string(x) { var c, j, r = '', allowNewLine = false; if (jsonmode && x !== '"') { warningAt("Strings must use doublequote.", line, character); } function esc(n) { var i = parseInt(s.substr(j + 1, n), 16); j += n; if (i >= 32 && i <= 126 && i !== 34 && i !== 92 && i !== 39) { warningAt("Unnecessary escapement.", line, character); } character += n; c = String.fromCharCode(i); } j = 0; unclosedString: for (;;) { while (j >= s.length) { j = 0; var cl = line, cf = from; if (!nextLine()) { errorAt("Unclosed string.", cl, cf); break unclosedString; } if (allowNewLine) { allowNewLine = false; } else { warningAt("Unclosed string.", cl, cf); } } c = s.charAt(j); if (c === x) { character += 1; s = s.substr(j + 1); return it('(string)', r, x); } if (c < ' ') { if (c === '\n' || c === '\r') { break; } warningAt("Control character in string: {a}.", line, character + j, s.slice(0, j)); } else if (c === '\\') { j += 1; character += 1; c = s.charAt(j); n = s.charAt(j + 1); switch (c) { case '\\': case '"': case '/': break; case '\'': if (jsonmode) { warningAt("Avoid \\'.", line, character); } break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case '0': c = '\0'; // Octal literals fail in strict mode // check if the number is between 00 and 07 // where 'n' is the token next to 'c' if (n >= 0 && n <= 7 && directive["use strict"]) { warningAt( "Octal literals are not allowed in strict mode.", line, character); } break; case 'u': esc(4); break; case 'v': if (jsonmode) { warningAt("Avoid \\v.", line, character); } c = '\v'; break; case 'x': if (jsonmode) { warningAt("Avoid \\x-.", line, character); } esc(2); break; case '': // last character is escape character // always allow new line if escaped, but show // warning if option is not set allowNewLine = true; if (option.multistr) { if (jsonmode) { warningAt("Avoid EOL escapement.", line, character); } c = ''; character -= 1; break; } warningAt("Bad escapement of EOL. Use option multistr if needed.", line, character); break; default: warningAt("Bad escapement.", line, character); } } r += c; character += 1; j += 1; } } for (;;) { if (!s) { return it(nextLine() ? '(endline)' : '(end)', ''); } t = match(tx); if (!t) { t = ''; c = ''; while (s && s < '!') { s = s.substr(1); } if (s) { errorAt("Unexpected '{a}'.", line, character, s.substr(0, 1)); s = ''; } } else { // identifier if (c.isAlpha() || c === '_' || c === '$') { return it('(identifier)', t); } // number if (c.isDigit()) { if (!isFinite(Number(t))) { warningAt("Bad number '{a}'.", line, character, t); } if (s.substr(0, 1).isAlpha()) { warningAt("Missing space after '{a}'.", line, character, t); } if (c === '0') { d = t.substr(1, 1); if (d.isDigit()) { if (token.id !== '.') { warningAt("Don't use extra leading zeros '{a}'.", line, character, t); } } else if (jsonmode && (d === 'x' || d === 'X')) { warningAt("Avoid 0x-. '{a}'.", line, character, t); } } if (t.substr(t.length - 1) === '.') { warningAt( "A trailing decimal point can be confused with a dot '{a}'.", line, character, t); } return it('(number)', t); } switch (t) { // string case '"': case "'": return string(t); // // comment case '//': s = ''; token.comment = true; break; // /* comment case '/*': for (;;) { i = s.search(lx); if (i >= 0) { break; } if (!nextLine()) { errorAt("Unclosed comment.", line, character); } } character += i + 2; if (s.substr(i, 1) === '/') { errorAt("Nested comment.", line, character); } s = s.substr(i + 2); token.comment = true; break; // /*members /*jshint /*global case '/*members': case '/*member': case '/*jshint': case '/*jslint': case '/*global': case '*/': return { value: t, type: 'special', line: line, character: character, from: from }; case '': break; // / case '/': if (token.id === '/=') { errorAt("A regular expression literal can be confused with '/='.", line, from); } if (prereg) { depth = 0; captures = 0; l = 0; for (;;) { b = true; c = s.charAt(l); l += 1; switch (c) { case '': errorAt("Unclosed regular expression.", line, from); return quit('Stopping.', line, from); case '/': if (depth > 0) { warningAt("{a} unterminated regular expression " + "group(s).", line, from + l, depth); } c = s.substr(0, l - 1); q = { g: true, i: true, m: true }; while (q[s.charAt(l)] === true) { q[s.charAt(l)] = false; l += 1; } character += l; s = s.substr(l); q = s.charAt(0); if (q === '/' || q === '*') { errorAt("Confusing regular expression.", line, from); } return it('(regexp)', c); case '\\': c = s.charAt(l); if (c < ' ') { warningAt( "Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt( "Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; break; case '(': depth += 1; b = false; if (s.charAt(l) === '?') { l += 1; switch (s.charAt(l)) { case ':': case '=': case '!': l += 1; break; default: warningAt( "Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l)); } } else { captures += 1; } break; case '|': b = false; break; case ')': if (depth === 0) { warningAt("Unescaped '{a}'.", line, from + l, ')'); } else { depth -= 1; } break; case ' ': q = 1; while (s.charAt(l) === ' ') { l += 1; q += 1; } if (q > 1) { warningAt( "Spaces are hard to count. Use {{a}}.", line, from + l, q); } break; case '[': c = s.charAt(l); if (c === '^') { l += 1; if (option.regexp) { warningAt("Insecure '{a}'.", line, from + l, c); } else if (s.charAt(l) === ']') { errorAt("Unescaped '{a}'.", line, from + l, '^'); } } if (c === ']') { warningAt("Empty class.", line, from + l - 1); } isLiteral = false; isInRange = false; klass: do { c = s.charAt(l); l += 1; switch (c) { case '[': case '^': warningAt("Unescaped '{a}'.", line, from + l, c); if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '-': if (isLiteral && !isInRange) { isLiteral = false; isInRange = true; } else if (isInRange) { isInRange = false; } else if (s.charAt(l) === ']') { isInRange = true; } else { if (option.regexdash !== (l === 2 || (l === 3 && s.charAt(1) === '^'))) { warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); } isLiteral = true; } break; case ']': if (isInRange && !option.regexdash) { warningAt("Unescaped '{a}'.", line, from + l - 1, '-'); } break klass; case '\\': c = s.charAt(l); if (c < ' ') { warningAt( "Unexpected control character in regular expression.", line, from + l); } else if (c === '<') { warningAt( "Unexpected escaped character '{a}' in regular expression.", line, from + l, c); } l += 1; // \w, \s and \d are never part of a character range if (/[wsd]/i.test(c)) { if (isInRange) { warningAt("Unescaped '{a}'.", line, from + l, '-'); isInRange = false; } isLiteral = false; } else if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '/': warningAt("Unescaped '{a}'.", line, from + l - 1, '/'); if (isInRange) { isInRange = false; } else { isLiteral = true; } break; case '<': if (isInRange) { isInRange = false; } else { isLiteral = true; } break; default: if (isInRange) { isInRange = false; } else { isLiteral = true; } } } while (c); break; case '.': if (option.regexp) { warningAt("Insecure '{a}'.", line, from + l, c); } break; case ']': case '?': case '{': case '}': case '+': case '*': warningAt("Unescaped '{a}'.", line, from + l, c); } if (b) { switch (s.charAt(l)) { case '?': case '+': case '*': l += 1; if (s.charAt(l) === '?') { l += 1; } break; case '{': l += 1; c = s.charAt(l); if (c < '0' || c > '9') { warningAt( "Expected a number and instead saw '{a}'.", line, from + l, c); } l += 1; low = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; low = +c + (low * 10); } high = low; if (c === ',') { l += 1; high = Infinity; c = s.charAt(l); if (c >= '0' && c <= '9') { l += 1; high = +c; for (;;) { c = s.charAt(l); if (c < '0' || c > '9') { break; } l += 1; high = +c + (high * 10); } } } if (s.charAt(l) !== '}') { warningAt( "Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c); } else { l += 1; } if (s.charAt(l) === '?') { l += 1; } if (low > high) { warningAt( "'{a}' should not be greater than '{b}'.", line, from + l, low, high); } } } } c = s.substr(0, l - 1); character += l; s = s.substr(l); return it('(regexp)', c); } return it('(punctuator)', t); // punctuator case '#': return it('(punctuator)', t); default: return it('(punctuator)', t); } } } } }; }()); function addlabel(t, type) { if (t === 'hasOwnProperty') { warning("'hasOwnProperty' is a really bad name."); } // Define t in the current function in the current scope. if (is_own(funct, t) && !funct['(global)']) { if (funct[t] === true) { if (option.latedef) warning("'{a}' was used before it was defined.", nexttoken, t); } else { if (!option.shadow && type !== "exception") warning("'{a}' is already defined.", nexttoken, t); } } funct[t] = type; if (funct['(global)']) { global[t] = funct; if (is_own(implied, t)) { if (option.latedef) warning("'{a}' was used before it was defined.", nexttoken, t); delete implied[t]; } } else { scope[t] = funct; } } function doOption() { var b, obj, filter, o = nexttoken.value, t, v; switch (o) { case '*/': error("Unbegun comment."); break; case '/*members': case '/*member': o = '/*members'; if (!membersOnly) { membersOnly = {}; } obj = membersOnly; break; case '/*jshint': case '/*jslint': obj = option; filter = boolOptions; break; case '/*global': obj = predefined; break; default: error("What?"); } t = lex.token(); loop: for (;;) { for (;;) { if (t.type === 'special' && t.value === '*/') { break loop; } if (t.id !== '(endline)' && t.id !== ',') { break; } t = lex.token(); } if (t.type !== '(string)' && t.type !== '(identifier)' && o !== '/*members') { error("Bad option.", t); } v = lex.token(); if (v.id === ':') { v = lex.token(); if (obj === membersOnly) { error("Expected '{a}' and instead saw '{b}'.", t, '*/', ':'); } if (o === '/*jshint') { checkOption(t.value, t); } if (t.value === 'indent' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.white = true; obj.indent = b; } else if (t.value === 'maxerr' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.maxerr = b; } else if (t.value === 'maxlen' && (o === '/*jshint' || o === '/*jslint')) { b = +v.value; if (typeof b !== 'number' || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { error("Expected a small integer and instead saw '{a}'.", v, v.value); } obj.maxlen = b; } else if (t.value === 'validthis') { if (funct['(global)']) { error("Option 'validthis' can't be used in a global scope."); } else { if (v.value === 'true' || v.value === 'false') obj[t.value] = v.value === 'true'; else error("Bad option value.", v); } } else if (v.value === 'true') { obj[t.value] = true; } else if (v.value === 'false') { obj[t.value] = false; } else { error("Bad option value.", v); } t = lex.token(); } else { if (o === '/*jshint' || o === '/*jslint') { error("Missing option value.", t); } obj[t.value] = false; t = v; } } if (filter) { assume(); } } // We need a peek function. If it has an argument, it peeks that much farther // ahead. It is used to distinguish // for ( var i in ... // from // for ( var i = ... function peek(p) { var i = p || 0, j = 0, t; while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } return t; } // Produce the next token. It looks for programming errors. function advance(id, t) { switch (token.id) { case '(number)': if (nexttoken.id === '.') { warning("A dot following a number can be confused with a decimal point.", token); } break; case '-': if (nexttoken.id === '-' || nexttoken.id === '--') { warning("Confusing minusses."); } break; case '+': if (nexttoken.id === '+' || nexttoken.id === '++') { warning("Confusing plusses."); } break; } if (token.type === '(string)' || token.identifier) { anonname = token.value; } if (id && nexttoken.id !== id) { if (t) { if (nexttoken.id === '(end)') { warning("Unmatched '{a}'.", t, t.id); } else { warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", nexttoken, id, t.id, t.line, nexttoken.value); } } else if (nexttoken.type !== '(identifier)' || nexttoken.value !== id) { warning("Expected '{a}' and instead saw '{b}'.", nexttoken, id, nexttoken.value); } } prevtoken = token; token = nexttoken; for (;;) { nexttoken = lookahead.shift() || lex.token(); if (nexttoken.id === '(end)' || nexttoken.id === '(error)') { return; } if (nexttoken.type === 'special') { doOption(); } else { if (nexttoken.id !== '(endline)') { break; } } } } // This is the heart of JSHINT, the Pratt parser. In addition to parsing, it // is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is // like .nud except that it is only used on the first token of a statement. // Having .fud makes it much easier to define statement-oriented languages like // JavaScript. I retained Pratt's nomenclature. // .nud Null denotation // .fud First null denotation // .led Left denotation // lbp Left binding power // rbp Right binding power // They are elements of the parsing method called Top Down Operator Precedence. function expression(rbp, initial) { var left, isArray = false, isObject = false; if (nexttoken.id === '(end)') error("Unexpected early end of program.", token); advance(); if (initial) { anonname = 'anonymous'; funct['(verb)'] = token.value; } if (initial === true && token.fud) { left = token.fud(); } else { if (token.nud) { left = token.nud(); } else { if (nexttoken.type === '(number)' && token.id === '.') { warning("A leading decimal point can be confused with a dot: '.{a}'.", token, nexttoken.value); advance(); return token; } else { error("Expected an identifier and instead saw '{a}'.", token, token.id); } } while (rbp < nexttoken.lbp) { isArray = token.value === 'Array'; isObject = token.value === 'Object'; advance(); if (isArray && token.id === '(' && nexttoken.id === ')') warning("Use the array literal notation [].", token); if (isObject && token.id === '(' && nexttoken.id === ')') warning("Use the object literal notation {}.", token); if (token.led) { left = token.led(left); } else { error("Expected an operator and instead saw '{a}'.", token, token.id); } } } return left; } // Functions for conformance of style. function adjacent(left, right) { left = left || token; right = right || nexttoken; if (option.white) { if (left.character !== right.from && left.line === right.line) { left.from += (left.character - left.from); warning("Unexpected space after '{a}'.", left, left.value); } } } function nobreak(left, right) { left = left || token; right = right || nexttoken; if (option.white && (left.character !== right.from || left.line !== right.line)) { warning("Unexpected space before '{a}'.", right, right.value); } } function nospace(left, right) { left = left || token; right = right || nexttoken; if (option.white && !left.comment) { if (left.line === right.line) { adjacent(left, right); } } } function nonadjacent(left, right) { if (option.white) { left = left || token; right = right || nexttoken; if (left.line === right.line && left.character === right.from) { left.from += (left.character - left.from); warning("Missing space after '{a}'.", left, left.value); } } } function nobreaknonadjacent(left, right) { left = left || token; right = right || nexttoken; if (!option.laxbreak && left.line !== right.line) { warning("Bad line breaking before '{a}'.", right, right.id); } else if (option.white) { left = left || token; right = right || nexttoken; if (left.character === right.from) { left.from += (left.character - left.from); warning("Missing space after '{a}'.", left, left.value); } } } function indentation(bias) { var i; if (option.white && nexttoken.id !== '(end)') { i = indent + (bias || 0); if (nexttoken.from !== i) { warning( "Expected '{a}' to have an indentation at {b} instead at {c}.", nexttoken, nexttoken.value, i, nexttoken.from); } } } function nolinebreak(t) { t = t || token; if (t.line !== nexttoken.line) { warning("Line breaking error '{a}'.", t, t.value); } } function comma() { if (token.line !== nexttoken.line) { if (!option.laxcomma) { if (comma.first) { warning("Comma warnings can be turned off with 'laxcomma'"); comma.first = false; } warning("Bad line breaking before '{a}'.", token, nexttoken.id); } } else if (!token.comment && token.character !== nexttoken.from && option.white) { token.from += (token.character - token.from); warning("Unexpected space after '{a}'.", token, token.value); } advance(','); nonadjacent(token, nexttoken); } // Functional constructors for making the symbols that will be inherited by // tokens. function symbol(s, p) { var x = syntax[s]; if (!x || typeof x !== 'object') { syntax[s] = x = { id: s, lbp: p, value: s }; } return x; } function delim(s) { return symbol(s, 0); } function stmt(s, f) { var x = delim(s); x.identifier = x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; } function reserveName(x) { var c = x.id.charAt(0); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { x.identifier = x.reserved = true; } return x; } function prefix(s, f) { var x = symbol(s, 150); reserveName(x); x.nud = (typeof f === 'function') ? f : function () { this.right = expression(150); this.arity = 'unary'; if (this.id === '++' || this.id === '--') { if (option.plusplus) { warning("Unexpected use of '{a}'.", this, this.id); } else if ((!this.right.identifier || this.right.reserved) && this.right.id !== '.' && this.right.id !== '[') { warning("Bad operand.", this); } } return this; }; return x; } function type(s, f) { var x = delim(s); x.type = s; x.nud = f; return x; } function reserve(s, f) { var x = type(s, f); x.identifier = x.reserved = true; return x; } function reservevar(s, v) { return reserve(s, function () { if (typeof v === 'function') { v(this); } return this; }); } function infix(s, f, p, w) { var x = symbol(s, p); reserveName(x); x.led = function (left) { if (!w) { nobreaknonadjacent(prevtoken, token); nonadjacent(token, nexttoken); } if (s === "in" && left.id === "!") { warning("Confusing use of '{a}'.", left, '!'); } if (typeof f === 'function') { return f(left, this); } else { this.left = left; this.right = expression(p); return this; } }; return x; } function relation(s, f) { var x = symbol(s, 100); x.led = function (left) { nobreaknonadjacent(prevtoken, token); nonadjacent(token, nexttoken); var right = expression(100); if ((left && left.id === 'NaN') || (right && right.id === 'NaN')) { warning("Use the isNaN function to compare with NaN.", this); } else if (f) { f.apply(this, [left, right]); } if (left.id === '!') { warning("Confusing use of '{a}'.", left, '!'); } if (right.id === '!') { warning("Confusing use of '{a}'.", right, '!'); } this.left = left; this.right = right; return this; }; return x; } function isPoorRelation(node) { return node && ((node.type === '(number)' && +node.value === 0) || (node.type === '(string)' && node.value === '') || (node.type === 'null' && !option.eqnull) || node.type === 'true' || node.type === 'false' || node.type === 'undefined'); } function assignop(s, f) { symbol(s, 20).exps = true; return infix(s, function (left, that) { var l; that.left = left; if (predefined[left.value] === false && scope[left.value]['(global)'] === true) { warning("Read only.", left); } else if (left['function']) { warning("'{a}' is a function.", left, left.value); } if (left) { if (option.esnext && funct[left.value] === 'const') { warning("Attempting to override '{a}' which is a constant", left, left.value); } if (left.id === '.' || left.id === '[') { if (!left.left || left.left.value === 'arguments') { warning('Bad assignment.', that); } that.right = expression(19); return that; } else if (left.identifier && !left.reserved) { if (funct[left.value] === 'exception') { warning("Do not assign to the exception parameter.", left); } that.right = expression(19); return that; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment and instead saw a function invocation.", token); } } error("Bad assignment.", that); }, 20); } function bitwise(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === 'function') ? f : function (left) { if (option.bitwise) { warning("Unexpected use of '{a}'.", this, this.id); } this.left = left; this.right = expression(p); return this; }; return x; } function bitwiseassignop(s) { symbol(s, 20).exps = true; return infix(s, function (left, that) { if (option.bitwise) { warning("Unexpected use of '{a}'.", that, that.id); } nonadjacent(prevtoken, token); nonadjacent(token, nexttoken); if (left) { if (left.id === '.' || left.id === '[' || (left.identifier && !left.reserved)) { expression(19); return that; } if (left === syntax['function']) { warning( "Expected an identifier in an assignment, and instead saw a function invocation.", token); } return that; } error("Bad assignment.", that); }, 20); } function suffix(s, f) { var x = symbol(s, 150); x.led = function (left) { if (option.plusplus) { warning("Unexpected use of '{a}'.", this, this.id); } else if ((!left.identifier || left.reserved) && left.id !== '.' && left.id !== '[') { warning("Bad operand.", this); } this.left = left; return this; }; return x; } // fnparam means that this identifier is being defined as a function // argument (see identifier()) function optionalidentifier(fnparam) { if (nexttoken.identifier) { advance(); if (token.reserved && !option.es5) { // `undefined` as a function param is a common pattern to protect // against the case when somebody does `undefined = true` and // help with minification. More info: https://gist.github.com/315916 if (!fnparam || token.value !== 'undefined') { warning("Expected an identifier and instead saw '{a}' (a reserved word).", token, token.id); } } return token.value; } } // fnparam means that this identifier is being defined as a function // argument function identifier(fnparam) { var i = optionalidentifier(fnparam); if (i) { return i; } if (token.id === 'function' && nexttoken.id === '(') { warning("Missing name in function declaration."); } else { error("Expected an identifier and instead saw '{a}'.", nexttoken, nexttoken.value); } } function reachable(s) { var i = 0, t; if (nexttoken.id !== ';' || noreach) { return; } for (;;) { t = peek(i); if (t.reach) { return; } if (t.id !== '(endline)') { if (t.id === 'function') { if (!option.latedef) { break; } warning( "Inner functions should be listed at the top of the outer function.", t); break; } warning("Unreachable '{a}' after '{b}'.", t, t.value, s); break; } i += 1; } } function statement(noindent) { var i = indent, r, s = scope, t = nexttoken; if (t.id === ";") { advance(";"); return; } // Is this a labelled statement? if (t.identifier && !t.reserved && peek().id === ':') { advance(); advance(':'); scope = Object.create(s); addlabel(t.value, 'label'); if (!nexttoken.labelled) { warning("Label '{a}' on {b} statement.", nexttoken, t.value, nexttoken.value); } if (jx.test(t.value + ':')) { warning("Label '{a}' looks like a javascript url.", t, t.value); } nexttoken.label = t.value; t = nexttoken; } // Parse the statement. if (!noindent) { indentation(); } r = expression(0, true); // Look for the final semicolon. if (!t.block) { if (!option.expr && (!r || !r.exps)) { warning("Expected an assignment or function call and instead saw an expression.", token); } else if (option.nonew && r.id === '(' && r.left.id === 'new') { warning("Do not use 'new' for side effects."); } if (nexttoken.id === ',') { return comma(); } if (nexttoken.id !== ';') { if (!option.asi) { // If this is the last statement in a block that ends on // the same line *and* option lastsemic is on, ignore the warning. // Otherwise, complain about missing semicolon. if (!option.lastsemic || nexttoken.id !== '}' || nexttoken.line !== token.line) { warningAt("Missing semicolon.", token.line, token.character); } } } else { adjacent(token, nexttoken); advance(';'); nonadjacent(token, nexttoken); } } // Restore the indentation. indent = i; scope = s; return r; } function statements(startLine) { var a = [], f, p; while (!nexttoken.reach && nexttoken.id !== '(end)') { if (nexttoken.id === ';') { p = peek(); if (!p || p.id !== "(") { warning("Unnecessary semicolon."); } advance(';'); } else { a.push(statement(startLine === nexttoken.line)); } } return a; } /* * read all directives * recognizes a simple form of asi, but always * warns, if it is used */ function directives() { var i, p, pn; for (;;) { if (nexttoken.id === "(string)") { p = peek(0); if (p.id === "(endline)") { i = 1; do { pn = peek(i); i = i + 1; } while (pn.id === "(endline)"); if (pn.id !== ";") { if (pn.id !== "(string)" && pn.id !== "(number)" && pn.id !== "(regexp)" && pn.identifier !== true && pn.id !== "}") { break; } warning("Missing semicolon.", nexttoken); } else { p = pn; } } else if (p.id === "}") { // directive with no other statements, warn about missing semicolon warning("Missing semicolon.", p); } else if (p.id !== ";") { break; } indentation(); advance(); if (directive[token.value]) { warning("Unnecessary directive \"{a}\".", token, token.value); } if (token.value === "use strict") { option.newcap = true; option.undef = true; } // there's no directive negation, so always set to true directive[token.value] = true; if (p.id === ";") { advance(";"); } continue; } break; } } /* * Parses a single block. A block is a sequence of statements wrapped in * braces. * * ordinary - true for everything but function bodies and try blocks. * stmt - true if block can be a single statement (e.g. in if/for/while). * isfunc - true if block is a function body */ function block(ordinary, stmt, isfunc) { var a, b = inblock, old_indent = indent, m, s = scope, t, line, d; inblock = ordinary; if (!ordinary || !option.funcscope) scope = Object.create(scope); nonadjacent(token, nexttoken); t = nexttoken; if (nexttoken.id === '{') { advance('{'); line = token.line; if (nexttoken.id !== '}') { indent += option.indent; while (!ordinary && nexttoken.from > indent) { indent += option.indent; } if (isfunc) { m = {}; for (d in directive) { if (is_own(directive, d)) { m[d] = directive[d]; } } directives(); if (option.strict && funct['(context)']['(global)']) { if (!m["use strict"] && !directive["use strict"]) { warning("Missing \"use strict\" statement."); } } } a = statements(line); if (isfunc) { directive = m; } indent -= option.indent; if (line !== nexttoken.line) { indentation(); } } else if (line !== nexttoken.line) { indentation(); } advance('}', t); indent = old_indent; } else if (!ordinary) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, '{', nexttoken.value); } else { if (!stmt || option.curly) warning("Expected '{a}' and instead saw '{b}'.", nexttoken, '{', nexttoken.value); noreach = true; indent += option.indent; // test indentation only if statement is in new line a = [statement(nexttoken.line === token.line)]; indent -= option.indent; noreach = false; } funct['(verb)'] = null; if (!ordinary || !option.funcscope) scope = s; inblock = b; if (ordinary && option.noempty && (!a || a.length === 0)) { warning("Empty block."); } return a; } function countMember(m) { if (membersOnly && typeof membersOnly[m] !== 'boolean') { warning("Unexpected /*member '{a}'.", token, m); } if (typeof member[m] === 'number') { member[m] += 1; } else { member[m] = 1; } } function note_implied(token) { var name = token.value, line = token.line, a = implied[name]; if (typeof a === 'function') { a = false; } if (!a) { a = [line]; implied[name] = a; } else if (a[a.length - 1] !== line) { a.push(line); } } // Build the syntax table by declaring the syntactic elements of the language. type('(number)', function () { return this; }); type('(string)', function () { return this; }); syntax['(identifier)'] = { type: '(identifier)', lbp: 0, identifier: true, nud: function () { var v = this.value, s = scope[v], f; if (typeof s === 'function') { // Protection against accidental inheritance. s = undefined; } else if (typeof s === 'boolean') { f = funct; funct = functions[0]; addlabel(v, 'var'); s = funct; funct = f; } // The name is in scope and defined in the current function. if (funct === s) { // Change 'unused' to 'var', and reject labels. switch (funct[v]) { case 'unused': funct[v] = 'var'; break; case 'unction': funct[v] = 'function'; this['function'] = true; break; case 'function': this['function'] = true; break; case 'label': warning("'{a}' is a statement label.", token, v); break; } } else if (funct['(global)']) { // The name is not defined in the function. If we are in the global // scope, then we have an undefined variable. // // Operators typeof and delete do not raise runtime errors even if // the base object of a reference is null so no need to display warning // if we're inside of typeof or delete. if (option.undef && typeof predefined[v] !== 'boolean') { // Attempting to subscript a null reference will throw an // error, even within the typeof and delete operators if (!(anonname === 'typeof' || anonname === 'delete') || (nexttoken && (nexttoken.value === '.' || nexttoken.value === '['))) { isundef(funct, "'{a}' is not defined.", token, v); } } note_implied(token); } else { // If the name is already defined in the current // function, but not as outer, then there is a scope error. switch (funct[v]) { case 'closure': case 'function': case 'var': case 'unused': warning("'{a}' used out of scope.", token, v); break; case 'label': warning("'{a}' is a statement label.", token, v); break; case 'outer': case 'global': break; default: // If the name is defined in an outer function, make an outer entry, // and if it was unused, make it var. if (s === true) { funct[v] = true; } else if (s === null) { warning("'{a}' is not allowed.", token, v); note_implied(token); } else if (typeof s !== 'object') { // Operators typeof and delete do not raise runtime errors even // if the base object of a reference is null so no need to // display warning if we're inside of typeof or delete. if (option.undef) { // Attempting to subscript a null reference will throw an // error, even within the typeof and delete operators if (!(anonname === 'typeof' || anonname === 'delete') || (nexttoken && (nexttoken.value === '.' || nexttoken.value === '['))) { isundef(funct, "'{a}' is not defined.", token, v); } } funct[v] = true; note_implied(token); } else { switch (s[v]) { case 'function': case 'unction': this['function'] = true; s[v] = 'closure'; funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'var': case 'unused': s[v] = 'closure'; funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'closure': case 'parameter': funct[v] = s['(global)'] ? 'global' : 'outer'; break; case 'label': warning("'{a}' is a statement label.", token, v); } } } } return this; }, led: function () { error("Expected an operator and instead saw '{a}'.", nexttoken, nexttoken.value); } }; type('(regexp)', function () { return this; }); // ECMAScript parser delim('(endline)'); delim('(begin)'); delim('(end)').reach = true; delim('</').reach = true; delim('<!'); delim('<!--'); delim('-->'); delim('(error)').reach = true; delim('}').reach = true; delim(')'); delim(']'); delim('"').reach = true; delim("'").reach = true; delim(';'); delim(':').reach = true; delim(','); delim('#'); delim('@'); reserve('else'); reserve('case').reach = true; reserve('catch'); reserve('default').reach = true; reserve('finally'); reservevar('arguments', function (x) { if (directive['use strict'] && funct['(global)']) { warning("Strict violation.", x); } }); reservevar('eval'); reservevar('false'); reservevar('Infinity'); reservevar('NaN'); reservevar('null'); reservevar('this', function (x) { if (directive['use strict'] && !option.validthis && ((funct['(statement)'] && funct['(name)'].charAt(0) > 'Z') || funct['(global)'])) { warning("Possible strict violation.", x); } }); reservevar('true'); reservevar('undefined'); assignop('=', 'assign', 20); assignop('+=', 'assignadd', 20); assignop('-=', 'assignsub', 20); assignop('*=', 'assignmult', 20); assignop('/=', 'assigndiv', 20).nud = function () { error("A regular expression literal can be confused with '/='."); }; assignop('%=', 'assignmod', 20); bitwiseassignop('&=', 'assignbitand', 20); bitwiseassignop('|=', 'assignbitor', 20); bitwiseassignop('^=', 'assignbitxor', 20); bitwiseassignop('<<=', 'assignshiftleft', 20); bitwiseassignop('>>=', 'assignshiftright', 20); bitwiseassignop('>>>=', 'assignshiftrightunsigned', 20); infix('?', function (left, that) { that.left = left; that.right = expression(10); advance(':'); that['else'] = expression(10); return that; }, 30); infix('||', 'or', 40); infix('&&', 'and', 50); bitwise('|', 'bitor', 70); bitwise('^', 'bitxor', 80); bitwise('&', 'bitand', 90); relation('==', function (left, right) { var eqnull = option.eqnull && (left.value === 'null' || right.value === 'null'); if (!eqnull && option.eqeqeq) warning("Expected '{a}' and instead saw '{b}'.", this, '===', '=='); else if (isPoorRelation(left)) warning("Use '{a}' to compare with '{b}'.", this, '===', left.value); else if (isPoorRelation(right)) warning("Use '{a}' to compare with '{b}'.", this, '===', right.value); return this; }); relation('==='); relation('!=', function (left, right) { var eqnull = option.eqnull && (left.value === 'null' || right.value === 'null'); if (!eqnull && option.eqeqeq) { warning("Expected '{a}' and instead saw '{b}'.", this, '!==', '!='); } else if (isPoorRelation(left)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', left.value); } else if (isPoorRelation(right)) { warning("Use '{a}' to compare with '{b}'.", this, '!==', right.value); } return this; }); relation('!=='); relation('<'); relation('>'); relation('<='); relation('>='); bitwise('<<', 'shiftleft', 120); bitwise('>>', 'shiftright', 120); bitwise('>>>', 'shiftrightunsigned', 120); infix('in', 'in', 120); infix('instanceof', 'instanceof', 120); infix('+', function (left, that) { var right = expression(130); if (left && right && left.id === '(string)' && right.id === '(string)') { left.value += right.value; left.character = right.character; if (!option.scripturl && jx.test(left.value)) { warning("JavaScript URL.", left); } return left; } that.left = left; that.right = right; return that; }, 130); prefix('+', 'num'); prefix('+++', function () { warning("Confusing pluses."); this.right = expression(150); this.arity = 'unary'; return this; }); infix('+++', function (left) { warning("Confusing pluses."); this.left = left; this.right = expression(130); return this; }, 130); infix('-', 'sub', 130); prefix('-', 'neg'); prefix('---', function () { warning("Confusing minuses."); this.right = expression(150); this.arity = 'unary'; return this; }); infix('---', function (left) { warning("Confusing minuses."); this.left = left; this.right = expression(130); return this; }, 130); infix('*', 'mult', 140); infix('/', 'div', 140); infix('%', 'mod', 140); suffix('++', 'postinc'); prefix('++', 'preinc'); syntax['++'].exps = true; suffix('--', 'postdec'); prefix('--', 'predec'); syntax['--'].exps = true; prefix('delete', function () { var p = expression(0); if (!p || (p.id !== '.' && p.id !== '[')) { warning("Variables should not be deleted."); } this.first = p; return this; }).exps = true; prefix('~', function () { if (option.bitwise) { warning("Unexpected '{a}'.", this, '~'); } expression(150); return this; }); prefix('!', function () { this.right = expression(150); this.arity = 'unary'; if (bang[this.right.id] === true) { warning("Confusing use of '{a}'.", this, '!'); } return this; }); prefix('typeof', 'typeof'); prefix('new', function () { var c = expression(155), i; if (c && c.id !== 'function') { if (c.identifier) { c['new'] = true; switch (c.value) { case 'Number': case 'String': case 'Boolean': case 'Math': case 'JSON': warning("Do not use {a} as a constructor.", token, c.value); break; case 'Function': if (!option.evil) { warning("The Function constructor is eval."); } break; case 'Date': case 'RegExp': break; default: if (c.id !== 'function') { i = c.value.substr(0, 1); if (option.newcap && (i < 'A' || i > 'Z')) { warning("A constructor name should start with an uppercase letter.", token); } } } } else { if (c.id !== '.' && c.id !== '[' && c.id !== '(') { warning("Bad constructor.", token); } } } else { if (!option.supernew) warning("Weird construction. Delete 'new'.", this); } adjacent(token, nexttoken); if (nexttoken.id !== '(' && !option.supernew) { warning("Missing '()' invoking a constructor."); } this.first = c; return this; }); syntax['new'].exps = true; prefix('void').exps = true; infix('.', function (left, that) { adjacent(prevtoken, token); nobreak(); var m = identifier(); if (typeof m === 'string') { countMember(m); } that.left = left; that.right = m; if (left && left.value === 'arguments' && (m === 'callee' || m === 'caller')) { if (option.noarg) warning("Avoid arguments.{a}.", left, m); else if (directive['use strict']) error('Strict violation.'); } else if (!option.evil && left && left.value === 'document' && (m === 'write' || m === 'writeln')) { warning("document.write can be a form of eval.", left); } if (!option.evil && (m === 'eval' || m === 'execScript')) { warning('eval is evil.'); } return that; }, 160, true); infix('(', function (left, that) { if (prevtoken.id !== '}' && prevtoken.id !== ')') { nobreak(prevtoken, token); } nospace(); if (option.immed && !left.immed && left.id === 'function') { warning("Wrap an immediate function invocation in parentheses " + "to assist the reader in understanding that the expression " + "is the result of a function, and not the function itself."); } var n = 0, p = []; if (left) { if (left.type === '(identifier)') { if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if (left.value !== 'Number' && left.value !== 'String' && left.value !== 'Boolean' && left.value !== 'Date') { if (left.value === 'Math') { warning("Math is not a function.", left); } else if (option.newcap) { warning( "Missing 'new' prefix when invoking a constructor.", left); } } } } } if (nexttoken.id !== ')') { for (;;) { p[p.length] = expression(10); n += 1; if (nexttoken.id !== ',') { break; } comma(); } } advance(')'); nospace(prevtoken, token); if (typeof left === 'object') { if (left.value === 'parseInt' && n === 1) { warning("Missing radix parameter.", left); } if (!option.evil) { if (left.value === 'eval' || left.value === 'Function' || left.value === 'execScript') { warning("eval is evil.", left); } else if (p[0] && p[0].id === '(string)' && (left.value === 'setTimeout' || left.value === 'setInterval')) { warning( "Implied eval is evil. Pass a function instead of a string.", left); } } if (!left.identifier && left.id !== '.' && left.id !== '[' && left.id !== '(' && left.id !== '&&' && left.id !== '||' && left.id !== '?') { warning("Bad invocation.", left); } } that.left = left; return that; }, 155, true).exps = true; prefix('(', function () { nospace(); if (nexttoken.id === 'function') { nexttoken.immed = true; } var v = expression(0); advance(')', this); nospace(prevtoken, token); if (option.immed && v.id === 'function') { if (nexttoken.id === '(' || (nexttoken.id === '.' && (peek().value === 'call' || peek().value === 'apply'))) { warning( "Move the invocation into the parens that contain the function.", nexttoken); } else { warning( "Do not wrap function literals in parens unless they are to be immediately invoked.", this); } } return v; }); infix('[', function (left, that) { nobreak(prevtoken, token); nospace(); var e = expression(0), s; if (e && e.type === '(string)') { if (!option.evil && (e.value === 'eval' || e.value === 'execScript')) { warning("eval is evil.", that); } countMember(e.value); if (!option.sub && ix.test(e.value)) { s = syntax[e.value]; if (!s || !s.reserved) { warning("['{a}'] is better written in dot notation.", e, e.value); } } } advance(']', that); nospace(prevtoken, token); that.left = left; that.right = e; return that; }, 160, true); prefix('[', function () { var b = token.line !== nexttoken.line; this.first = []; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } while (nexttoken.id !== '(end)') { while (nexttoken.id === ',') { warning("Extra comma."); advance(','); } if (nexttoken.id === ']') { break; } if (b && token.line !== nexttoken.line) { indentation(); } this.first.push(expression(10)); if (nexttoken.id === ',') { comma(); if (nexttoken.id === ']' && !option.es5) { warning("Extra comma.", token); break; } } else { break; } } if (b) { indent -= option.indent; indentation(); } advance(']', this); return this; }, 160); function property_name() { var id = optionalidentifier(true); if (!id) { if (nexttoken.id === '(string)') { id = nexttoken.value; advance(); } else if (nexttoken.id === '(number)') { id = nexttoken.value.toString(); advance(); } } return id; } function functionparams() { var i, t = nexttoken, p = []; advance('('); nospace(); if (nexttoken.id === ')') { advance(')'); return; } for (;;) { i = identifier(true); p.push(i); addlabel(i, 'parameter'); if (nexttoken.id === ',') { comma(); } else { advance(')', t); nospace(prevtoken, token); return p; } } } function doFunction(i, statement) { var f, oldOption = option, oldScope = scope; option = Object.create(option); scope = Object.create(scope); funct = { '(name)' : i || '"' + anonname + '"', '(line)' : nexttoken.line, '(context)' : funct, '(breakage)' : 0, '(loopage)' : 0, '(scope)' : scope, '(statement)': statement }; f = funct; token.funct = funct; functions.push(funct); if (i) { addlabel(i, 'function'); } funct['(params)'] = functionparams(); block(false, false, true); scope = oldScope; option = oldOption; funct['(last)'] = token.line; funct = funct['(context)']; return f; } (function (x) { x.nud = function () { var b, f, i, j, p, t; var props = {}; // All properties, including accessors function saveProperty(name, token) { if (props[name] && is_own(props, name)) warning("Duplicate member '{a}'.", nexttoken, i); else props[name] = {}; props[name].basic = true; props[name].basicToken = token; } function saveSetter(name, token) { if (props[name] && is_own(props, name)) { if (props[name].basic || props[name].setter) warning("Duplicate member '{a}'.", nexttoken, i); } else { props[name] = {}; } props[name].setter = true; props[name].setterToken = token; } function saveGetter(name) { if (props[name] && is_own(props, name)) { if (props[name].basic || props[name].getter) warning("Duplicate member '{a}'.", nexttoken, i); } else { props[name] = {}; } props[name].getter = true; props[name].getterToken = token; } b = token.line !== nexttoken.line; if (b) { indent += option.indent; if (nexttoken.from === indent + option.indent) { indent += option.indent; } } for (;;) { if (nexttoken.id === '}') { break; } if (b) { indentation(); } if (nexttoken.value === 'get' && peek().id !== ':') { advance('get'); if (!option.es5) { error("get/set are ES5 features."); } i = property_name(); if (!i) { error("Missing property name."); } saveGetter(i); t = nexttoken; adjacent(token, nexttoken); f = doFunction(); p = f['(params)']; if (p) { warning("Unexpected parameter '{a}' in get {b} function.", t, p[0], i); } adjacent(token, nexttoken); } else if (nexttoken.value === 'set' && peek().id !== ':') { advance('set'); if (!option.es5) { error("get/set are ES5 features."); } i = property_name(); if (!i) { error("Missing property name."); } saveSetter(i, nexttoken); t = nexttoken; adjacent(token, nexttoken); f = doFunction(); p = f['(params)']; if (!p || p.length !== 1) { warning("Expected a single parameter in set {a} function.", t, i); } } else { i = property_name(); saveProperty(i, nexttoken); if (typeof i !== 'string') { break; } advance(':'); nonadjacent(token, nexttoken); expression(10); } countMember(i); if (nexttoken.id === ',') { comma(); if (nexttoken.id === ',') { warning("Extra comma.", token); } else if (nexttoken.id === '}' && !option.es5) { warning("Extra comma.", token); } } else { break; } } if (b) { indent -= option.indent; indentation(); } advance('}', this); // Check for lonely setters if in the ES5 mode. if (option.es5) { for (var name in props) { if (is_own(props, name) && props[name].setter && !props[name].getter) { warning("Setter is defined without getter.", props[name].setterToken); } } } return this; }; x.fud = function () { error("Expected to see a statement and instead saw a block.", token); }; }(delim('{'))); // This Function is called when esnext option is set to true // it adds the `const` statement to JSHINT useESNextSyntax = function () { var conststatement = stmt('const', function (prefix) { var id, name, value; this.first = []; for (;;) { nonadjacent(token, nexttoken); id = identifier(); if (funct[id] === "const") { warning("const '" + id + "' has already been declared"); } if (funct['(global)'] && predefined[id] === false) { warning("Redefinition of '{a}'.", token, id); } addlabel(id, 'const'); if (prefix) { break; } name = token; this.first.push(token); if (nexttoken.id !== "=") { warning("const " + "'{a}' is initialized to 'undefined'.", token, id); } if (nexttoken.id === '=') { nonadjacent(token, nexttoken); advance('='); nonadjacent(token, nexttoken); if (nexttoken.id === 'undefined') { warning("It is not necessary to initialize " + "'{a}' to 'undefined'.", token, id); } if (peek(0).id === '=' && nexttoken.identifier) { error("Constant {a} was not declared correctly.", nexttoken, nexttoken.value); } value = expression(0); name.first = value; } if (nexttoken.id !== ',') { break; } comma(); } return this; }); conststatement.exps = true; }; var varstatement = stmt('var', function (prefix) { // JavaScript does not have block scope. It only has function scope. So, // declaring a variable in a block can have unexpected consequences. var id, name, value; if (funct['(onevar)'] && option.onevar) { warning("Too many var statements."); } else if (!funct['(global)']) { funct['(onevar)'] = true; } this.first = []; for (;;) { nonadjacent(token, nexttoken); id = identifier(); if (option.esnext && funct[id] === "const") { warning("const '" + id + "' has already been declared"); } if (funct['(global)'] && predefined[id] === false) { warning("Redefinition of '{a}'.", token, id); } addlabel(id, 'unused'); if (prefix) { break; } name = token; this.first.push(token); if (nexttoken.id === '=') { nonadjacent(token, nexttoken); advance('='); nonadjacent(token, nexttoken); if (nexttoken.id === 'undefined') { warning("It is not necessary to initialize '{a}' to 'undefined'.", token, id); } if (peek(0).id === '=' && nexttoken.identifier) { error("Variable {a} was not declared correctly.", nexttoken, nexttoken.value); } value = expression(0); name.first = value; } if (nexttoken.id !== ',') { break; } comma(); } return this; }); varstatement.exps = true; blockstmt('function', function () { if (inblock) { warning("Function declarations should not be placed in blocks. " + "Use a function expression or move the statement to the top of " + "the outer function.", token); } var i = identifier(); if (option.esnext && funct[i] === "const") { warning("const '" + i + "' has already been declared"); } adjacent(token, nexttoken); addlabel(i, 'unction'); doFunction(i, true); if (nexttoken.id === '(' && nexttoken.line === token.line) { error( "Function declarations are not invocable. Wrap the whole function invocation in parens."); } return this; }); prefix('function', function () { var i = optionalidentifier(); if (i) { adjacent(token, nexttoken); } else { nonadjacent(token, nexttoken); } doFunction(i); if (!option.loopfunc && funct['(loopage)']) { warning("Don't make functions within a loop."); } return this; }); blockstmt('if', function () { var t = nexttoken; advance('('); nonadjacent(this, t); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); block(true, true); if (nexttoken.id === 'else') { nonadjacent(token, nexttoken); advance('else'); if (nexttoken.id === 'if' || nexttoken.id === 'switch') { statement(true); } else { block(true, true); } } return this; }); blockstmt('try', function () { var b, e, s; block(false); if (nexttoken.id === 'catch') { advance('catch'); nonadjacent(token, nexttoken); advance('('); s = scope; scope = Object.create(s); e = nexttoken.value; if (nexttoken.type !== '(identifier)') { warning("Expected an identifier and instead saw '{a}'.", nexttoken, e); } else { addlabel(e, 'exception'); } advance(); advance(')'); block(false); b = true; scope = s; } if (nexttoken.id === 'finally') { advance('finally'); block(false); return; } else if (!b) { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'catch', nexttoken.value); } return this; }); blockstmt('while', function () { var t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); block(true, true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; }).labelled = true; blockstmt('with', function () { var t = nexttoken; if (directive['use strict']) { error("'with' is not allowed in strict mode.", token); } else if (!option.withstmt) { warning("Don't use 'with'.", token); } advance('('); nonadjacent(this, t); nospace(); expression(0); advance(')', t); nospace(prevtoken, token); block(true, true); return this; }); blockstmt('switch', function () { var t = nexttoken, g = false; funct['(breakage)'] += 1; advance('('); nonadjacent(this, t); nospace(); this.condition = expression(20); advance(')', t); nospace(prevtoken, token); nonadjacent(token, nexttoken); t = nexttoken; advance('{'); nonadjacent(token, nexttoken); indent += option.indent; this.cases = []; for (;;) { switch (nexttoken.id) { case 'case': switch (funct['(verb)']) { case 'break': case 'case': case 'continue': case 'return': case 'switch': case 'throw': break; default: // You can tell JSHint that you don't use break intentionally by // adding a comment /* falls through */ on a line just before // the next `case`. if (!ft.test(lines[nexttoken.line - 2])) { warning( "Expected a 'break' statement before 'case'.", token); } } indentation(-option.indent); advance('case'); this.cases.push(expression(20)); g = true; advance(':'); funct['(verb)'] = 'case'; break; case 'default': switch (funct['(verb)']) { case 'break': case 'continue': case 'return': case 'throw': break; default: if (!ft.test(lines[nexttoken.line - 2])) { warning( "Expected a 'break' statement before 'default'.", token); } } indentation(-option.indent); advance('default'); g = true; advance(':'); break; case '}': indent -= option.indent; indentation(); advance('}', t); if (this.cases.length === 1 || this.condition.id === 'true' || this.condition.id === 'false') { if (!option.onecase) warning("This 'switch' should be an 'if'.", this); } funct['(breakage)'] -= 1; funct['(verb)'] = undefined; return; case '(end)': error("Missing '{a}'.", nexttoken, '}'); return; default: if (g) { switch (token.id) { case ',': error("Each value should have its own case label."); return; case ':': g = false; statements(); break; default: error("Missing ':' on a case clause.", token); return; } } else { if (token.id === ':') { advance(':'); error("Unexpected '{a}'.", token, ':'); statements(); } else { error("Expected '{a}' and instead saw '{b}'.", nexttoken, 'case', nexttoken.value); return; } } } } }).labelled = true; stmt('debugger', function () { if (!option.debug) { warning("All 'debugger' statements should be removed."); } return this; }).exps = true; (function () { var x = stmt('do', function () { funct['(breakage)'] += 1; funct['(loopage)'] += 1; this.first = block(true); advance('while'); var t = nexttoken; nonadjacent(token, t); advance('('); nospace(); expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } advance(')', t); nospace(prevtoken, token); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; }); x.labelled = true; x.exps = true; }()); blockstmt('for', function () { var s, t = nexttoken; funct['(breakage)'] += 1; funct['(loopage)'] += 1; advance('('); nonadjacent(this, t); nospace(); if (peek(nexttoken.id === 'var' ? 1 : 0).id === 'in') { if (nexttoken.id === 'var') { advance('var'); varstatement.fud.call(varstatement, true); } else { switch (funct[nexttoken.value]) { case 'unused': funct[nexttoken.value] = 'var'; break; case 'var': break; default: warning("Bad for in variable '{a}'.", nexttoken, nexttoken.value); } advance(); } advance('in'); expression(20); advance(')', t); s = block(true, true); if (option.forin && s && (s.length > 1 || typeof s[0] !== 'object' || s[0].value !== 'if')) { warning("The body of a for in should be wrapped in an if statement to filter " + "unwanted properties from the prototype.", this); } funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; } else { if (nexttoken.id !== ';') { if (nexttoken.id === 'var') { advance('var'); varstatement.fud.call(varstatement); } else { for (;;) { expression(0, 'for'); if (nexttoken.id !== ',') { break; } comma(); } } } nolinebreak(token); advance(';'); if (nexttoken.id !== ';') { expression(20); if (nexttoken.id === '=') { if (!option.boss) warning("Expected a conditional expression and instead saw an assignment."); advance('='); expression(20); } } nolinebreak(token); advance(';'); if (nexttoken.id === ';') { error("Expected '{a}' and instead saw '{b}'.", nexttoken, ')', ';'); } if (nexttoken.id !== ')') { for (;;) { expression(0, 'for'); if (nexttoken.id !== ',') { break; } comma(); } } advance(')', t); nospace(prevtoken, token); block(true, true); funct['(breakage)'] -= 1; funct['(loopage)'] -= 1; return this; } }).labelled = true; stmt('break', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) warning("Unexpected '{a}'.", nexttoken, this.value); if (!option.asi) nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } this.first = nexttoken; advance(); } } reachable('break'); return this; }).exps = true; stmt('continue', function () { var v = nexttoken.value; if (funct['(breakage)'] === 0) warning("Unexpected '{a}'.", nexttoken, this.value); if (!option.asi) nolinebreak(this); if (nexttoken.id !== ';') { if (token.line === nexttoken.line) { if (funct[v] !== 'label') { warning("'{a}' is not a statement label.", nexttoken, v); } else if (scope[v] !== funct) { warning("'{a}' is out of scope.", nexttoken, v); } this.first = nexttoken; advance(); } } else if (!funct['(loopage)']) { warning("Unexpected '{a}'.", nexttoken, this.value); } reachable('continue'); return this; }).exps = true; stmt('return', function () { if (this.line === nexttoken.line) { if (nexttoken.id === '(regexp)') warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator."); if (nexttoken.id !== ';' && !nexttoken.reach) { nonadjacent(token, nexttoken); if (peek().value === "=" && !option.boss) { warningAt("Did you mean to return a conditional instead of an assignment?", token.line, token.character + 1); } this.first = expression(0); } } else if (!option.asi) { nolinebreak(this); // always warn (Line breaking error) } reachable('return'); return this; }).exps = true; stmt('throw', function () { nolinebreak(this); nonadjacent(token, nexttoken); this.first = expression(20); reachable('throw'); return this; }).exps = true; // Superfluous reserved words reserve('class'); reserve('const'); reserve('enum'); reserve('export'); reserve('extends'); reserve('import'); reserve('super'); reserve('let'); reserve('yield'); reserve('implements'); reserve('interface'); reserve('package'); reserve('private'); reserve('protected'); reserve('public'); reserve('static'); // Parse JSON function jsonValue() { function jsonObject() { var o = {}, t = nexttoken; advance('{'); if (nexttoken.id !== '}') { for (;;) { if (nexttoken.id === '(end)') { error("Missing '}' to match '{' from line {a}.", nexttoken, t.line); } else if (nexttoken.id === '}') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } else if (nexttoken.id !== '(string)') { warning("Expected a string and instead saw {a}.", nexttoken, nexttoken.value); } if (o[nexttoken.value] === true) { warning("Duplicate key '{a}'.", nexttoken, nexttoken.value); } else if ((nexttoken.value === '__proto__' && !option.proto) || (nexttoken.value === '__iterator__' && !option.iterator)) { warning("The '{a}' key may produce unexpected results.", nexttoken, nexttoken.value); } else { o[nexttoken.value] = true; } advance(); advance(':'); jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance('}'); } function jsonArray() { var t = nexttoken; advance('['); if (nexttoken.id !== ']') { for (;;) { if (nexttoken.id === '(end)') { error("Missing ']' to match '[' from line {a}.", nexttoken, t.line); } else if (nexttoken.id === ']') { warning("Unexpected comma.", token); break; } else if (nexttoken.id === ',') { error("Unexpected comma.", nexttoken); } jsonValue(); if (nexttoken.id !== ',') { break; } advance(','); } } advance(']'); } switch (nexttoken.id) { case '{': jsonObject(); break; case '[': jsonArray(); break; case 'true': case 'false': case 'null': case '(number)': case '(string)': advance(); break; case '-': advance('-'); if (token.character !== nexttoken.from) { warning("Unexpected space after '-'.", token); } adjacent(token, nexttoken); advance('(number)'); break; default: error("Expected a JSON value.", nexttoken); } } // The actual JSHINT function itself. var itself = function (s, o, g) { var a, i, k; JSHINT.errors = []; JSHINT.undefs = []; predefined = Object.create(standard); combine(predefined, g || {}); if (o) { a = o.predef; if (a) { if (Array.isArray(a)) { for (i = 0; i < a.length; i += 1) { predefined[a[i]] = true; } } else if (typeof a === 'object') { k = Object.keys(a); for (i = 0; i < k.length; i += 1) { predefined[k[i]] = !!a[k[i]]; } } } option = o; } else { option = {}; } option.indent = option.indent || 4; option.maxerr = option.maxerr || 50; tab = ''; for (i = 0; i < option.indent; i += 1) { tab += ' '; } indent = 1; global = Object.create(predefined); scope = global; funct = { '(global)': true, '(name)': '(global)', '(scope)': scope, '(breakage)': 0, '(loopage)': 0 }; functions = [funct]; urls = []; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; jsonmode = false; warnings = 0; lex.init(s); prereg = true; directive = {}; prevtoken = token = nexttoken = syntax['(begin)']; // Check options for (var name in o) { if (is_own(o, name)) { checkOption(name, token); } } assume(); // combine the passed globals after we've assumed all our options combine(predefined, g || {}); //reset values comma.first = true; try { advance(); switch (nexttoken.id) { case '{': case '[': option.laxbreak = true; jsonmode = true; jsonValue(); break; default: directives(); if (directive["use strict"] && !option.globalstrict) { warning("Use the function form of \"use strict\".", prevtoken); } statements(); } advance('(end)'); var markDefined = function (name, context) { do { if (typeof context[name] === 'string') { // JSHINT marks unused variables as 'unused' and // unused function declaration as 'unction'. This // code changes such instances back 'var' and // 'closure' so that the code in JSHINT.data() // doesn't think they're unused. if (context[name] === 'unused') context[name] = 'var'; else if (context[name] === 'unction') context[name] = 'closure'; return true; } context = context['(context)']; } while (context); return false; }; var clearImplied = function (name, line) { if (!implied[name]) return; var newImplied = []; for (var i = 0; i < implied[name].length; i += 1) { if (implied[name][i] !== line) newImplied.push(implied[name][i]); } if (newImplied.length === 0) delete implied[name]; else implied[name] = newImplied; }; // Check queued 'x is not defined' instances to see if they're still undefined. for (i = 0; i < JSHINT.undefs.length; i += 1) { k = JSHINT.undefs[i].slice(0); if (markDefined(k[2].value, k[0])) { clearImplied(k[2].value, k[2].line); } else { warning.apply(warning, k.slice(1)); } } } catch (e) { if (e) { var nt = nexttoken || {}; JSHINT.errors.push({ raw : e.raw, reason : e.message, line : e.line || nt.line, character : e.character || nt.from }, null); } } return JSHINT.errors.length === 0; }; // Data summary. itself.data = function () { var data = { functions: [], options: option }, fu, globals, implieds = [], f, i, j, members = [], n, unused = [], v; if (itself.errors.length) { data.errors = itself.errors; } if (jsonmode) { data.json = true; } for (n in implied) { if (is_own(implied, n)) { implieds.push({ name: n, line: implied[n] }); } } if (implieds.length > 0) { data.implieds = implieds; } if (urls.length > 0) { data.urls = urls; } globals = Object.keys(scope); if (globals.length > 0) { data.globals = globals; } for (i = 1; i < functions.length; i += 1) { f = functions[i]; fu = {}; for (j = 0; j < functionicity.length; j += 1) { fu[functionicity[j]] = []; } for (n in f) { if (is_own(f, n) && n.charAt(0) !== '(') { v = f[n]; if (v === 'unction') { v = 'unused'; } if (Array.isArray(fu[v])) { fu[v].push(n); if (v === 'unused') { unused.push({ name: n, line: f['(line)'], 'function': f['(name)'] }); } } } } for (j = 0; j < functionicity.length; j += 1) { if (fu[functionicity[j]].length === 0) { delete fu[functionicity[j]]; } } fu.name = f['(name)']; fu.param = f['(params)']; fu.line = f['(line)']; fu.last = f['(last)']; data.functions.push(fu); } if (unused.length > 0) { data.unused = unused; } members = []; for (n in member) { if (typeof member[n] === 'number') { data.member = member; break; } } return data; }; itself.report = function (option) { var data = itself.data(); var a = [], c, e, err, f, i, k, l, m = '', n, o = [], s; function detail(h, array) { var b, i, singularity; if (array) { o.push('<div><i>' + h + '</i> '); array = array.sort(); for (i = 0; i < array.length; i += 1) { if (array[i] !== singularity) { singularity = array[i]; o.push((b ? ', ' : '') + singularity); b = true; } } o.push('</div>'); } } if (data.errors || data.implieds || data.unused) { err = true; o.push('<div id=errors><i>Error:</i>'); if (data.errors) { for (i = 0; i < data.errors.length; i += 1) { c = data.errors[i]; if (c) { e = c.evidence || ''; o.push('<p>Problem' + (isFinite(c.line) ? ' at line ' + c.line + ' character ' + c.character : '') + ': ' + c.reason.entityify() + '</p><p class=evidence>' + (e && (e.length > 80 ? e.slice(0, 77) + '...' : e).entityify()) + '</p>'); } } } if (data.implieds) { s = []; for (i = 0; i < data.implieds.length; i += 1) { s[i] = '<code>' + data.implieds[i].name + '</code>&nbsp;<i>' + data.implieds[i].line + '</i>'; } o.push('<p><i>Implied global:</i> ' + s.join(', ') + '</p>'); } if (data.unused) { s = []; for (i = 0; i < data.unused.length; i += 1) { s[i] = '<code><u>' + data.unused[i].name + '</u></code>&nbsp;<i>' + data.unused[i].line + '</i> <code>' + data.unused[i]['function'] + '</code>'; } o.push('<p><i>Unused variable:</i> ' + s.join(', ') + '</p>'); } if (data.json) { o.push('<p>JSON: bad.</p>'); } o.push('</div>'); } if (!option) { o.push('<br><div id=functions>'); if (data.urls) { detail("URLs<br>", data.urls, '<br>'); } if (data.json && !err) { o.push('<p>JSON: good.</p>'); } else if (data.globals) { o.push('<div><i>Global</i> ' + data.globals.sort().join(', ') + '</div>'); } else { o.push('<div><i>No new global variables introduced.</i></div>'); } for (i = 0; i < data.functions.length; i += 1) { f = data.functions[i]; o.push('<br><div class=function><i>' + f.line + '-' + f.last + '</i> ' + (f.name || '') + '(' + (f.param ? f.param.join(', ') : '') + ')</div>'); detail('<big><b>Unused</b></big>', f.unused); detail('Closure', f.closure); detail('Variable', f['var']); detail('Exception', f.exception); detail('Outer', f.outer); detail('Global', f.global); detail('Label', f.label); } if (data.member) { a = Object.keys(data.member); if (a.length) { a = a.sort(); m = '<br><pre id=members>/*members '; l = 10; for (i = 0; i < a.length; i += 1) { k = a[i]; n = k.name(); if (l + n.length > 72) { o.push(m + '<br>'); m = ' '; l = 1; } l += n.length + 2; if (data.member[k] === 1) { n = '<i>' + n + '</i>'; } if (i < a.length - 1) { n += ', '; } m += n; } o.push(m + '<br>*/</pre>'); } o.push('</div>'); } } return o.join(''); }; itself.jshint = itself; return itself; }()); // Make JSHINT a Node module, if possible. if (typeof exports === 'object' && exports) exports.JSHINT = JSHINT; }); /* * Narcissus - JS implemented in JS. * * Parser. */ define('ace/narcissus/parser', ['require', 'exports', 'module' , 'ace/narcissus/lexer', 'ace/narcissus/definitions', 'ace/narcissus/options'], function(require, exports, module) { var lexer = require('./lexer'); var definitions = require('./definitions'); var options = require('./options'); var Tokenizer = lexer.Tokenizer; var Dict = definitions.Dict; var Stack = definitions.Stack; // Set constants in the local scope. eval(definitions.consts); function pushDestructuringVarDecls(n, s) { for (var i in n) { var sub = n[i]; if (sub.type === IDENTIFIER) { s.varDecls.push(sub); } else { pushDestructuringVarDecls(sub, s); } } } function Parser(tokenizer) { tokenizer.parser = this; this.t = tokenizer; this.x = null; this.unexpectedEOF = false; options.mozillaMode && (this.mozillaMode = true); options.parenFreeMode && (this.parenFreeMode = true); } function StaticContext(parentScript, parentBlock, inModule, inFunction, strictMode) { this.parentScript = parentScript; this.parentBlock = parentBlock || parentScript; this.inModule = inModule || false; this.inFunction = inFunction || false; this.inForLoopInit = false; this.topLevel = true; this.allLabels = new Stack(); this.currentLabels = new Stack(); this.labeledTargets = new Stack(); this.defaultLoopTarget = null; this.defaultTarget = null; this.strictMode = strictMode; } StaticContext.prototype = { // non-destructive update via prototype extension update: function(ext) { var desc = {}; for (var key in ext) { desc[key] = { value: ext[key], writable: true, enumerable: true, configurable: true } } return Object.create(this, desc); }, pushLabel: function(label) { return this.update({ currentLabels: this.currentLabels.push(label), allLabels: this.allLabels.push(label) }); }, pushTarget: function(target) { var isDefaultLoopTarget = target.isLoop; var isDefaultTarget = isDefaultLoopTarget || target.type === SWITCH; if (this.currentLabels.isEmpty()) { if (isDefaultLoopTarget) this.update({ defaultLoopTarget: target }); if (isDefaultTarget) this.update({ defaultTarget: target }); return this; } target.labels = new Dict(); this.currentLabels.forEach(function(label) { target.labels.set(label, true); }); return this.update({ currentLabels: new Stack(), labeledTargets: this.labeledTargets.push(target), defaultLoopTarget: isDefaultLoopTarget ? target : this.defaultLoopTarget, defaultTarget: isDefaultTarget ? target : this.defaultTarget }); }, nest: function() { return this.topLevel ? this.update({ topLevel: false }) : this; }, canImport: function() { return this.topLevel && !this.inFunction; }, canExport: function() { return this.inModule && this.topLevel && !this.inFunction; }, banWith: function() { return this.strictMode || this.inModule; }, modulesAllowed: function() { return this.topLevel && !this.inFunction; } }; var Pp = Parser.prototype; Pp.mozillaMode = false; Pp.parenFreeMode = false; Pp.withContext = function(x, f) { var x0 = this.x; this.x = x; var result = f.call(this); // NB: we don't bother with finally, since exceptions trash the parser this.x = x0; return result; }; Pp.newNode = function newNode(opts) { return new Node(this.t, opts); }; Pp.fail = function fail(msg) { throw this.t.newSyntaxError(msg); }; Pp.match = function match(tt, scanOperand, keywordIsName) { return this.t.match(tt, scanOperand, keywordIsName); }; Pp.mustMatch = function mustMatch(tt, keywordIsName) { return this.t.mustMatch(tt, keywordIsName); }; Pp.peek = function peek(scanOperand) { return this.t.peek(scanOperand); }; Pp.peekOnSameLine = function peekOnSameLine(scanOperand) { return this.t.peekOnSameLine(scanOperand); }; Pp.done = function done() { return this.t.done; }; Pp.Script = function Script(inModule, inFunction, expectEnd) { var node = this.newNode(scriptInit()); var x2 = new StaticContext(node, node, inModule, inFunction); this.withContext(x2, function() { this.Statements(node, true); }); if (expectEnd && !this.done()) this.fail("expected end of input"); return node; }; function Pragma(n) { if (n.type === SEMICOLON) { var e = n.expression; if (e.type === STRING && e.value === "use strict") { n.pragma = "strict"; return true; } } return false; } /* * Node :: (tokenizer, optional init object) -> node */ function Node(t, init) { var token = t.token; if (token) { // If init.type exists it will override token.type. this.type = token.type; this.value = token.value; this.lineno = token.lineno; // Start and end are file positions for error handling. this.start = token.start; this.end = token.end; } else { this.lineno = t.lineno; } this.filename = t.filename; this.children = []; for (var prop in init) this[prop] = init[prop]; } /* * SyntheticNode :: (optional init object) -> node */ function SyntheticNode(init) { this.children = []; for (var prop in init) this[prop] = init[prop]; this.synthetic = true; } var Np = Node.prototype = SyntheticNode.prototype = {}; Np.constructor = Node; var TO_SOURCE_SKIP = { type: true, value: true, lineno: true, start: true, end: true, tokenizer: true, assignOp: true }; function unevalableConst(code) { var token = definitions.tokens[code]; var constName = definitions.opTypeNames.hasOwnProperty(token) ? definitions.opTypeNames[token] : token in definitions.keywords ? token.toUpperCase() : token; return { toSource: function() { return constName } }; } Np.toSource = function toSource() { var mock = {}; var self = this; mock.type = unevalableConst(this.type); // avoid infinite recursion in case of back-links if (this.generatingSource) return mock.toSource(); this.generatingSource = true; if ("value" in this) mock.value = this.value; if ("lineno" in this) mock.lineno = this.lineno; if ("start" in this) mock.start = this.start; if ("end" in this) mock.end = this.end; if (this.assignOp) mock.assignOp = unevalableConst(this.assignOp); for (var key in this) { if (this.hasOwnProperty(key) && !(key in TO_SOURCE_SKIP)) mock[key] = this[key]; } try { return mock.toSource(); } finally { delete this.generatingSource; } }; // Always use push to add operands to an expression, to update start and end. Np.push = function (kid) { // kid can be null e.g. [1, , 2]. if (kid !== null) { if (kid.start < this.start) this.start = kid.start; if (this.end < kid.end) this.end = kid.end; } return this.children.push(kid); } Node.indentLevel = 0; function tokenString(tt) { var t = definitions.tokens[tt]; return /^\W/.test(t) ? definitions.opTypeNames[t] : t.toUpperCase(); } Np.toString = function () { var a = []; for (var i in this) { if (this.hasOwnProperty(i) && i !== 'type' && i !== 'target') a.push({id: i, value: this[i]}); } a.sort(function (a,b) { return (a.id < b.id) ? -1 : 1; }); var INDENTATION = " "; var n = ++Node.indentLevel; var s = "{\n" + INDENTATION.repeat(n) + "type: " + tokenString(this.type); for (i = 0; i < a.length; i++) s += ",\n" + INDENTATION.repeat(n) + a[i].id + ": " + a[i].value; n = --Node.indentLevel; s += "\n" + INDENTATION.repeat(n) + "}"; return s; } Np.synth = function(init) { var node = new SyntheticNode(init); node.filename = this.filename; node.lineno = this.lineno; node.start = this.start; node.end = this.end; return node; }; var LOOP_INIT = { isLoop: true }; function blockInit() { return { type: BLOCK, varDecls: [] }; } function scriptInit() { return { type: SCRIPT, funDecls: [], varDecls: [], modDefns: new Dict(), modAssns: new Dict(), modDecls: new Dict(), modLoads: new Dict(), impDecls: [], expDecls: [], exports: new Dict(), hasEmptyReturn: false, hasReturnWithValue: false, hasYield: false }; } definitions.defineGetter(Np, "length", function() { throw new Error("Node.prototype.length is gone; " + "use n.children.length instead"); }); definitions.defineProperty(String.prototype, "repeat", function(n) { var s = "", t = this + s; while (--n >= 0) s += t; return s; }, false, false, true); Pp.MaybeLeftParen = function MaybeLeftParen() { if (this.parenFreeMode) return this.match(LEFT_PAREN) ? LEFT_PAREN : END; return this.mustMatch(LEFT_PAREN).type; }; Pp.MaybeRightParen = function MaybeRightParen(p) { if (p === LEFT_PAREN) this.mustMatch(RIGHT_PAREN); } /* * Statements :: (node[, boolean]) -> void * * Parses a sequence of Statements. */ Pp.Statements = function Statements(n, topLevel) { var prologue = !!topLevel; try { while (!this.done() && this.peek(true) !== RIGHT_CURLY) { var n2 = this.Statement(); n.push(n2); if (prologue && Pragma(n2)) { this.x.strictMode = true; n.strict = true; } else { prologue = false; } } } catch (e) { try { if (this.done()) this.unexpectedEOF = true; } catch(e) {} throw e; } } Pp.Block = function Block() { this.mustMatch(LEFT_CURLY); var n = this.newNode(blockInit()); var x2 = this.x.update({ parentBlock: n }).pushTarget(n); this.withContext(x2, function() { this.Statements(n); }); this.mustMatch(RIGHT_CURLY); return n; } var DECLARED_FORM = 0, EXPRESSED_FORM = 1, STATEMENT_FORM = 2; function Export(node, isDefinition) { this.node = node; // the AST node declaring this individual export this.isDefinition = isDefinition; // is the node an 'export'-annotated definition? this.resolved = null; // resolved pointer to the target of this export } /* * registerExport :: (Dict, EXPORT node) -> void */ function registerExport(exports, decl) { function register(name, exp) { if (exports.has(name)) throw new SyntaxError("multiple exports of " + name); exports.set(name, exp); } switch (decl.type) { case MODULE: case FUNCTION: register(decl.name, new Export(decl, true)); break; case VAR: for (var i = 0; i < decl.children.length; i++) register(decl.children[i].name, new Export(decl.children[i], true)); break; case LET: case CONST: throw new Error("NYI: " + definitions.tokens[decl.type]); case EXPORT: for (var i = 0; i < decl.pathList.length; i++) { var path = decl.pathList[i]; switch (path.type) { case OBJECT_INIT: for (var j = 0; j < path.children.length; j++) { // init :: IDENTIFIER | PROPERTY_INIT var init = path.children[j]; if (init.type === IDENTIFIER) register(init.value, new Export(init, false)); else register(init.children[0].value, new Export(init.children[1], false)); } break; case DOT: register(path.children[1].value, new Export(path, false)); break; case IDENTIFIER: register(path.value, new Export(path, false)); break; default: throw new Error("unexpected export path: " + definitions.tokens[path.type]); } } break; default: throw new Error("unexpected export decl: " + definitions.tokens[exp.type]); } } /* * Module :: (node) -> Module * * Static semantic representation of a module. */ function Module(node) { var exports = node.body.exports; var modDefns = node.body.modDefns; var exportedModules = new Dict(); exports.forEach(function(name, exp) { var node = exp.node; if (node.type === MODULE) { exportedModules.set(name, node); } else if (!exp.isDefinition && node.type === IDENTIFIER && modDefns.has(node.value)) { var mod = modDefns.get(node.value); exportedModules.set(name, mod); } }); this.node = node; this.exports = exports; this.exportedModules = exportedModules; } /* * Statement :: () -> node * * Parses a Statement. */ Pp.Statement = function Statement() { var i, label, n, n2, p, c, ss, tt = this.t.get(true), tt2, x0, x2, x3; var comments = this.t.blockComments; // Cases for statements ending in a right curly return early, avoiding the // common semicolon insertion magic after this switch. switch (tt) { case IMPORT: if (!this.x.canImport()) this.fail("illegal context for import statement"); n = this.newNode(); n.pathList = this.ImportPathList(); this.x.parentScript.impDecls.push(n); break; case EXPORT: if (!this.x.canExport()) this.fail("export statement not in module top level"); switch (this.peek()) { case MODULE: case FUNCTION: case LET: case VAR: case CONST: n = this.Statement(); n.blockComments = comments; n.exported = true; this.x.parentScript.expDecls.push(n); registerExport(this.x.parentScript.exports, n); return n; } n = this.newNode(); n.pathList = this.ExportPathList(); this.x.parentScript.expDecls.push(n); registerExport(this.x.parentScript.exports, n); break; case FUNCTION: // DECLARED_FORM extends funDecls of x, STATEMENT_FORM doesn't. return this.FunctionDefinition(true, this.x.topLevel ? DECLARED_FORM : STATEMENT_FORM, comments); case LEFT_CURLY: n = this.newNode(blockInit()); x2 = this.x.update({ parentBlock: n }).pushTarget(n).nest(); this.withContext(x2, function() { this.Statements(n); }); this.mustMatch(RIGHT_CURLY); return n; case IF: n = this.newNode(); n.condition = this.HeadExpression(); x2 = this.x.pushTarget(n).nest(); this.withContext(x2, function() { n.thenPart = this.Statement(); n.elsePart = this.match(ELSE, true) ? this.Statement() : null; }); return n; case SWITCH: // This allows CASEs after a DEFAULT, which is in the standard. n = this.newNode({ cases: [], defaultIndex: -1 }); n.discriminant = this.HeadExpression(); x2 = this.x.pushTarget(n).nest(); this.withContext(x2, function() { this.mustMatch(LEFT_CURLY); while ((tt = this.t.get()) !== RIGHT_CURLY) { switch (tt) { case DEFAULT: if (n.defaultIndex >= 0) this.fail("More than one switch default"); // FALL THROUGH case CASE: n2 = this.newNode(); if (tt === DEFAULT) n.defaultIndex = n.cases.length; else n2.caseLabel = this.Expression(COLON); break; default: this.fail("Invalid switch case"); } this.mustMatch(COLON); n2.statements = this.newNode(blockInit()); while ((tt=this.peek(true)) !== CASE && tt !== DEFAULT && tt !== RIGHT_CURLY) n2.statements.push(this.Statement()); n.cases.push(n2); } }); return n; case FOR: n = this.newNode(LOOP_INIT); n.blockComments = comments; if (this.match(IDENTIFIER)) { if (this.t.token.value === "each") n.isEach = true; else this.t.unget(); } if (!this.parenFreeMode) this.mustMatch(LEFT_PAREN); x2 = this.x.pushTarget(n).nest(); x3 = this.x.update({ inForLoopInit: true }); n2 = null; if ((tt = this.peek(true)) !== SEMICOLON) { this.withContext(x3, function() { if (tt === VAR || tt === CONST) { this.t.get(); n2 = this.Variables(); } else if (tt === LET) { this.t.get(); if (this.peek() === LEFT_PAREN) { n2 = this.LetBlock(false); } else { // Let in for head, we need to add an implicit block // around the rest of the for. this.x.parentBlock = n; n.varDecls = []; n2 = this.Variables(); } } else { n2 = this.Expression(); } }); } if (n2 && this.match(IN)) { n.type = FOR_IN; this.withContext(x3, function() { n.object = this.Expression(); if (n2.type === VAR || n2.type === LET) { c = n2.children; // Destructuring turns one decl into multiples, so either // there must be only one destructuring or only one // decl. if (c.length !== 1 && n2.destructurings.length !== 1) { // FIXME: this.fail ? throw new SyntaxError("Invalid for..in left-hand side", this.filename, n2.lineno); } if (n2.destructurings.length > 0) { n.iterator = n2.destructurings[0]; } else { n.iterator = c[0]; } n.varDecl = n2; } else { if (n2.type === ARRAY_INIT || n2.type === OBJECT_INIT) { n2.destructuredNames = this.checkDestructuring(n2); } n.iterator = n2; } }); } else { x3.inForLoopInit = false; n.setup = n2; this.mustMatch(SEMICOLON); if (n.isEach) this.fail("Invalid for each..in loop"); this.withContext(x3, function() { n.condition = (this.peek(true) === SEMICOLON) ? null : this.Expression(); this.mustMatch(SEMICOLON); tt2 = this.peek(true); n.update = (this.parenFreeMode ? tt2 === LEFT_CURLY || definitions.isStatementStartCode[tt2] : tt2 === RIGHT_PAREN) ? null : this.Expression(); }); } if (!this.parenFreeMode) this.mustMatch(RIGHT_PAREN); this.withContext(x2, function() { n.body = this.Statement(); }); return n; case WHILE: n = this.newNode({ isLoop: true }); n.blockComments = comments; n.condition = this.HeadExpression(); x2 = this.x.pushTarget(n).nest(); this.withContext(x2, function() { n.body = this.Statement(); }); return n; case DO: n = this.newNode({ isLoop: true }); n.blockComments = comments; x2 = this.x.pushTarget(n).next(); this.withContext(x2, function() { n.body = this.Statement(); }); this.mustMatch(WHILE); n.condition = this.HeadExpression(); // <script language="JavaScript"> (without version hints) may need // automatic semicolon insertion without a newline after do-while. // See http://bugzilla.mozilla.org/show_bug.cgi?id=238945. this.match(SEMICOLON); return n; case BREAK: case CONTINUE: n = this.newNode(); n.blockComments = comments; // handle the |foo: break foo;| corner case x2 = this.x.pushTarget(n); if (this.peekOnSameLine() === IDENTIFIER) { this.t.get(); n.label = this.t.token.value; } if (n.label) { n.target = x2.labeledTargets.find(function(target) { return target.labels.has(n.label) }); } else if (tt === CONTINUE) { n.target = x2.defaultLoopTarget; } else { n.target = x2.defaultTarget; } if (!n.target) this.fail("Invalid " + ((tt === BREAK) ? "break" : "continue")); if (!n.target.isLoop && tt === CONTINUE) this.fail("Invalid continue"); break; case TRY: n = this.newNode({ catchClauses: [] }); n.blockComments = comments; n.tryBlock = this.Block(); while (this.match(CATCH)) { n2 = this.newNode(); p = this.MaybeLeftParen(); switch (this.t.get()) { case LEFT_BRACKET: case LEFT_CURLY: // Destructured catch identifiers. this.t.unget(); n2.varName = this.DestructuringExpression(true); break; case IDENTIFIER: n2.varName = this.t.token.value; break; default: this.fail("missing identifier in catch"); break; } if (this.match(IF)) { if (!this.mozillaMode) this.fail("Illegal catch guard"); if (n.catchClauses.length && !n.catchClauses.top().guard) this.fail("Guarded catch after unguarded"); n2.guard = this.Expression(); } this.MaybeRightParen(p); n2.block = this.Block(); n.catchClauses.push(n2); } if (this.match(FINALLY)) n.finallyBlock = this.Block(); if (!n.catchClauses.length && !n.finallyBlock) this.fail("Invalid try statement"); return n; case CATCH: case FINALLY: this.fail(definitions.tokens[tt] + " without preceding try"); case THROW: n = this.newNode(); n.exception = this.Expression(); break; case RETURN: n = this.ReturnOrYield(); break; case WITH: if (this.x.banWith()) this.fail("with statements not allowed in strict code or modules"); n = this.newNode(); n.blockComments = comments; n.object = this.HeadExpression(); x2 = this.x.pushTarget(n).next(); this.withContext(x2, function() { n.body = this.Statement(); }); return n; case VAR: case CONST: n = this.Variables(); break; case LET: if (this.peek() === LEFT_PAREN) { n = this.LetBlock(true); return n; } n = this.Variables(); break; case DEBUGGER: n = this.newNode(); break; case NEWLINE: case SEMICOLON: n = this.newNode({ type: SEMICOLON }); n.blockComments = comments; n.expression = null; return n; case IDENTIFIER: case USE: case MODULE: switch (this.t.token.value) { case "use": if (!isPragmaToken(this.peekOnSameLine())) { this.t.unget(); break; } return this.newNode({ type: USE, params: this.Pragmas() }); case "module": if (!this.x.modulesAllowed()) this.fail("module declaration not at top level"); this.x.parentScript.hasModules = true; tt = this.peekOnSameLine(); if (tt !== IDENTIFIER && tt !== LEFT_CURLY) { this.t.unget(); break; } n = this.newNode({ type: MODULE }); n.blockComments = comments; this.mustMatch(IDENTIFIER); label = this.t.token.value; if (this.match(LEFT_CURLY)) { n.name = label; n.body = this.Script(true, false); n.module = new Module(n); this.mustMatch(RIGHT_CURLY); this.x.parentScript.modDefns.set(n.name, n); return n; } this.t.unget(); this.ModuleVariables(n); return n; default: tt = this.peek(); // Labeled statement. if (tt === COLON) { label = this.t.token.value; if (this.x.allLabels.has(label)) this.fail("Duplicate label: " + label); this.t.get(); n = this.newNode({ type: LABEL, label: label }); n.blockComments = comments; x2 = this.x.pushLabel(label).nest(); this.withContext(x2, function() { n.statement = this.Statement(); }); n.target = (n.statement.type === LABEL) ? n.statement.target : n.statement; return n; } // FALL THROUGH } // FALL THROUGH default: // Expression statement. // We unget the current token to parse the expression as a whole. n = this.newNode({ type: SEMICOLON }); this.t.unget(); n.blockComments = comments; n.expression = this.Expression(); n.end = n.expression.end; break; } n.blockComments = comments; this.MagicalSemicolon(); return n; } /* * isPragmaToken :: (number) -> boolean */ function isPragmaToken(tt) { switch (tt) { case IDENTIFIER: case STRING: case NUMBER: case NULL: case TRUE: case FALSE: return true; } return false; } /* * Pragmas :: () -> Array[Array[token]] */ Pp.Pragmas = function Pragmas() { var pragmas = []; do { pragmas.push(this.Pragma()); } while (this.match(COMMA)); this.MagicalSemicolon(); return pragmas; } /* * Pragmas :: () -> Array[token] */ Pp.Pragma = function Pragma() { var items = []; var tt; do { tt = this.t.get(true); items.push(this.t.token); } while (isPragmaToken(this.peek())); return items; } /* * MagicalSemicolon :: () -> void */ Pp.MagicalSemicolon = function MagicalSemicolon() { var tt; if (this.t.lineno === this.t.token.lineno) { tt = this.peekOnSameLine(); if (tt !== END && tt !== NEWLINE && tt !== SEMICOLON && tt !== RIGHT_CURLY) this.fail("missing ; before statement"); } this.match(SEMICOLON); } /* * ReturnOrYield :: () -> (RETURN | YIELD) node */ Pp.ReturnOrYield = function ReturnOrYield() { var n, b, tt = this.t.token.type, tt2; var parentScript = this.x.parentScript; if (tt === RETURN) { if (!this.x.inFunction) this.fail("Return not in function"); } else /* if (tt === YIELD) */ { if (!this.x.inFunction) this.fail("Yield not in function"); parentScript.hasYield = true; } n = this.newNode({ value: undefined }); tt2 = (tt === RETURN) ? this.peekOnSameLine(true) : this.peek(true); if (tt2 !== END && tt2 !== NEWLINE && tt2 !== SEMICOLON && tt2 !== RIGHT_CURLY && (tt !== YIELD || (tt2 !== tt && tt2 !== RIGHT_BRACKET && tt2 !== RIGHT_PAREN && tt2 !== COLON && tt2 !== COMMA))) { if (tt === RETURN) { n.value = this.Expression(); parentScript.hasReturnWithValue = true; } else { n.value = this.AssignExpression(); } } else if (tt === RETURN) { parentScript.hasEmptyReturn = true; } return n; } /* * ModuleExpression :: () -> (STRING | IDENTIFIER | DOT) node */ Pp.ModuleExpression = function ModuleExpression() { return this.match(STRING) ? this.newNode() : this.QualifiedPath(); } /* * ImportPathList :: () -> Array[DOT node] */ Pp.ImportPathList = function ImportPathList() { var a = []; do { a.push(this.ImportPath()); } while (this.match(COMMA)); return a; } /* * ImportPath :: () -> DOT node */ Pp.ImportPath = function ImportPath() { var n = this.QualifiedPath(); if (!this.match(DOT)) { if (n.type === IDENTIFIER) this.fail("cannot import local variable"); return n; } var n2 = this.newNode(); n2.push(n); n2.push(this.ImportSpecifierSet()); return n2; } /* * ExplicitSpecifierSet :: (() -> node) -> OBJECT_INIT node */ Pp.ExplicitSpecifierSet = function ExplicitSpecifierSet(SpecifierRHS) { var n, n2, id, tt; n = this.newNode({ type: OBJECT_INIT }); this.mustMatch(LEFT_CURLY); if (!this.match(RIGHT_CURLY)) { do { id = this.Identifier(); if (this.match(COLON)) { n2 = this.newNode({ type: PROPERTY_INIT }); n2.push(id); n2.push(SpecifierRHS()); n.push(n2); } else { n.push(id); } } while (!this.match(RIGHT_CURLY) && this.mustMatch(COMMA)); } return n; } /* * ImportSpecifierSet :: () -> (IDENTIFIER | OBJECT_INIT) node */ Pp.ImportSpecifierSet = function ImportSpecifierSet() { var self = this; return this.match(MUL) ? this.newNode({ type: IDENTIFIER, name: "*" }) : ExplicitSpecifierSet(function() { return self.Identifier() }); } /* * Identifier :: () -> IDENTIFIER node */ Pp.Identifier = function Identifier() { this.mustMatch(IDENTIFIER); return this.newNode({ type: IDENTIFIER }); } /* * IdentifierName :: () -> IDENTIFIER node */ Pp.IdentifierName = function IdentifierName() { this.mustMatch(IDENTIFIER, true); return this.newNode({ type: IDENTIFIER }); } /* * QualifiedPath :: () -> (IDENTIFIER | DOT) node */ Pp.QualifiedPath = function QualifiedPath() { var n, n2; n = this.Identifier(); while (this.match(DOT)) { if (this.peek() !== IDENTIFIER) { // Unget the '.' token, which isn't part of the QualifiedPath. this.t.unget(); break; } n2 = this.newNode(); n2.push(n); n2.push(this.Identifier()); n = n2; } return n; } /* * ExportPath :: () -> (IDENTIFIER | DOT | OBJECT_INIT) node */ Pp.ExportPath = function ExportPath() { var self = this; if (this.peek() === LEFT_CURLY) return this.ExplicitSpecifierSet(function() { return self.QualifiedPath() }); return this.QualifiedPath(); } /* * ExportPathList :: () -> Array[(IDENTIFIER | DOT | OBJECT_INIT) node] */ Pp.ExportPathList = function ExportPathList() { var a = []; do { a.push(this.ExportPath()); } while (this.match(COMMA)); return a; } /* * FunctionDefinition :: (boolean, * DECLARED_FORM or EXPRESSED_FORM or STATEMENT_FORM, * [string] or null or undefined) * -> node */ Pp.FunctionDefinition = function FunctionDefinition(requireName, functionForm, comments) { var tt; var f = this.newNode({ params: [], paramComments: [] }); if (typeof comments === "undefined") comments = null; f.blockComments = comments; if (f.type !== FUNCTION) f.type = (f.value === "get") ? GETTER : SETTER; if (this.match(MUL)) f.isExplicitGenerator = true; if (this.match(IDENTIFIER, false, true)) f.name = this.t.token.value; else if (requireName) this.fail("missing function identifier"); var inModule = this.x.inModule; x2 = new StaticContext(null, null, inModule, true, this.x.strictMode); this.withContext(x2, function() { this.mustMatch(LEFT_PAREN); if (!this.match(RIGHT_PAREN)) { do { tt = this.t.get(); f.paramComments.push(this.t.lastBlockComment()); switch (tt) { case LEFT_BRACKET: case LEFT_CURLY: // Destructured formal parameters. this.t.unget(); f.params.push(this.DestructuringExpression()); break; case IDENTIFIER: f.params.push(this.t.token.value); break; default: this.fail("missing formal parameter"); } } while (this.match(COMMA)); this.mustMatch(RIGHT_PAREN); } // Do we have an expression closure or a normal body? tt = this.t.get(true); if (tt !== LEFT_CURLY) this.t.unget(); if (tt !== LEFT_CURLY) { f.body = this.AssignExpression(); } else { f.body = this.Script(inModule, true); } }); if (tt === LEFT_CURLY) this.mustMatch(RIGHT_CURLY); f.end = this.t.token.end; f.functionForm = functionForm; if (functionForm === DECLARED_FORM) this.x.parentScript.funDecls.push(f); if (this.x.inModule && !f.isExplicitGenerator && f.body.hasYield) this.fail("yield in non-generator function"); if (f.isExplicitGenerator || f.body.hasYield) f.body = this.newNode({ type: GENERATOR, body: f.body }); return f; } /* * ModuleVariables :: (MODULE node) -> void * * Parses a comma-separated list of module declarations (and maybe * initializations). */ Pp.ModuleVariables = function ModuleVariables(n) { var n1, n2; do { n1 = this.Identifier(); if (this.match(ASSIGN)) { n2 = this.ModuleExpression(); n1.initializer = n2; if (n2.type === STRING) this.x.parentScript.modLoads.set(n1.value, n2.value); else this.x.parentScript.modAssns.set(n1.value, n1); } n.push(n1); } while (this.match(COMMA)); } /* * Variables :: () -> node * * Parses a comma-separated list of var declarations (and maybe * initializations). */ Pp.Variables = function Variables(letBlock) { var n, n2, ss, i, s, tt; tt = this.t.token.type; switch (tt) { case VAR: case CONST: s = this.x.parentScript; break; case LET: s = this.x.parentBlock; break; case LEFT_PAREN: tt = LET; s = letBlock; break; } n = this.newNode({ type: tt, destructurings: [] }); do { tt = this.t.get(); if (tt === LEFT_BRACKET || tt === LEFT_CURLY) { // Need to unget to parse the full destructured expression. this.t.unget(); var dexp = this.DestructuringExpression(true); n2 = this.newNode({ type: IDENTIFIER, name: dexp, readOnly: n.type === CONST }); n.push(n2); pushDestructuringVarDecls(n2.name.destructuredNames, s); n.destructurings.push({ exp: dexp, decl: n2 }); if (this.x.inForLoopInit && this.peek() === IN) { continue; } this.mustMatch(ASSIGN); if (this.t.token.assignOp) this.fail("Invalid variable initialization"); n2.blockComment = this.t.lastBlockComment(); n2.initializer = this.AssignExpression(); continue; } if (tt !== IDENTIFIER) this.fail("missing variable name"); n2 = this.newNode({ type: IDENTIFIER, name: this.t.token.value, readOnly: n.type === CONST }); n.push(n2); s.varDecls.push(n2); if (this.match(ASSIGN)) { var comment = this.t.lastBlockComment(); if (this.t.token.assignOp) this.fail("Invalid variable initialization"); n2.initializer = this.AssignExpression(); } else { var comment = this.t.lastBlockComment(); } n2.blockComment = comment; } while (this.match(COMMA)); return n; } /* * LetBlock :: (boolean) -> node * * Does not handle let inside of for loop init. */ Pp.LetBlock = function LetBlock(isStatement) { var n, n2; // t.token.type must be LET n = this.newNode({ type: LET_BLOCK, varDecls: [] }); this.mustMatch(LEFT_PAREN); n.variables = this.Variables(n); this.mustMatch(RIGHT_PAREN); if (isStatement && this.peek() !== LEFT_CURLY) { /* * If this is really an expression in let statement guise, then we * need to wrap the LET_BLOCK node in a SEMICOLON node so that we pop * the return value of the expression. */ n2 = this.newNode({ type: SEMICOLON, expression: n }); isStatement = false; } if (isStatement) n.block = this.Block(); else n.expression = this.AssignExpression(); return n; } Pp.checkDestructuring = function checkDestructuring(n, simpleNamesOnly) { if (n.type === ARRAY_COMP) this.fail("Invalid array comprehension left-hand side"); if (n.type !== ARRAY_INIT && n.type !== OBJECT_INIT) return; var lhss = {}; var nn, n2, idx, sub, cc, c = n.children; for (var i = 0, j = c.length; i < j; i++) { if (!(nn = c[i])) continue; if (nn.type === PROPERTY_INIT) { cc = nn.children; sub = cc[1]; idx = cc[0].value; } else if (n.type === OBJECT_INIT) { // Do we have destructuring shorthand {foo, bar}? sub = nn; idx = nn.value; } else { sub = nn; idx = i; } if (sub.type === ARRAY_INIT || sub.type === OBJECT_INIT) { lhss[idx] = this.checkDestructuring(sub, simpleNamesOnly); } else { if (simpleNamesOnly && sub.type !== IDENTIFIER) { // In declarations, lhs must be simple names this.fail("missing name in pattern"); } lhss[idx] = sub; } } return lhss; } Pp.DestructuringExpression = function DestructuringExpression(simpleNamesOnly) { var n = this.PrimaryExpression(); // Keep the list of lefthand sides for varDecls n.destructuredNames = this.checkDestructuring(n, simpleNamesOnly); return n; } Pp.GeneratorExpression = function GeneratorExpression(e) { return this.newNode({ type: GENERATOR, expression: e, tail: this.ComprehensionTail() }); } Pp.ComprehensionTail = function ComprehensionTail() { var body, n, n2, n3, p; // t.token.type must be FOR body = this.newNode({ type: COMP_TAIL }); do { // Comprehension tails are always for..in loops. n = this.newNode({ type: FOR_IN, isLoop: true }); if (this.match(IDENTIFIER)) { // But sometimes they're for each..in. if (this.mozillaMode && this.t.token.value === "each") n.isEach = true; else this.t.unget(); } p = this.MaybeLeftParen(); switch(this.t.get()) { case LEFT_BRACKET: case LEFT_CURLY: this.t.unget(); // Destructured left side of for in comprehension tails. n.iterator = this.DestructuringExpression(); break; case IDENTIFIER: n.iterator = n3 = this.newNode({ type: IDENTIFIER }); n3.name = n3.value; n.varDecl = n2 = this.newNode({ type: VAR }); n2.push(n3); this.x.parentScript.varDecls.push(n3); // Don't add to varDecls since the semantics of comprehensions is // such that the variables are in their own function when // desugared. break; default: this.fail("missing identifier"); } this.mustMatch(IN); n.object = this.Expression(); this.MaybeRightParen(p); body.push(n); } while (this.match(FOR)); // Optional guard. if (this.match(IF)) body.guard = this.HeadExpression(); return body; } Pp.HeadExpression = function HeadExpression() { var p = this.MaybeLeftParen(); var n = this.ParenExpression(); this.MaybeRightParen(p); if (p === END && !n.parenthesized) { var tt = this.peek(); if (tt !== LEFT_CURLY && !definitions.isStatementStartCode[tt]) this.fail("Unparenthesized head followed by unbraced body"); } return n; } Pp.ParenExpression = function ParenExpression() { // Always accept the 'in' operator in a parenthesized expression, // where it's unambiguous, even if we might be parsing the init of a // for statement. var x2 = this.x.update({ inForLoopInit: this.x.inForLoopInit && (this.t.token.type === LEFT_PAREN) }); var n = this.withContext(x2, function() { return this.Expression(); }); if (this.match(FOR)) { if (n.type === YIELD && !n.parenthesized) this.fail("Yield expression must be parenthesized"); if (n.type === COMMA && !n.parenthesized) this.fail("Generator expression must be parenthesized"); n = this.GeneratorExpression(n); } return n; } /* * Expression :: () -> node * * Top-down expression parser matched against SpiderMonkey. */ Pp.Expression = function Expression() { var n, n2; n = this.AssignExpression(); if (this.match(COMMA)) { n2 = this.newNode({ type: COMMA }); n2.push(n); n = n2; do { n2 = n.children[n.children.length-1]; if (n2.type === YIELD && !n2.parenthesized) this.fail("Yield expression must be parenthesized"); n.push(this.AssignExpression()); } while (this.match(COMMA)); } return n; } Pp.AssignExpression = function AssignExpression() { var n, lhs; // Have to treat yield like an operand because it could be the leftmost // operand of the expression. if (this.match(YIELD, true)) return this.ReturnOrYield(); n = this.newNode({ type: ASSIGN }); lhs = this.ConditionalExpression(); if (!this.match(ASSIGN)) { return lhs; } n.blockComment = this.t.lastBlockComment(); switch (lhs.type) { case OBJECT_INIT: case ARRAY_INIT: lhs.destructuredNames = this.checkDestructuring(lhs); // FALL THROUGH case IDENTIFIER: case DOT: case INDEX: case CALL: break; default: this.fail("Bad left-hand side of assignment"); break; } n.assignOp = lhs.assignOp = this.t.token.assignOp; n.push(lhs); n.push(this.AssignExpression()); return n; } Pp.ConditionalExpression = function ConditionalExpression() { var n, n2; n = this.OrExpression(); if (this.match(HOOK)) { n2 = n; n = this.newNode({ type: HOOK }); n.push(n2); var x2 = this.x.update({ inForLoopInit: false }); this.withContext(x2, function() { n.push(this.AssignExpression()); }); if (!this.match(COLON)) this.fail("missing : after ?"); n.push(this.AssignExpression()); } return n; } Pp.OrExpression = function OrExpression() { var n, n2; n = this.AndExpression(); while (this.match(OR)) { n2 = this.newNode(); n2.push(n); n2.push(this.AndExpression()); n = n2; } return n; } Pp.AndExpression = function AndExpression() { var n, n2; n = this.BitwiseOrExpression(); while (this.match(AND)) { n2 = this.newNode(); n2.push(n); n2.push(this.BitwiseOrExpression()); n = n2; } return n; } Pp.BitwiseOrExpression = function BitwiseOrExpression() { var n, n2; n = this.BitwiseXorExpression(); while (this.match(BITWISE_OR)) { n2 = this.newNode(); n2.push(n); n2.push(this.BitwiseXorExpression()); n = n2; } return n; } Pp.BitwiseXorExpression = function BitwiseXorExpression() { var n, n2; n = this.BitwiseAndExpression(); while (this.match(BITWISE_XOR)) { n2 = this.newNode(); n2.push(n); n2.push(this.BitwiseAndExpression()); n = n2; } return n; } Pp.BitwiseAndExpression = function BitwiseAndExpression() { var n, n2; n = this.EqualityExpression(); while (this.match(BITWISE_AND)) { n2 = this.newNode(); n2.push(n); n2.push(this.EqualityExpression()); n = n2; } return n; } Pp.EqualityExpression = function EqualityExpression() { var n, n2; n = this.RelationalExpression(); while (this.match(EQ) || this.match(NE) || this.match(STRICT_EQ) || this.match(STRICT_NE)) { n2 = this.newNode(); n2.push(n); n2.push(this.RelationalExpression()); n = n2; } return n; } Pp.RelationalExpression = function RelationalExpression() { var n, n2; var x2 = this.x.update({ inForLoopInit: false }); this.withContext(x2, function() { n = this.ShiftExpression(); while ((this.match(LT) || this.match(LE) || this.match(GE) || this.match(GT) || (!this.x.inForLoopInit && this.match(IN)) || this.match(INSTANCEOF))) { n2 = this.newNode(); n2.push(n); n2.push(this.ShiftExpression()); n = n2; } }); return n; } Pp.ShiftExpression = function ShiftExpression() { var n, n2; n = this.AddExpression(); while (this.match(LSH) || this.match(RSH) || this.match(URSH)) { n2 = this.newNode(); n2.push(n); n2.push(this.AddExpression()); n = n2; } return n; } Pp.AddExpression = function AddExpression() { var n, n2; n = this.MultiplyExpression(); while (this.match(PLUS) || this.match(MINUS)) { n2 = this.newNode(); n2.push(n); n2.push(this.MultiplyExpression()); n = n2; } return n; } Pp.MultiplyExpression = function MultiplyExpression() { var n, n2; n = this.UnaryExpression(); while (this.match(MUL) || this.match(DIV) || this.match(MOD)) { n2 = this.newNode(); n2.push(n); n2.push(this.UnaryExpression()); n = n2; } return n; } Pp.UnaryExpression = function UnaryExpression() { var n, n2, tt; switch (tt = this.t.get(true)) { case DELETE: case VOID: case TYPEOF: case NOT: case BITWISE_NOT: case PLUS: case MINUS: if (tt === PLUS) n = this.newNode({ type: UNARY_PLUS }); else if (tt === MINUS) n = this.newNode({ type: UNARY_MINUS }); else n = this.newNode(); n.push(this.UnaryExpression()); break; case INCREMENT: case DECREMENT: // Prefix increment/decrement. n = this.newNode(); n.push(this.MemberExpression(true)); break; default: this.t.unget(); n = this.MemberExpression(true); // Don't look across a newline boundary for a postfix {in,de}crement. if (this.t.tokens[(this.t.tokenIndex + this.t.lookahead - 1) & 3].lineno === this.t.lineno) { if (this.match(INCREMENT) || this.match(DECREMENT)) { n2 = this.newNode({ postfix: true }); n2.push(n); n = n2; } } break; } return n; } Pp.MemberExpression = function MemberExpression(allowCallSyntax) { var n, n2, name, tt; if (this.match(NEW)) { n = this.newNode(); n.push(this.MemberExpression(false)); if (this.match(LEFT_PAREN)) { n.type = NEW_WITH_ARGS; n.push(this.ArgumentList()); } } else { n = this.PrimaryExpression(); } while ((tt = this.t.get()) !== END) { switch (tt) { case DOT: n2 = this.newNode(); n2.push(n); n2.push(this.IdentifierName()); break; case LEFT_BRACKET: n2 = this.newNode({ type: INDEX }); n2.push(n); n2.push(this.Expression()); this.mustMatch(RIGHT_BRACKET); break; case LEFT_PAREN: if (allowCallSyntax) { n2 = this.newNode({ type: CALL }); n2.push(n); n2.push(this.ArgumentList()); break; } // FALL THROUGH default: this.t.unget(); return n; } n = n2; } return n; } Pp.ArgumentList = function ArgumentList() { var n, n2; n = this.newNode({ type: LIST }); if (this.match(RIGHT_PAREN, true)) return n; do { n2 = this.AssignExpression(); if (n2.type === YIELD && !n2.parenthesized && this.peek() === COMMA) this.fail("Yield expression must be parenthesized"); if (this.match(FOR)) { n2 = this.GeneratorExpression(n2); if (n.children.length > 1 || this.peek(true) === COMMA) this.fail("Generator expression must be parenthesized"); } n.push(n2); } while (this.match(COMMA)); this.mustMatch(RIGHT_PAREN); return n; } Pp.PrimaryExpression = function PrimaryExpression() { var n, n2, tt = this.t.get(true); switch (tt) { case FUNCTION: n = this.FunctionDefinition(false, EXPRESSED_FORM); break; case LEFT_BRACKET: n = this.newNode({ type: ARRAY_INIT }); while ((tt = this.peek(true)) !== RIGHT_BRACKET) { if (tt === COMMA) { this.t.get(); n.push(null); continue; } n.push(this.AssignExpression()); if (tt !== COMMA && !this.match(COMMA)) break; } // If we matched exactly one element and got a FOR, we have an // array comprehension. if (n.children.length === 1 && this.match(FOR)) { n2 = this.newNode({ type: ARRAY_COMP, expression: n.children[0], tail: this.ComprehensionTail() }); n = n2; } this.mustMatch(RIGHT_BRACKET); break; case LEFT_CURLY: var id, fd; n = this.newNode({ type: OBJECT_INIT }); object_init: if (!this.match(RIGHT_CURLY)) { do { tt = this.t.get(); if ((this.t.token.value === "get" || this.t.token.value === "set") && this.peek() === IDENTIFIER) { n.push(this.FunctionDefinition(true, EXPRESSED_FORM)); } else { var comments = this.t.blockComments; switch (tt) { case IDENTIFIER: case NUMBER: case STRING: id = this.newNode({ type: IDENTIFIER }); break; case RIGHT_CURLY: break object_init; default: if (this.t.token.value in definitions.keywords) { id = this.newNode({ type: IDENTIFIER }); break; } this.fail("Invalid property name"); } if (this.match(COLON)) { n2 = this.newNode({ type: PROPERTY_INIT }); n2.push(id); n2.push(this.AssignExpression()); n2.blockComments = comments; n.push(n2); } else { // Support, e.g., |var {x, y} = o| as destructuring shorthand // for |var {x: x, y: y} = o|, per proposed JS2/ES4 for JS1.8. if (this.peek() !== COMMA && this.peek() !== RIGHT_CURLY) this.fail("missing : after property"); n.push(id); } } } while (this.match(COMMA)); this.mustMatch(RIGHT_CURLY); } break; case LEFT_PAREN: n = this.ParenExpression(); this.mustMatch(RIGHT_PAREN); n.parenthesized = true; break; case LET: n = this.LetBlock(false); break; case NULL: case THIS: case TRUE: case FALSE: case IDENTIFIER: case NUMBER: case STRING: case REGEXP: n = this.newNode(); break; default: this.fail("missing operand; found " + definitions.tokens[tt]); break; } return n; } /* * parse :: (source, filename, line number) -> node */ function parse(s, f, l) { var t = new Tokenizer(s, f, l, options.allowHTMLComments); var p = new Parser(t); return p.Script(false, false, true); } /* * parseFunction :: (source, boolean, * DECLARED_FORM or EXPRESSED_FORM or STATEMENT_FORM, * filename, line number) * -> node */ function parseFunction(s, requireName, form, f, l) { var t = new Tokenizer(s, f, l); var p = new Parser(t); p.x = new StaticContext(null, null, false, false, false); return p.FunctionDefinition(requireName, form); } /* * parseStdin :: (source, {line number}, string, (string) -> boolean) -> program node */ function parseStdin(s, ln, prefix, isCommand) { // the special .begin command is only recognized at the beginning if (s.match(/^[\s]*\.begin[\s]*$/)) { ++ln.value; return parseMultiline(ln, prefix); } // commands at the beginning are treated as the entire input if (isCommand(s.trim())) s = ""; for (;;) { try { var t = new Tokenizer(s, "stdin", ln.value, false); var p = new Parser(t); var n = p.Script(false, false); ln.value = t.lineno; return n; } catch (e) { if (!p.unexpectedEOF) throw e; // commands in the middle are not treated as part of the input var more; do { if (prefix) putstr(prefix); more = readline(); if (!more) throw e; } while (isCommand(more.trim())); s += "\n" + more; } } } /* * parseMultiline :: ({line number}, string | null) -> program node */ function parseMultiline(ln, prefix) { var s = ""; for (;;) { if (prefix) putstr(prefix); var more = readline(); if (more === null) return null; // the only command recognized in multiline mode is .end if (more.match(/^[\s]*\.end[\s]*$/)) break; s += "\n" + more; } var t = new Tokenizer(s, "stdin", ln.value, false); var p = new Parser(t); var n = p.Script(false, false); ln.value = t.lineno; return n; } exports.parse = parse; exports.parseStdin = parseStdin; exports.parseFunction = parseFunction; exports.Node = Node; exports.DECLARED_FORM = DECLARED_FORM; exports.EXPRESSED_FORM = EXPRESSED_FORM; exports.STATEMENT_FORM = STATEMENT_FORM; exports.Tokenizer = Tokenizer; exports.Parser = Parser; exports.Module = Module; exports.Export = Export; }); /* ***** 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> * Stephan Herhut <stephan.a.herhut@intel.com> * 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('ace/narcissus/lexer', ['require', 'exports', 'module' , 'ace/narcissus/definitions'], function(require, exports, module) { var definitions = require('./definitions'); // 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; } } /* * Since JavaScript provides no convenient way to determine if a * character is in a particular Unicode category, we use * metacircularity to accomplish this (oh yeaaaah!) */ function isValidIdentifierChar(ch, first) { // check directly for ASCII if (ch <= "\u007F") { if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '$' || ch === '_' || (!first && (ch >= '0' && ch <= '9'))) { return true; } return false; } // create an object to test this in var x = {}; x["x"+ch] = true; x[ch] = true; // then use eval to determine if it's a valid character var valid = false; try { valid = (Function("x", "return (x." + (first?"":"x") + ch + ");")(x) === true); } catch (ex) {} return valid; } function isIdentifier(str) { if (typeof str !== "string") return false; if (str.length === 0) return false; if (!isValidIdentifierChar(str[0], true)) return false; for (var i = 1; i < str.length; i++) { if (!isValidIdentifierChar(str[i], false)) return false; } return true; } /* * Tokenizer :: (source, filename, line number, boolean) -> Tokenizer */ function Tokenizer(s, f, l, allowHTMLComments) { this.cursor = 0; this.source = String(s); this.tokens = []; this.tokenIndex = 0; this.lookahead = 0; this.scanNewlines = false; this.filename = f || ""; this.lineno = l || 1; this.allowHTMLComments = allowHTMLComments; this.blockComments = null; } 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, keywordIsName) { return this.get(scanOperand, keywordIsName) === tt || this.unget(); }, mustMatch: function (tt, keywordIsName) { if (!this.match(tt, false, keywordIsName)) { 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; }, lastBlockComment: function() { var length = this.blockComments.length; return length ? this.blockComments[length - 1] : null; }, // Eat comments and whitespace. skip: function () { var input = this.source; this.blockComments = []; for (;;) { var ch = input[this.cursor++]; var next = input[this.cursor]; // handle \r, \r\n and (always preferable) \n if (ch === '\r') { // if the next character is \n, we don't care about this at all if (next === '\n') continue; // otherwise, we want to consider this as a newline ch = '\n'; } if (ch === '\n' && !this.scanNewlines) { this.lineno++; } else if (ch === '/' && next === '*') { var commentStart = ++this.cursor; for (;;) { ch = input[this.cursor++]; if (ch === undefined) throw this.newSyntaxError("Unterminated comment"); if (ch === '*') { next = input[this.cursor]; if (next === '/') { var commentEnd = this.cursor - 1; this.cursor++; break; } } else if (ch === '\n') { this.lineno++; } } this.blockComments.push(input.substring(commentStart, commentEnd)); } else if ((ch === '/' && next === '/') || (this.allowHTMLComments && ch === '<' && next === '!' && input[this.cursor + 1] === '-' && input[this.cursor + 2] === '-' && (this.cursor += 2))) { this.cursor++; for (;;) { ch = input[this.cursor++]; next = input[this.cursor]; if (ch === undefined) return; if (ch === '\r') { // check for \r\n if (next !== '\n') ch = '\n'; } if (ch === '\n') { if (this.scanNewlines) { this.cursor--; } else { this.lineno++; } break; } } } else if (!(ch in definitions.whitespace)) { 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( input.substring(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( input.substring(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; if (input.length <= this.cursor) throw this.newSyntaxError("Unterminated string literal"); while ((ch = input[this.cursor++]) !== delim) { if (ch == '\n' || ch == '\r') throw this.newSyntaxError("Unterminated string literal"); 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 lexIdent: function (ch, keywordIsName) { var token = this.token; var id = ch; while ((ch = this.getValidIdentifierChar(false)) !== null) { id += ch; } token.type = IDENTIFIER; token.value = id; if (keywordIsName) return; var kw; if (this.parser.mozillaMode) { kw = definitions.mozillaKeywords[id]; if (kw) { token.type = kw; return; } } if (this.parser.x.strictMode) { kw = definitions.strictKeywords[id]; if (kw) { token.type = kw; return; } } kw = definitions.keywords[id]; if (kw) token.type = kw; }, /* * Tokenizer.get :: ([boolean[, boolean]]) -> token type * * Consume input *only* if there is no lookahead. * Dispatch to the appropriate lexing function depending on the input. */ get: function (scanOperand, keywordIsName) { 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 ich = this.getValidIdentifierChar(true); var ch = (ich === null) ? input[this.cursor++] : null; if (ich !== null) { this.lexIdent(ich, keywordIsName); } 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' || ch === '\r')) { // if this was a \r, look for \r\n if (ch === '\r' && input[this.cursor] === '\n') this.cursor++; 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) { m = (this.filename ? this.filename + ":" : "") + this.lineno + ": " + m; var e = new SyntaxError(m, this.filename, this.lineno); e.source = this.source; e.cursor = this.lookahead ? this.tokens[(this.tokenIndex + this.lookahead) & 3].start : this.cursor; return e; }, /* Gets a single valid identifier char from the input stream, or null * if there is none. */ getValidIdentifierChar: function(first) { var input = this.source; if (this.cursor >= input.length) return null; var ch = input[this.cursor]; // first check for \u escapes if (ch === '\\' && input[this.cursor+1] === 'u') { // get the character value try { ch = String.fromCharCode(parseInt( input.substring(this.cursor + 2, this.cursor + 6), 16)); } catch (ex) { return null; } this.cursor += 5; } var valid = isValidIdentifierChar(ch, first); if (valid) this.cursor++; return (valid ? ch : null); }, }; exports.isIdentifier = isIdentifier; exports.Tokenizer = Tokenizer; }); /* ***** 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('ace/narcissus/definitions', ['require', 'exports', 'module' ], function(require, exports, module) { 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", // Contextual keywords. "IMPLEMENTS", "INTERFACE", "LET", "MODULE", "PACKAGE", "PRIVATE", "PROTECTED", "PUBLIC", "STATIC", "USE", "YIELD", // Terminals. "IDENTIFIER", "NUMBER", "STRING", "REGEXP", // Keywords. "break", "case", "catch", "const", "continue", "debugger", "default", "delete", "do", "else", "export", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", ]; var strictKeywords = { __proto__: null, "implements": true, "interface": true, "let": true, //"module": true, "package": true, "private": true, "protected": true, "public": true, "static": true, "use": true, "yield": true }; var statementStartTokens = [ "break", "const", "continue", "debugger", "do", "for", "if", "let", "return", "switch", "throw", "try", "var", "yield", "while", "with", ]; // Whitespace characters (see ECMA-262 7.2) var whitespaceChars = [ // normal whitespace: "\u0009", "\u000B", "\u000C", "\u0020", "\u00A0", "\uFEFF", // high-Unicode whitespace: "\u1680", "\u180E", "\u2000", "\u2001", "\u2002", "\u2003", "\u2004", "\u2005", "\u2006", "\u2007", "\u2008", "\u2009", "\u200A", "\u202F", "\u205F", "\u3000" ]; var whitespace = {}; for (var i = 0; i < whitespaceChars.length; i++) { whitespace[whitespaceChars[i]] = true; } // 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}; var mozillaKeywords = {__proto__: null}; // Define const END, etc., based on the token names. Also map name to index. var tokenIds = {}; var hostSupportsEvalConst = (function() { try { return eval("(function(s) { eval(s); return x })('const x = true;')"); } catch (e) { return false; } })(); // Building up a string to be eval'd in different contexts. var consts = hostSupportsEvalConst ? "const " : "var "; 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(); if (name === "LET" || name === "YIELD") mozillaKeywords[name] = i; if (strictKeywords[name]) strictKeywords[name] = i; 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 defineGetterSetter(obj, prop, getter, setter, dontDelete, dontEnum) { Object.defineProperty(obj, prop, { get: getter, set: setter, configurable: !dontDelete, enumerable: !dontEnum }); } function defineMemoGetter(obj, prop, fn, dontDelete, dontEnum) { Object.defineProperty(obj, prop, { get: function() { var val = fn(); defineProperty(obj, prop, val, dontDelete, true, dontEnum); return val; }, configurable: true, 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\]/); } var Fpapply = Function.prototype.apply; function apply(f, o, a) { return Fpapply.call(f, [o].concat(a)); } var applyNew; // ES5's bind is a simpler way to implement applyNew if (Function.prototype.bind) { applyNew = function applyNew(f, a) { return new (f.bind.apply(f, [,].concat(Array.prototype.slice.call(a))))(); }; } else { applyNew = function applyNew(f, a) { switch (a.length) { case 0: return new f(); case 1: return new f(a[0]); case 2: return new f(a[0], a[1]); case 3: return new f(a[0], a[1], a[2]); default: var argStr = "a[0]"; for (var i = 1, n = a.length; i < n; i++) argStr += ",a[" + i + "]"; return eval("new f(" + argStr + ")"); } }; } function getPropertyDescriptor(obj, name) { while (obj) { if (({}).hasOwnProperty.call(obj, name)) return Object.getOwnPropertyDescriptor(obj, name); obj = Object.getPrototypeOf(obj); } } function getPropertyNames(obj) { var table = Object.create(null, {}); while (obj) { var names = Object.getOwnPropertyNames(obj); for (var i = 0, n = names.length; i < n; i++) table[names[i]] = true; obj = Object.getPrototypeOf(obj); } return Object.keys(table); } function getOwnProperties(obj) { var map = {}; for (var name in Object.getOwnPropertyNames(obj)) map[name] = Object.getOwnPropertyDescriptor(obj, name); return map; } function blacklistHandler(target, blacklist) { var mask = Object.create(null, {}); var redirect = Dict.create(blacklist).mapObject(function(name) { return mask; }); return mixinHandler(redirect, target); } function whitelistHandler(target, whitelist) { var catchall = Object.create(null, {}); var redirect = Dict.create(whitelist).mapObject(function(name) { return target; }); return mixinHandler(redirect, catchall); } /* * Mixin proxies break the single-inheritance model of prototypes, so * the handler treats all properties as own-properties: * * X * | * +------------+------------+ * | O | * | | | * | O O O | * | | | | | * | O O O O | * | | | | | | * | O O O O O | * | | | | | | | * +-(*)--(w)--(x)--(y)--(z)-+ */ function mixinHandler(redirect, catchall) { function targetFor(name) { return hasOwn(redirect, name) ? redirect[name] : catchall; } function getMuxPropertyDescriptor(name) { var desc = getPropertyDescriptor(targetFor(name), name); if (desc) desc.configurable = true; return desc; } function getMuxPropertyNames() { var names1 = Object.getOwnPropertyNames(redirect).filter(function(name) { return name in redirect[name]; }); var names2 = getPropertyNames(catchall).filter(function(name) { return !hasOwn(redirect, name); }); return names1.concat(names2); } function enumerateMux() { var result = Object.getOwnPropertyNames(redirect).filter(function(name) { return name in redirect[name]; }); for (name in catchall) { if (!hasOwn(redirect, name)) result.push(name); }; return result; } function hasMux(name) { return name in targetFor(name); } return { getOwnPropertyDescriptor: getMuxPropertyDescriptor, getPropertyDescriptor: getMuxPropertyDescriptor, getOwnPropertyNames: getMuxPropertyNames, defineProperty: function(name, desc) { Object.defineProperty(targetFor(name), name, desc); }, "delete": function(name) { var target = targetFor(name); return delete target[name]; }, // FIXME: ha ha ha fix: function() { }, has: hasMux, hasOwn: hasMux, get: function(receiver, name) { var target = targetFor(name); return target[name]; }, set: function(receiver, name, val) { var target = targetFor(name); target[name] = val; return true; }, enumerate: enumerateMux, keys: enumerateMux }; } 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); } }; } var hasOwnProperty = ({}).hasOwnProperty; function hasOwn(obj, name) { return hasOwnProperty.call(obj, name); } function Dict(table, size) { this.table = table || Object.create(null, {}); this.size = size || 0; } Dict.create = function(table) { var init = Object.create(null, {}); var size = 0; var names = Object.getOwnPropertyNames(table); for (var i = 0, n = names.length; i < n; i++) { var name = names[i]; init[name] = table[name]; size++; } return new Dict(init, size); }; Dict.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]); }, map: function(f) { var table1 = this.table; var table2 = Object.create(null, {}); this.forEach(function(key, val) { table2[key] = f.call(this, val, key); }); return new Dict(table2, this.size); }, mapObject: function(f) { var table1 = this.table; var table2 = Object.create(null, {}); this.forEach(function(key, val) { table2[key] = f.call(this, val, key); }); return table2; }, toObject: function() { return this.mapObject(function(val) { return val; }); }, choose: function() { return Object.getOwnPropertyNames(this.table)[0]; }, remove: function(x) { if (hasOwnProperty.call(this.table, x)) { this.size--; delete this.table[x]; } }, copy: function() { var table = Object.create(null, {}); for (var key in this.table) table[key] = this.table[key]; return new Dict(table, this.size); }, keys: function() { return Object.keys(this.table); }, toString: function() { return "[object Dict]" } }; var _WeakMap = typeof WeakMap === "function" ? WeakMap : (function() { // shim for ES6 WeakMap with poor asymptotics function WeakMap(array) { this.array = array || []; } function searchMap(map, key, found, notFound) { var a = map.array; for (var i = 0, n = a.length; i < n; i++) { var pair = a[i]; if (pair.key === key) return found(pair, i); } return notFound(); } WeakMap.prototype = { has: function(x) { return searchMap(this, x, function() { return true }, function() { return false }); }, set: function(x, v) { var a = this.array; searchMap(this, x, function(pair) { pair.value = v }, function() { a.push({ key: x, value: v }) }); }, get: function(x) { return searchMap(this, x, function(pair) { return pair.value }, function() { return null }); }, "delete": function(x) { var a = this.array; searchMap(this, x, function(pair, i) { a.splice(i, 1) }, function() { }); }, toString: function() { return "[object WeakMap]" } }; return WeakMap; })(); // 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); } } }; if (!Array.prototype.copy) { defineProperty(Array.prototype, "copy", function() { var result = []; for (var i = 0, n = this.length; i < n; i++) result[i] = this[i]; return result; }, false, false, true); } if (!Array.prototype.top) { defineProperty(Array.prototype, "top", function() { return this.length && this[this.length-1]; }, false, false, true); } exports.tokens = tokens; exports.whitespace = whitespace; exports.opTypeNames = opTypeNames; exports.keywords = keywords; exports.mozillaKeywords = mozillaKeywords; exports.strictKeywords = strictKeywords; exports.isStatementStartCode = isStatementStartCode; exports.tokenIds = tokenIds; exports.consts = consts; exports.assignOps = assignOps; exports.defineGetter = defineGetter; exports.defineGetterSetter = defineGetterSetter; exports.defineMemoGetter = defineMemoGetter; exports.defineProperty = defineProperty; exports.isNativeCode = isNativeCode; exports.apply = apply; exports.applyNew = applyNew; exports.mixinHandler = mixinHandler; exports.whitelistHandler = whitelistHandler; exports.blacklistHandler = blacklistHandler; exports.makePassthruHandler = makePassthruHandler; exports.Dict = Dict; exports.WeakMap = _WeakMap; exports.Stack = Stack; }); /* ***** 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 ***** */ define('ace/narcissus/options', ['require', 'exports', 'module' ], function(require, exports, module) { // Global variables to hide from the interpreter exports.hiddenHostGlobals = { Narcissus: true }; // Desugar SpiderMonkey language extensions? exports.desugarExtensions = false; // Allow HTML comments? exports.allowHTMLComments = false; // Allow non-standard Mozilla extensions? exports.mozillaMode = true; // Allow experimental paren-free mode? exports.parenFreeMode = false; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/mode/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/html_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/html'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var Mode = function() { var highlighter = new HtmlHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$behaviour = new XmlBehaviour(); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { return 0; }; this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); 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); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/html_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HtmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", regex : "<(?=\s*script\\b)", next : "script" }, { token : "meta.tag", regex : "<(?=\s*style\\b)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] }; xmlUtil.tag(this.$rules, "tag", "start"); xmlUtil.tag(this.$rules, "style", "css-start"); xmlUtil.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(HtmlHighlightRules, TextHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/folding/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/mixed', 'ace/mode/folding/xml', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function() { MixedFoldMode.call(this, new XmlFoldMode({ // void elements "area": 1, "base": 1, "br": 1, "col": 1, "command": 1, "embed": 1, "hr": 1, "img": 1, "input": 1, "keygen": 1, "link": 1, "meta": 1, "param": 1, "source": 1, "track": 1, "wbr": 1, // optional tags "li": 1, "dt": 1, "dd": 1, "p": 1, "rt": 1, "rp": 1, "optgroup": 1, "option": 1, "colgroup": 1, "td": 1, "th": 1 }), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); define('ace/mode/folding/mixed', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/monokai', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-monokai"; exports.cssText = "\ .ace-monokai .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-monokai .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-monokai .ace_gutter {\ background: #292a24;\ color: #f1f1f1;\ }\ \ .ace-monokai .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-monokai .ace_scroller {\ background-color: #272822;\ }\ \ .ace-monokai .ace_text-layer {\ cursor: text;\ color: #F8F8F2;\ }\ \ .ace-monokai .ace_cursor {\ border-left: 2px solid #F8F8F0;\ }\ \ .ace-monokai .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #F8F8F0;\ }\ \ .ace-monokai .ace_marker-layer .ace_selection {\ background: #49483E;\ }\ \ .ace-monokai.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #272822;\ border-radius: 2px;\ }\ \ .ace-monokai .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-monokai .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #49483E;\ }\ \ .ace-monokai .ace_marker-layer .ace_active_line {\ background: #49483E;\ }\ .ace-monokai .ace_gutter_active_line {\ background-color: #191916;\ }\ \ .ace-monokai .ace_marker-layer .ace_selected_word {\ border: 1px solid #49483E;\ }\ \ .ace-monokai .ace_invisible {\ color: #49483E;\ }\ \ .ace-monokai .ace_keyword, .ace-monokai .ace_meta {\ color:#F92672;\ }\ \ .ace-monokai .ace_constant.ace_language {\ color:#AE81FF;\ }\ \ .ace-monokai .ace_constant.ace_numeric {\ color:#AE81FF;\ }\ \ .ace-monokai .ace_constant.ace_other {\ color:#AE81FF;\ }\ \ .ace-monokai .ace_invalid {\ color:#F8F8F0;\ background-color:#F92672;\ }\ \ .ace-monokai .ace_invalid.ace_deprecated {\ color:#F8F8F0;\ background-color:#AE81FF;\ }\ \ .ace-monokai .ace_support.ace_constant {\ color:#66D9EF;\ }\ \ .ace-monokai .ace_fold {\ background-color: #A6E22E;\ border-color: #F8F8F2;\ }\ \ .ace-monokai .ace_support.ace_function {\ color:#66D9EF;\ }\ \ .ace-monokai .ace_storage {\ color:#F92672;\ }\ \ .ace-monokai .ace_storage.ace_type, .ace-monokai .ace_support.ace_type{\ font-style:italic;\ color:#66D9EF;\ }\ \ .ace-monokai .ace_variable {\ color:#A6E22E;\ }\ \ .ace-monokai .ace_variable.ace_parameter {\ font-style:italic;\ color:#FD971F;\ }\ \ .ace-monokai .ace_string {\ color:#E6DB74;\ }\ \ .ace-monokai .ace_comment {\ color:#75715E;\ }\ \ .ace-monokai .ace_entity.ace_other.ace_attribute-name {\ color:#A6E22E;\ }\ \ .ace-monokai .ace_entity.ace_name.ace_function {\ color:#A6E22E;\ }\ \ .ace-monokai .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Colin Gourlay <colin DOT j DOT gourlay AT gmail DOT com> * Lee Gao * * 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 ***** */ define('ace/mode/lua', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/lua_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules; var Mode = function() { this.$tokenizer = new Tokenizer(new LuaHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var chunks = ["function", "then", "do", "repeat"]; if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } else { for (var i in tokens){ var token = tokens[i]; if (token.type != "keyword") continue; var chunk_i = chunks.indexOf(token.value); if (chunk_i != -1){ indent += tab; break; } } } } return indent; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/lua_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LuaHighlightRules = function() { var keywords = lang.arrayToMap( ("break|do|else|elseif|end|for|function|if|in|local|repeat|"+ "return|then|until|while|or|and|not").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false|nil|_G|_VERSION").split("|") ); var builtinFunctions = lang.arrayToMap( ("string|xpcall|package|tostring|print|os|unpack|require|"+ "getfenv|setmetatable|next|assert|tonumber|io|rawequal|"+ "collectgarbage|getmetatable|module|rawset|math|debug|"+ "pcall|table|newproxy|type|coroutine|_G|select|gcinfo|"+ "pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|"+ "load|error|loadfile|"+ "sub|upper|len|gfind|rep|find|match|char|dump|gmatch|"+ "reverse|byte|format|gsub|lower|preload|loadlib|loaded|"+ "loaders|cpath|config|path|seeall|exit|setlocale|date|"+ "getenv|difftime|remove|time|clock|tmpname|rename|execute|"+ "lines|write|close|flush|open|output|type|read|stderr|"+ "stdin|input|stdout|popen|tmpfile|log|max|acos|huge|"+ "ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|"+ "frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|"+ "atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|"+ "gethook|setmetatable|setlocal|traceback|setfenv|getinfo|"+ "setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|"+ "foreachi|maxn|foreach|concat|sort|remove|resume|yield|"+ "status|wrap|create|running").split("|") ); var stdLibaries = lang.arrayToMap( ("string|package|os|io|math|debug|table|coroutine").split("|") ); var metatableMethods = lang.arrayToMap( ("__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|"+ "__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber").split("|") ); var futureReserved = lang.arrayToMap( ("").split("|") ); var deprecatedIn5152 = lang.arrayToMap( ("setn|foreach|foreachi|gcinfo|log10|maxn").split("|") ); var strPre = ""; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var integer = "(?:" + decimalInteger + "|" + hexInteger + ")"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var floatNumber = "(?:" + pointFloat + ")"; var comment_stack = []; this.$rules = { "start" : // bracketed comments [{ token : "comment", // --[[ comment regex : strPre + '\\-\\-\\[\\[.*\\]\\]' }, { token : "comment", // --[=[ comment regex : strPre + '\\-\\-\\[\\=\\[.*\\]\\=\\]' }, { token : "comment", // --[==[ comment regex : strPre + '\\-\\-\\[\\={2}\\[.*\\]\\={2}\\]' }, { token : "comment", // --[===[ comment regex : strPre + '\\-\\-\\[\\={3}\\[.*\\]\\={3}\\]' }, { token : "comment", // --[====[ comment regex : strPre + '\\-\\-\\[\\={4}\\[.*\\]\\={4}\\]' }, { token : "comment", // --[====+[ comment regex : strPre + '\\-\\-\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]' }, // multiline bracketed comments { token : "comment", // --[[ comment regex : strPre + '\\-\\-\\[\\[.*$', merge : true, next : "qcomment" }, { token : "comment", // --[=[ comment regex : strPre + '\\-\\-\\[\\=\\[.*$', merge : true, next : "qcomment1" }, { token : "comment", // --[==[ comment regex : strPre + '\\-\\-\\[\\={2}\\[.*$', merge : true, next : "qcomment2" }, { token : "comment", // --[===[ comment regex : strPre + '\\-\\-\\[\\={3}\\[.*$', merge : true, next : "qcomment3" }, { token : "comment", // --[====[ comment regex : strPre + '\\-\\-\\[\\={4}\\[.*$', merge : true, next : "qcomment4" }, { token : function(value){ // --[====+[ comment // WARNING: EXTREMELY SLOW, but this is the only way to circumvent the // limits imposed by the current automaton. // I've never personally seen any practical code where 5 or more '='s are // used for string or commenting, so this will rarely be invoked. var pattern = /\-\-\[(\=+)\[/, match; // you can never be too paranoid ;) if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined) comment_stack.push(match.length); return "comment"; }, regex : strPre + '\\-\\-\\[\\={5}\\=*\\[.*$', merge : true, next : "qcomment5" }, // single line comments { token : "comment", regex : "\\-\\-.*$" }, // bracketed strings { token : "string", // [[ string regex : strPre + '\\[\\[.*\\]\\]' }, { token : "string", // [=[ string regex : strPre + '\\[\\=\\[.*\\]\\=\\]' }, { token : "string", // [==[ string regex : strPre + '\\[\\={2}\\[.*\\]\\={2}\\]' }, { token : "string", // [===[ string regex : strPre + '\\[\\={3}\\[.*\\]\\={3}\\]' }, { token : "string", // [====[ string regex : strPre + '\\[\\={4}\\[.*\\]\\={4}\\]' }, { token : "string", // [====+[ string regex : strPre + '\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]' }, // multiline bracketed strings { token : "string", // [[ string regex : strPre + '\\[\\[.*$', merge : true, next : "qstring" }, { token : "string", // [=[ string regex : strPre + '\\[\\=\\[.*$', merge : true, next : "qstring1" }, { token : "string", // [==[ string regex : strPre + '\\[\\={2}\\[.*$', merge : true, next : "qstring2" }, { token : "string", // [===[ string regex : strPre + '\\[\\={3}\\[.*$', merge : true, next : "qstring3" }, { token : "string", // [====[ string regex : strPre + '\\[\\={4}\\[.*$', merge : true, next : "qstring4" }, { token : function(value){ // --[====+[ string // WARNING: EXTREMELY SLOW, see above. var pattern = /\[(\=+)\[/, match; if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined) comment_stack.push(match.length); return "string"; }, regex : strPre + '\\[\\={5}\\=*\\[.*$', merge : true, next : "qstring5" }, { token : "string", // " string regex : strPre + '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ' string regex : strPre + "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (stdLibaries.hasOwnProperty(value)) return "constant.library"; else if (deprecatedIn5152.hasOwnProperty(value)) return "invalid.deprecated"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (metatableMethods.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\." }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" }, { token : "text", regex : "\\s+" } ], "qcomment": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment1": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\=\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment2": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment3": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment4": [ { token : "comment", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qcomment5": [ { token : function(value){ // very hackish, mutates the qcomment5 field on the fly. var pattern = /\](\=+)\]/, rule = this.rules.qcomment5[0], match; rule.next = "start"; if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined){ var found = match.length, expected; if ((expected = comment_stack.pop()) != found){ comment_stack.push(expected); rule.next = "qcomment5"; } } return "comment"; }, regex : "(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]", next : "start" }, { token : "comment", merge : true, regex : '.+' } ], "qstring": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring1": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\=\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring2": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring3": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring4": [ { token : "string", regex : "(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring5": [ { token : function(value){ // very hackish, mutates the qstring5 field on the fly. var pattern = /\](\=+)\]/, rule = this.rules.qstring5[0], match; rule.next = "start"; if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined){ var found = match.length, expected; if ((expected = comment_stack.pop()) != found){ comment_stack.push(expected); rule.next = "qstring5"; } } return "string"; }, regex : "(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; } oop.inherits(LuaHighlightRules, TextHighlightRules); exports.LuaHighlightRules = LuaHighlightRules; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * André Fiedler <fiedler dot andre a t gmail dot 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 ***** */ define('ace/mode/php', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/php_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PhpHighlightRules = require("./php_highlight_rules").PhpHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new PhpHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/php_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PhpHighlightRules = function() { var docComment = DocCommentHighlightRules; // http://php.net/quickref.php var builtinFunctions = lang.arrayToMap( ('abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|aggregate_methods_by_list|aggregate_methods_by_regexp|' + 'aggregate_properties|aggregate_properties_by_list|aggregate_properties_by_regexp|aggregation_info|amqpconnection|amqpexchange|amqpqueue|' + 'apache_child_terminate|apache_get_modules|apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|' + 'apache_reset_timeout|apache_response_headers|apache_setenv|apc_add|apc_bin_dump|apc_bin_dumpfile|apc_bin_load|apc_bin_loadfile|' + 'apc_cache_info|apc_cas|apc_clear_cache|apc_compile_file|apc_dec|apc_define_constants|apc_delete|apc_delete_file|apc_exists|apc_fetch|' + 'apc_inc|apc_load_constants|apc_sma_info|apc_store|apciterator|apd_breakpoint|apd_callstack|apd_clunk|apd_continue|apd_croak|' + 'apd_dump_function_table|apd_dump_persistent_resources|apd_dump_regular_resources|apd_echo|apd_get_active_symbols|apd_set_pprof_trace|' + 'apd_set_session|apd_set_session_trace|apd_set_session_trace_socket|appenditerator|array|array_change_key_case|array_chunk|array_combine|' + 'array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_fill_keys|array_filter|' + 'array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|' + 'array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|' + 'array_reduce|array_replace|array_replace_recursive|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|' + 'array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|' + 'array_values|array_walk|array_walk_recursive|arrayaccess|arrayiterator|arrayobject|arsort|asin|asinh|asort|assert|assert_options|atan|' + 'atan2|atanh|audioproperties|badfunctioncallexception|badmethodcallexception|base64_decode|base64_encode|base_convert|basename|' + 'bbcode_add_element|bbcode_add_smiley|bbcode_create|bbcode_destroy|bbcode_parse|bbcode_set_arg_parser|bbcode_set_flags|bcadd|bccomp|bcdiv|' + 'bcmod|bcmul|bcompiler_load|bcompiler_load_exe|bcompiler_parse_class|bcompiler_read|bcompiler_write_class|bcompiler_write_constant|' + 'bcompiler_write_exe_footer|bcompiler_write_file|bcompiler_write_footer|bcompiler_write_function|bcompiler_write_functions_from_file|' + 'bcompiler_write_header|bcompiler_write_included_filename|bcpow|bcpowmod|bcscale|bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|' + 'bindtextdomain|bson_decode|bson_encode|bumpValue|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|' + 'cachingiterator|cairo|cairo_create|cairo_font_face_get_type|cairo_font_face_status|cairo_font_options_create|cairo_font_options_equal|' + 'cairo_font_options_get_antialias|cairo_font_options_get_hint_metrics|cairo_font_options_get_hint_style|' + 'cairo_font_options_get_subpixel_order|cairo_font_options_hash|cairo_font_options_merge|cairo_font_options_set_antialias|' + 'cairo_font_options_set_hint_metrics|cairo_font_options_set_hint_style|cairo_font_options_set_subpixel_order|cairo_font_options_status|' + 'cairo_format_stride_for_width|cairo_image_surface_create|cairo_image_surface_create_for_data|cairo_image_surface_create_from_png|' + 'cairo_image_surface_get_data|cairo_image_surface_get_format|cairo_image_surface_get_height|cairo_image_surface_get_stride|' + 'cairo_image_surface_get_width|cairo_matrix_create_scale|cairo_matrix_create_translate|cairo_matrix_invert|cairo_matrix_multiply|' + 'cairo_matrix_rotate|cairo_matrix_transform_distance|cairo_matrix_transform_point|cairo_matrix_translate|cairo_pattern_add_color_stop_rgb|' + 'cairo_pattern_add_color_stop_rgba|cairo_pattern_create_for_surface|cairo_pattern_create_linear|cairo_pattern_create_radial|' + 'cairo_pattern_create_rgb|cairo_pattern_create_rgba|cairo_pattern_get_color_stop_count|cairo_pattern_get_color_stop_rgba|' + 'cairo_pattern_get_extend|cairo_pattern_get_filter|cairo_pattern_get_linear_points|cairo_pattern_get_matrix|' + 'cairo_pattern_get_radial_circles|cairo_pattern_get_rgba|cairo_pattern_get_surface|cairo_pattern_get_type|cairo_pattern_set_extend|' + 'cairo_pattern_set_filter|cairo_pattern_set_matrix|cairo_pattern_status|cairo_pdf_surface_create|cairo_pdf_surface_set_size|' + 'cairo_ps_get_levels|cairo_ps_level_to_string|cairo_ps_surface_create|cairo_ps_surface_dsc_begin_page_setup|' + 'cairo_ps_surface_dsc_begin_setup|cairo_ps_surface_dsc_comment|cairo_ps_surface_get_eps|cairo_ps_surface_restrict_to_level|' + 'cairo_ps_surface_set_eps|cairo_ps_surface_set_size|cairo_scaled_font_create|cairo_scaled_font_extents|cairo_scaled_font_get_ctm|' + 'cairo_scaled_font_get_font_face|cairo_scaled_font_get_font_matrix|cairo_scaled_font_get_font_options|cairo_scaled_font_get_scale_matrix|' + 'cairo_scaled_font_get_type|cairo_scaled_font_glyph_extents|cairo_scaled_font_status|cairo_scaled_font_text_extents|' + 'cairo_surface_copy_page|cairo_surface_create_similar|cairo_surface_finish|cairo_surface_flush|cairo_surface_get_content|' + 'cairo_surface_get_device_offset|cairo_surface_get_font_options|cairo_surface_get_type|cairo_surface_mark_dirty|' + 'cairo_surface_mark_dirty_rectangle|cairo_surface_set_device_offset|cairo_surface_set_fallback_resolution|cairo_surface_show_page|' + 'cairo_surface_status|cairo_surface_write_to_png|cairo_svg_surface_create|cairo_svg_surface_restrict_to_version|' + 'cairo_svg_version_to_string|cairoantialias|cairocontent|cairocontext|cairoexception|cairoextend|cairofillrule|cairofilter|cairofontface|' + 'cairofontoptions|cairofontslant|cairofonttype|cairofontweight|cairoformat|cairogradientpattern|cairohintmetrics|cairohintstyle|' + 'cairoimagesurface|cairolineargradient|cairolinecap|cairolinejoin|cairomatrix|cairooperator|cairopath|cairopattern|cairopatterntype|' + 'cairopdfsurface|cairopslevel|cairopssurface|cairoradialgradient|cairoscaledfont|cairosolidpattern|cairostatus|cairosubpixelorder|' + 'cairosurface|cairosurfacepattern|cairosurfacetype|cairosvgsurface|cairosvgversion|cairotoyfontface|cal_days_in_month|cal_from_jd|cal_info|' + 'cal_to_jd|calcul_hmac|calculhmac|call_user_func|call_user_func_array|call_user_method|call_user_method_array|callbackfilteriterator|ceil|' + 'chdb|chdb_create|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_alias|class_exists|class_implements|' + 'class_parents|classkit_import|classkit_method_add|classkit_method_copy|classkit_method_redefine|classkit_method_remove|' + 'classkit_method_rename|clearstatcache|clone|closedir|closelog|collator|com|com_addref|com_create_guid|com_event_sink|com_get|' + 'com_get_active_object|com_invoke|com_isenum|com_load|com_load_typelib|com_message_pump|com_print_typeinfo|com_propget|com_propput|' + 'com_propset|com_release|com_set|compact|connection_aborted|connection_status|connection_timeout|constant|construct|construct|construct|' + 'convert_cyr_string|convert_uudecode|convert_uuencode|copy|cos|cosh|count|count_chars|countable|counter_bump|counter_bump_value|' + 'counter_create|counter_get|counter_get_meta|counter_get_named|counter_get_value|counter_reset|counter_reset_value|crack_check|' + 'crack_closedict|crack_getlastmessage|crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|' + 'ctype_graph|ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|cubrid_affected_rows|cubrid_bind|' + 'cubrid_client_encoding|cubrid_close|cubrid_close_prepare|cubrid_close_request|cubrid_col_get|cubrid_col_size|cubrid_column_names|' + 'cubrid_column_types|cubrid_commit|cubrid_connect|cubrid_connect_with_url|cubrid_current_oid|cubrid_data_seek|cubrid_db_name|' + 'cubrid_disconnect|cubrid_drop|cubrid_errno|cubrid_error|cubrid_error_code|cubrid_error_code_facility|cubrid_error_msg|cubrid_execute|' + 'cubrid_fetch|cubrid_fetch_array|cubrid_fetch_assoc|cubrid_fetch_field|cubrid_fetch_lengths|cubrid_fetch_object|cubrid_fetch_row|' + 'cubrid_field_flags|cubrid_field_len|cubrid_field_name|cubrid_field_seek|cubrid_field_table|cubrid_field_type|cubrid_free_result|' + 'cubrid_get|cubrid_get_autocommit|cubrid_get_charset|cubrid_get_class_name|cubrid_get_client_info|cubrid_get_db_parameter|' + 'cubrid_get_server_info|cubrid_insert_id|cubrid_is_instance|cubrid_list_dbs|cubrid_load_from_glo|cubrid_lob_close|cubrid_lob_export|' + 'cubrid_lob_get|cubrid_lob_send|cubrid_lob_size|cubrid_lock_read|cubrid_lock_write|cubrid_move_cursor|cubrid_new_glo|cubrid_next_result|' + 'cubrid_num_cols|cubrid_num_fields|cubrid_num_rows|cubrid_ping|cubrid_prepare|cubrid_put|cubrid_query|cubrid_real_escape_string|' + 'cubrid_result|cubrid_rollback|cubrid_save_to_glo|cubrid_schema|cubrid_send_glo|cubrid_seq_drop|cubrid_seq_insert|cubrid_seq_put|' + 'cubrid_set_add|cubrid_set_autocommit|cubrid_set_db_parameter|cubrid_set_drop|cubrid_unbuffered_query|cubrid_version|curl_close|' + 'curl_copy_handle|curl_errno|curl_error|curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|' + 'curl_multi_getcontent|curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_setopt_array|' + 'curl_version|current|cyrus_authenticate|cyrus_bind|cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|date_add|date_create|' + 'date_create_from_format|date_date_set|date_default_timezone_get|date_default_timezone_set|date_diff|date_format|date_get_last_errors|' + 'date_interval_create_from_date_string|date_interval_format|date_isodate_set|date_modify|date_offset_get|date_parse|date_parse_from_format|' + 'date_sub|date_sun_info|date_sunrise|date_sunset|date_time_set|date_timestamp_get|date_timestamp_set|date_timezone_get|date_timezone_set|' + 'dateinterval|dateperiod|datetime|datetimezone|db2_autocommit|db2_bind_param|db2_client_info|db2_close|db2_column_privileges|db2_columns|' + 'db2_commit|db2_conn_error|db2_conn_errormsg|db2_connect|db2_cursor_type|db2_escape_string|db2_exec|db2_execute|db2_fetch_array|' + 'db2_fetch_assoc|db2_fetch_both|db2_fetch_object|db2_fetch_row|db2_field_display_size|db2_field_name|db2_field_num|db2_field_precision|' + 'db2_field_scale|db2_field_type|db2_field_width|db2_foreign_keys|db2_free_result|db2_free_stmt|db2_get_option|db2_last_insert_id|' + 'db2_lob_read|db2_next_result|db2_num_fields|db2_num_rows|db2_pclose|db2_pconnect|db2_prepare|db2_primary_keys|db2_procedure_columns|' + 'db2_procedures|db2_result|db2_rollback|db2_server_info|db2_set_option|db2_special_columns|db2_statistics|db2_stmt_error|db2_stmt_errormsg|' + 'db2_table_privileges|db2_tables|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|dba_handlers|dba_insert|dba_key_split|dba_list|' + 'dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|dbase_add_record|dbase_close|dbase_create|dbase_delete_record|' + 'dbase_get_header_info|dbase_get_record|dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|' + 'dbase_replace_record|dbplus_add|dbplus_aql|dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|' + 'dbplus_flush|dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|dbplus_lockrel|' + 'dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|dbplus_resolve|dbplus_restorepos|' + 'dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|' + 'dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|' + 'dbplus_update|dbplus_xlockrel|dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|' + 'dbx_sort|dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debug_zval_dump|decbin|dechex|decoct|define|' + 'define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|dio_seek|dio_stat|dio_tcsetattr|' + 'dio_truncate|dio_write|dir|directoryiterator|dirname|disk_free_space|disk_total_space|diskfreespace|dl|dngettext|dns_check_record|' + 'dns_get_mx|dns_get_record|dom_import_simplexml|domainexception|domattr|domattribute_name|domattribute_set_value|domattribute_specified|' + 'domattribute_value|domcharacterdata|domcomment|domdocument|domdocument_add_root|domdocument_create_attribute|' + 'domdocument_create_cdata_section|domdocument_create_comment|domdocument_create_element|domdocument_create_element_ns|' + 'domdocument_create_entity_reference|domdocument_create_processing_instruction|domdocument_create_text_node|domdocument_doctype|' + 'domdocument_document_element|domdocument_dump_file|domdocument_dump_mem|domdocument_get_element_by_id|domdocument_get_elements_by_tagname|' + 'domdocument_html_dump_mem|domdocument_xinclude|domdocumentfragment|domdocumenttype|domdocumenttype_entities|' + 'domdocumenttype_internal_subset|domdocumenttype_name|domdocumenttype_notations|domdocumenttype_public_id|domdocumenttype_system_id|' + 'domelement|domelement_get_attribute|domelement_get_attribute_node|domelement_get_elements_by_tagname|domelement_has_attribute|' + 'domelement_remove_attribute|domelement_set_attribute|domelement_set_attribute_node|domelement_tagname|domentity|domentityreference|' + 'domexception|domimplementation|domnamednodemap|domnode|domnode_add_namespace|domnode_append_child|domnode_append_sibling|' + 'domnode_attributes|domnode_child_nodes|domnode_clone_node|domnode_dump_node|domnode_first_child|domnode_get_content|' + 'domnode_has_attributes|domnode_has_child_nodes|domnode_insert_before|domnode_is_blank_node|domnode_last_child|domnode_next_sibling|' + 'domnode_node_name|domnode_node_type|domnode_node_value|domnode_owner_document|domnode_parent_node|domnode_prefix|domnode_previous_sibling|' + 'domnode_remove_child|domnode_replace_child|domnode_replace_node|domnode_set_content|domnode_set_name|domnode_set_namespace|' + 'domnode_unlink_node|domnodelist|domnotation|domprocessinginstruction|domprocessinginstruction_data|domprocessinginstruction_target|' + 'domtext|domxml_new_doc|domxml_open_file|domxml_open_mem|domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|' + 'domxml_xslt_stylesheet_file|domxml_xslt_version|domxpath|domxsltstylesheet_process|domxsltstylesheet_result_dump_file|' + 'domxsltstylesheet_result_dump_mem|dotnet|dotnet_load|doubleval|each|easter_date|easter_days|echo|empty|emptyiterator|' + 'enchant_broker_describe|enchant_broker_dict_exists|enchant_broker_free|enchant_broker_free_dict|enchant_broker_get_error|' + 'enchant_broker_init|enchant_broker_list_dicts|enchant_broker_request_dict|enchant_broker_request_pwl_dict|enchant_broker_set_ordering|' + 'enchant_dict_add_to_personal|enchant_dict_add_to_session|enchant_dict_check|enchant_dict_describe|enchant_dict_get_error|' + 'enchant_dict_is_in_session|enchant_dict_quick_check|enchant_dict_store_replacement|enchant_dict_suggest|end|ereg|ereg_replace|eregi|' + 'eregi_replace|error_get_last|error_log|error_reporting|errorexception|escapeshellarg|escapeshellcmd|eval|event_add|event_base_free|' + 'event_base_loop|event_base_loopbreak|event_base_loopexit|event_base_new|event_base_priority_init|event_base_set|event_buffer_base_set|' + 'event_buffer_disable|event_buffer_enable|event_buffer_fd_set|event_buffer_free|event_buffer_new|event_buffer_priority_set|' + 'event_buffer_read|event_buffer_set_callback|event_buffer_timeout_set|event_buffer_watermark_set|event_buffer_write|event_del|event_free|' + 'event_new|event_set|exception|exec|exif_imagetype|exif_read_data|exif_tagname|exif_thumbnail|exit|exp|expect_expectl|expect_popen|explode|' + 'expm1|export|export|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|fam_monitor_collection|fam_monitor_directory|' + 'fam_monitor_file|fam_next_event|fam_open|fam_pending|fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|' + 'fbsql_blob_size|fbsql_change_user|fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|' + 'fbsql_create_db|fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|' + 'fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|fbsql_fetch_row|' + 'fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|fbsql_field_type|fbsql_free_result|' + 'fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|fbsql_list_fields|fbsql_list_tables|fbsql_next_result|' + 'fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|' + 'fbsql_rows_fetched|fbsql_select_db|fbsql_set_characterset|fbsql_set_lob_mode|fbsql_set_password|fbsql_set_transaction|fbsql_start_db|' + 'fbsql_stop_db|fbsql_table_name|fbsql_tablename|fbsql_username|fbsql_warnings|fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|' + 'fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|' + 'fdf_get_status|fdf_get_value|fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|' + 'fdf_save_string|fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_on_import_javascript|fdf_set_opt|' + 'fdf_set_status|fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file|' + 'file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filepro|' + 'filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|filepro_retrieve|filepro_rowcount|filesize|filesystemiterator|' + 'filetype|filter_has_var|filter_id|filter_input|filter_input_array|filter_list|filter_var|filter_var_array|filteriterator|finfo_buffer|' + 'finfo_close|finfo_file|finfo_open|finfo_set_flags|floatval|flock|floor|flush|fmod|fnmatch|fopen|forward_static_call|' + 'forward_static_call_array|fpassthru|fprintf|fputcsv|fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|' + 'ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|' + 'ftp_mdtm|ftp_mkdir|ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|' + 'ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|func_get_args|' + 'func_num_args|function_exists|fwrite|gc_collect_cycles|gc_disable|gc_enable|gc_enabled|gd_info|gearmanclient|gearmanjob|gearmantask|' + 'gearmanworker|geoip_continent_code_by_name|geoip_country_code3_by_name|geoip_country_code_by_name|geoip_country_name_by_name|' + 'geoip_database_info|geoip_db_avail|geoip_db_filename|geoip_db_get_all_info|geoip_id_by_name|geoip_isp_by_name|geoip_org_by_name|' + 'geoip_record_by_name|geoip_region_by_name|geoip_region_name_by_code|geoip_time_zone_by_country_and_region|getMeta|getNamed|getValue|' + 'get_browser|get_called_class|get_cfg_var|get_class|get_class_methods|get_class_vars|get_current_user|get_declared_classes|' + 'get_declared_interfaces|get_defined_constants|get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|' + 'get_html_translation_table|get_include_path|get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|' + 'get_meta_tags|get_object_vars|get_parent_class|get_required_files|get_resource_type|getallheaders|getconstant|getconstants|getconstructor|' + 'getcwd|getdate|getdefaultproperties|getdoccomment|getendline|getenv|getextension|getextensionname|getfilename|gethostbyaddr|gethostbyname|' + 'gethostbynamel|gethostname|getimagesize|getinterfacenames|getinterfaces|getlastmod|getmethod|getmethods|getmodifiers|getmxrr|getmygid|' + 'getmyinode|getmypid|getmyuid|getname|getnamespacename|getopt|getparentclass|getproperties|getproperty|getprotobyname|getprotobynumber|' + 'getrandmax|getrusage|getservbyname|getservbyport|getshortname|getstartline|getstaticproperties|getstaticpropertyvalue|gettext|' + 'gettimeofday|gettype|glob|globiterator|gmagick|gmagickdraw|gmagickpixel|gmdate|gmmktime|gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|' + 'gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|' + 'gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_nextprime|gmp_or|gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|' + 'gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_testbit|gmp_xor|gmstrftime|' + 'gnupg_adddecryptkey|gnupg_addencryptkey|gnupg_addsignkey|gnupg_cleardecryptkeys|gnupg_clearencryptkeys|gnupg_clearsignkeys|gnupg_decrypt|' + 'gnupg_decryptverify|gnupg_encrypt|gnupg_encryptsign|gnupg_export|gnupg_geterror|gnupg_getprotocol|gnupg_import|gnupg_init|gnupg_keyinfo|' + 'gnupg_setarmor|gnupg_seterrormode|gnupg_setsignmode|gnupg_sign|gnupg_verify|gopher_parsedir|grapheme_extract|grapheme_stripos|' + 'grapheme_stristr|grapheme_strlen|grapheme_strpos|grapheme_strripos|grapheme_strrpos|grapheme_strstr|grapheme_substr|gregoriantojd|' + 'gupnp_context_get_host_ip|gupnp_context_get_port|gupnp_context_get_subscription_timeout|gupnp_context_host_path|gupnp_context_new|' + 'gupnp_context_set_subscription_timeout|gupnp_context_timeout_add|gupnp_context_unhost_path|gupnp_control_point_browse_start|' + 'gupnp_control_point_browse_stop|gupnp_control_point_callback_set|gupnp_control_point_new|gupnp_device_action_callback_set|' + 'gupnp_device_info_get|gupnp_device_info_get_service|gupnp_root_device_get_available|gupnp_root_device_get_relative_location|' + 'gupnp_root_device_new|gupnp_root_device_set_available|gupnp_root_device_start|gupnp_root_device_stop|gupnp_service_action_get|' + 'gupnp_service_action_return|gupnp_service_action_return_error|gupnp_service_action_set|gupnp_service_freeze_notify|gupnp_service_info_get|' + 'gupnp_service_info_get_introspection|gupnp_service_introspection_get_state_variable|gupnp_service_notify|gupnp_service_proxy_action_get|' + 'gupnp_service_proxy_action_set|gupnp_service_proxy_add_notify|gupnp_service_proxy_callback_set|gupnp_service_proxy_get_subscribed|' + 'gupnp_service_proxy_remove_notify|gupnp_service_proxy_set_subscribed|gupnp_service_thaw_notify|gzclose|gzcompress|gzdecode|gzdeflate|' + 'gzencode|gzeof|gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|' + 'halt_compiler|haruannotation|haruannotation_setborderstyle|haruannotation_sethighlightmode|haruannotation_seticon|' + 'haruannotation_setopened|harudestination|harudestination_setfit|harudestination_setfitb|harudestination_setfitbh|harudestination_setfitbv|' + 'harudestination_setfith|harudestination_setfitr|harudestination_setfitv|harudestination_setxyz|harudoc|harudoc_addpage|' + 'harudoc_addpagelabel|harudoc_construct|harudoc_createoutline|harudoc_getcurrentencoder|harudoc_getcurrentpage|harudoc_getencoder|' + 'harudoc_getfont|harudoc_getinfoattr|harudoc_getpagelayout|harudoc_getpagemode|harudoc_getstreamsize|harudoc_insertpage|harudoc_loadjpeg|' + 'harudoc_loadpng|harudoc_loadraw|harudoc_loadttc|harudoc_loadttf|harudoc_loadtype1|harudoc_output|harudoc_readfromstream|' + 'harudoc_reseterror|harudoc_resetstream|harudoc_save|harudoc_savetostream|harudoc_setcompressionmode|harudoc_setcurrentencoder|' + 'harudoc_setencryptionmode|harudoc_setinfoattr|harudoc_setinfodateattr|harudoc_setopenaction|harudoc_setpagelayout|harudoc_setpagemode|' + 'harudoc_setpagesconfiguration|harudoc_setpassword|harudoc_setpermission|harudoc_usecnsencodings|harudoc_usecnsfonts|' + 'harudoc_usecntencodings|harudoc_usecntfonts|harudoc_usejpencodings|harudoc_usejpfonts|harudoc_usekrencodings|harudoc_usekrfonts|' + 'haruencoder|haruencoder_getbytetype|haruencoder_gettype|haruencoder_getunicode|haruencoder_getwritingmode|haruexception|harufont|' + 'harufont_getascent|harufont_getcapheight|harufont_getdescent|harufont_getencodingname|harufont_getfontname|harufont_gettextwidth|' + 'harufont_getunicodewidth|harufont_getxheight|harufont_measuretext|haruimage|haruimage_getbitspercomponent|haruimage_getcolorspace|' + 'haruimage_getheight|haruimage_getsize|haruimage_getwidth|haruimage_setcolormask|haruimage_setmaskimage|haruoutline|' + 'haruoutline_setdestination|haruoutline_setopened|harupage|harupage_arc|harupage_begintext|harupage_circle|harupage_closepath|' + 'harupage_concat|harupage_createdestination|harupage_createlinkannotation|harupage_createtextannotation|harupage_createurlannotation|' + 'harupage_curveto|harupage_curveto2|harupage_curveto3|harupage_drawimage|harupage_ellipse|harupage_endpath|harupage_endtext|' + 'harupage_eofill|harupage_eofillstroke|harupage_fill|harupage_fillstroke|harupage_getcharspace|harupage_getcmykfill|harupage_getcmykstroke|' + 'harupage_getcurrentfont|harupage_getcurrentfontsize|harupage_getcurrentpos|harupage_getcurrenttextpos|harupage_getdash|' + 'harupage_getfillingcolorspace|harupage_getflatness|harupage_getgmode|harupage_getgrayfill|harupage_getgraystroke|harupage_getheight|' + 'harupage_gethorizontalscaling|harupage_getlinecap|harupage_getlinejoin|harupage_getlinewidth|harupage_getmiterlimit|harupage_getrgbfill|' + 'harupage_getrgbstroke|harupage_getstrokingcolorspace|harupage_gettextleading|harupage_gettextmatrix|harupage_gettextrenderingmode|' + 'harupage_gettextrise|harupage_gettextwidth|harupage_gettransmatrix|harupage_getwidth|harupage_getwordspace|harupage_lineto|' + 'harupage_measuretext|harupage_movetextpos|harupage_moveto|harupage_movetonextline|harupage_rectangle|harupage_setcharspace|' + 'harupage_setcmykfill|harupage_setcmykstroke|harupage_setdash|harupage_setflatness|harupage_setfontandsize|harupage_setgrayfill|' + 'harupage_setgraystroke|harupage_setheight|harupage_sethorizontalscaling|harupage_setlinecap|harupage_setlinejoin|harupage_setlinewidth|' + 'harupage_setmiterlimit|harupage_setrgbfill|harupage_setrgbstroke|harupage_setrotate|harupage_setsize|harupage_setslideshow|' + 'harupage_settextleading|harupage_settextmatrix|harupage_settextrenderingmode|harupage_settextrise|harupage_setwidth|harupage_setwordspace|' + 'harupage_showtext|harupage_showtextnextline|harupage_stroke|harupage_textout|harupage_textrect|hasconstant|hash|hash_algos|hash_copy|' + 'hash_file|hash_final|hash_hmac|hash_hmac_file|hash_init|hash_update|hash_update_file|hash_update_stream|hasmethod|hasproperty|header|' + 'header_register_callback|header_remove|headers_list|headers_sent|hebrev|hebrevc|hex2bin|hexdec|highlight_file|highlight_string|' + 'html_entity_decode|htmlentities|htmlspecialchars|htmlspecialchars_decode|http_build_cookie|http_build_query|http_build_str|http_build_url|' + 'http_cache_etag|http_cache_last_modified|http_chunked_decode|http_date|http_deflate|http_get|http_get_request_body|' + 'http_get_request_body_stream|http_get_request_headers|http_head|http_inflate|http_match_etag|http_match_modified|' + 'http_match_request_header|http_negotiate_charset|http_negotiate_content_type|http_negotiate_language|http_parse_cookie|http_parse_headers|' + 'http_parse_message|http_parse_params|http_persistent_handles_clean|http_persistent_handles_count|http_persistent_handles_ident|' + 'http_post_data|http_post_fields|http_put_data|http_put_file|http_put_stream|http_redirect|http_request|http_request_body_encode|' + 'http_request_method_exists|http_request_method_name|http_request_method_register|http_request_method_unregister|http_response_code|' + 'http_send_content_disposition|http_send_content_type|http_send_data|http_send_file|http_send_last_modified|http_send_status|' + 'http_send_stream|http_support|http_throttle|httpdeflatestream|httpdeflatestream_construct|httpdeflatestream_factory|' + 'httpdeflatestream_finish|httpdeflatestream_flush|httpdeflatestream_update|httpinflatestream|httpinflatestream_construct|' + 'httpinflatestream_factory|httpinflatestream_finish|httpinflatestream_flush|httpinflatestream_update|httpmessage|httpmessage_addheaders|' + 'httpmessage_construct|httpmessage_detach|httpmessage_factory|httpmessage_fromenv|httpmessage_fromstring|httpmessage_getbody|' + 'httpmessage_getheader|httpmessage_getheaders|httpmessage_gethttpversion|httpmessage_getparentmessage|httpmessage_getrequestmethod|' + 'httpmessage_getrequesturl|httpmessage_getresponsecode|httpmessage_getresponsestatus|httpmessage_gettype|httpmessage_guesscontenttype|' + 'httpmessage_prepend|httpmessage_reverse|httpmessage_send|httpmessage_setbody|httpmessage_setheaders|httpmessage_sethttpversion|' + 'httpmessage_setrequestmethod|httpmessage_setrequesturl|httpmessage_setresponsecode|httpmessage_setresponsestatus|httpmessage_settype|' + 'httpmessage_tomessagetypeobject|httpmessage_tostring|httpquerystring|httpquerystring_construct|httpquerystring_get|httpquerystring_mod|' + 'httpquerystring_set|httpquerystring_singleton|httpquerystring_toarray|httpquerystring_tostring|httpquerystring_xlate|httprequest|' + 'httprequest_addcookies|httprequest_addheaders|httprequest_addpostfields|httprequest_addpostfile|httprequest_addputdata|' + 'httprequest_addquerydata|httprequest_addrawpostdata|httprequest_addssloptions|httprequest_clearhistory|httprequest_construct|' + 'httprequest_enablecookies|httprequest_getcontenttype|httprequest_getcookies|httprequest_getheaders|httprequest_gethistory|' + 'httprequest_getmethod|httprequest_getoptions|httprequest_getpostfields|httprequest_getpostfiles|httprequest_getputdata|' + 'httprequest_getputfile|httprequest_getquerydata|httprequest_getrawpostdata|httprequest_getrawrequestmessage|' + 'httprequest_getrawresponsemessage|httprequest_getrequestmessage|httprequest_getresponsebody|httprequest_getresponsecode|' + 'httprequest_getresponsecookies|httprequest_getresponsedata|httprequest_getresponseheader|httprequest_getresponseinfo|' + 'httprequest_getresponsemessage|httprequest_getresponsestatus|httprequest_getssloptions|httprequest_geturl|httprequest_resetcookies|' + 'httprequest_send|httprequest_setcontenttype|httprequest_setcookies|httprequest_setheaders|httprequest_setmethod|httprequest_setoptions|' + 'httprequest_setpostfields|httprequest_setpostfiles|httprequest_setputdata|httprequest_setputfile|httprequest_setquerydata|' + 'httprequest_setrawpostdata|httprequest_setssloptions|httprequest_seturl|httprequestpool|httprequestpool_attach|httprequestpool_construct|' + 'httprequestpool_destruct|httprequestpool_detach|httprequestpool_getattachedrequests|httprequestpool_getfinishedrequests|' + 'httprequestpool_reset|httprequestpool_send|httprequestpool_socketperform|httprequestpool_socketselect|httpresponse|httpresponse_capture|' + 'httpresponse_getbuffersize|httpresponse_getcache|httpresponse_getcachecontrol|httpresponse_getcontentdisposition|' + 'httpresponse_getcontenttype|httpresponse_getdata|httpresponse_getetag|httpresponse_getfile|httpresponse_getgzip|httpresponse_getheader|' + 'httpresponse_getlastmodified|httpresponse_getrequestbody|httpresponse_getrequestbodystream|httpresponse_getrequestheaders|' + 'httpresponse_getstream|httpresponse_getthrottledelay|httpresponse_guesscontenttype|httpresponse_redirect|httpresponse_send|' + 'httpresponse_setbuffersize|httpresponse_setcache|httpresponse_setcachecontrol|httpresponse_setcontentdisposition|' + 'httpresponse_setcontenttype|httpresponse_setdata|httpresponse_setetag|httpresponse_setfile|httpresponse_setgzip|httpresponse_setheader|' + 'httpresponse_setlastmodified|httpresponse_setstream|httpresponse_setthrottledelay|httpresponse_status|hw_array2objrec|hw_changeobject|' + 'hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|' + 'hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|hw_edittext|hw_error|' + 'hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|hw_getchildcollobj|hw_getchilddoccoll|' + 'hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|' + 'hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|' + 'hw_incollections|hw_info|hw_inscoll|hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|' + 'hw_new_document|hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|' + 'hwapi_attribute|hwapi_attribute_key|hwapi_attribute_langdepvalue|hwapi_attribute_value|hwapi_attribute_values|hwapi_checkin|' + 'hwapi_checkout|hwapi_children|hwapi_content|hwapi_content_mimetype|hwapi_content_read|hwapi_copy|hwapi_dbstat|hwapi_dcstat|' + 'hwapi_dstanchors|hwapi_dstofsrcanchor|hwapi_error_count|hwapi_error_reason|hwapi_find|hwapi_ftstat|hwapi_hgcsp|hwapi_hwstat|' + 'hwapi_identify|hwapi_info|hwapi_insert|hwapi_insertanchor|hwapi_insertcollection|hwapi_insertdocument|hwapi_link|hwapi_lock|hwapi_move|' + 'hwapi_new_content|hwapi_object|hwapi_object_assign|hwapi_object_attreditable|hwapi_object_count|hwapi_object_insert|hwapi_object_new|' + 'hwapi_object_remove|hwapi_object_title|hwapi_object_value|hwapi_objectbyanchor|hwapi_parents|hwapi_reason_description|hwapi_reason_type|' + 'hwapi_remove|hwapi_replace|hwapi_setcommittedversion|hwapi_srcanchors|hwapi_srcsofdst|hwapi_unlock|hwapi_user|hwapi_userlist|hypot|' + 'ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|ibase_blob_create|ibase_blob_echo|' + 'ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|' + 'ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|' + 'ibase_field_info|ibase_free_event_handler|ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|' + 'ibase_name_result|ibase_num_fields|ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|' + 'ibase_rollback|ibase_rollback_ret|ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|' + 'ibase_trans|ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|' + 'iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|id3_get_frame_long_name|id3_get_frame_short_name|id3_get_genre_id|id3_get_genre_list|' + 'id3_get_genre_name|id3_get_tag|id3_get_version|id3_remove_tag|id3_set_tag|id3v2attachedpictureframe|id3v2frame|id3v2tag|idate|' + 'idn_to_ascii|idn_to_unicode|idn_to_utf8|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|ifx_close|ifx_connect|ifx_copy_blob|' + 'ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|' + 'ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|' + 'ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|' + 'ifxus_open_slob|ifxus_read_slob|ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|iis_add_server|iis_get_dir_security|' + 'iis_get_script_map|iis_get_server_by_comment|iis_get_server_by_path|iis_get_server_rights|iis_get_service_state|iis_remove_server|' + 'iis_set_app_settings|iis_set_dir_security|iis_set_script_map|iis_set_server_rights|iis_start_server|iis_start_service|iis_stop_server|' + 'iis_stop_service|image2wbmp|image_type_to_extension|image_type_to_mime_type|imagealphablending|imageantialias|imagearc|imagechar|' + 'imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|imagecolorclosestalpha|imagecolorclosesthwb|' + 'imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|imagecolorresolve|imagecolorresolvealpha|imagecolorset|' + 'imagecolorsforindex|imagecolorstotal|imagecolortransparent|imageconvolution|imagecopy|imagecopymerge|imagecopymergegray|' + 'imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|imagecreatefromgd2part|imagecreatefromgif|' + 'imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|imagecreatefromxbm|imagecreatefromxpm|' + 'imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|imagefilledellipse|imagefilledpolygon|' + 'imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|imageftbbox|imagefttext|imagegammacorrect|imagegd|' + 'imagegd2|imagegif|imagegrabscreen|imagegrabwindow|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|imageline|imageloadfont|' + 'imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepsencodefont|imagepsextendfont|imagepsfreefont|imagepsloadfont|imagepsslantfont|' + 'imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|' + 'imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imagick|' + 'imagick_adaptiveblurimage|imagick_adaptiveresizeimage|imagick_adaptivesharpenimage|imagick_adaptivethresholdimage|imagick_addimage|' + 'imagick_addnoiseimage|imagick_affinetransformimage|imagick_animateimages|imagick_annotateimage|imagick_appendimages|imagick_averageimages|' + 'imagick_blackthresholdimage|imagick_blurimage|imagick_borderimage|imagick_charcoalimage|imagick_chopimage|imagick_clear|imagick_clipimage|' + 'imagick_clippathimage|imagick_clone|imagick_clutimage|imagick_coalesceimages|imagick_colorfloodfillimage|imagick_colorizeimage|' + 'imagick_combineimages|imagick_commentimage|imagick_compareimagechannels|imagick_compareimagelayers|imagick_compareimages|' + 'imagick_compositeimage|imagick_construct|imagick_contrastimage|imagick_contraststretchimage|imagick_convolveimage|imagick_cropimage|' + 'imagick_cropthumbnailimage|imagick_current|imagick_cyclecolormapimage|imagick_decipherimage|imagick_deconstructimages|' + 'imagick_deleteimageartifact|imagick_despeckleimage|imagick_destroy|imagick_displayimage|imagick_displayimages|imagick_distortimage|' + 'imagick_drawimage|imagick_edgeimage|imagick_embossimage|imagick_encipherimage|imagick_enhanceimage|imagick_equalizeimage|' + 'imagick_evaluateimage|imagick_extentimage|imagick_flattenimages|imagick_flipimage|imagick_floodfillpaintimage|imagick_flopimage|' + 'imagick_frameimage|imagick_fximage|imagick_gammaimage|imagick_gaussianblurimage|imagick_getcolorspace|imagick_getcompression|' + 'imagick_getcompressionquality|imagick_getcopyright|imagick_getfilename|imagick_getfont|imagick_getformat|imagick_getgravity|' + 'imagick_gethomeurl|imagick_getimage|imagick_getimagealphachannel|imagick_getimageartifact|imagick_getimagebackgroundcolor|' + 'imagick_getimageblob|imagick_getimageblueprimary|imagick_getimagebordercolor|imagick_getimagechanneldepth|' + 'imagick_getimagechanneldistortion|imagick_getimagechanneldistortions|imagick_getimagechannelextrema|imagick_getimagechannelmean|' + 'imagick_getimagechannelrange|imagick_getimagechannelstatistics|imagick_getimageclipmask|imagick_getimagecolormapcolor|' + 'imagick_getimagecolors|imagick_getimagecolorspace|imagick_getimagecompose|imagick_getimagecompression|imagick_getimagecompressionquality|' + 'imagick_getimagedelay|imagick_getimagedepth|imagick_getimagedispose|imagick_getimagedistortion|imagick_getimageextrema|' + 'imagick_getimagefilename|imagick_getimageformat|imagick_getimagegamma|imagick_getimagegeometry|imagick_getimagegravity|' + 'imagick_getimagegreenprimary|imagick_getimageheight|imagick_getimagehistogram|imagick_getimageindex|imagick_getimageinterlacescheme|' + 'imagick_getimageinterpolatemethod|imagick_getimageiterations|imagick_getimagelength|imagick_getimagemagicklicense|imagick_getimagematte|' + 'imagick_getimagemattecolor|imagick_getimageorientation|imagick_getimagepage|imagick_getimagepixelcolor|imagick_getimageprofile|' + 'imagick_getimageprofiles|imagick_getimageproperties|imagick_getimageproperty|imagick_getimageredprimary|imagick_getimageregion|' + 'imagick_getimagerenderingintent|imagick_getimageresolution|imagick_getimagesblob|imagick_getimagescene|imagick_getimagesignature|' + 'imagick_getimagesize|imagick_getimagetickspersecond|imagick_getimagetotalinkdensity|imagick_getimagetype|imagick_getimageunits|' + 'imagick_getimagevirtualpixelmethod|imagick_getimagewhitepoint|imagick_getimagewidth|imagick_getinterlacescheme|imagick_getiteratorindex|' + 'imagick_getnumberimages|imagick_getoption|imagick_getpackagename|imagick_getpage|imagick_getpixeliterator|imagick_getpixelregioniterator|' + 'imagick_getpointsize|imagick_getquantumdepth|imagick_getquantumrange|imagick_getreleasedate|imagick_getresource|imagick_getresourcelimit|' + 'imagick_getsamplingfactors|imagick_getsize|imagick_getsizeoffset|imagick_getversion|imagick_hasnextimage|imagick_haspreviousimage|' + 'imagick_identifyimage|imagick_implodeimage|imagick_labelimage|imagick_levelimage|imagick_linearstretchimage|imagick_liquidrescaleimage|' + 'imagick_magnifyimage|imagick_mapimage|imagick_mattefloodfillimage|imagick_medianfilterimage|imagick_mergeimagelayers|imagick_minifyimage|' + 'imagick_modulateimage|imagick_montageimage|imagick_morphimages|imagick_mosaicimages|imagick_motionblurimage|imagick_negateimage|' + 'imagick_newimage|imagick_newpseudoimage|imagick_nextimage|imagick_normalizeimage|imagick_oilpaintimage|imagick_opaquepaintimage|' + 'imagick_optimizeimagelayers|imagick_orderedposterizeimage|imagick_paintfloodfillimage|imagick_paintopaqueimage|' + 'imagick_painttransparentimage|imagick_pingimage|imagick_pingimageblob|imagick_pingimagefile|imagick_polaroidimage|imagick_posterizeimage|' + 'imagick_previewimages|imagick_previousimage|imagick_profileimage|imagick_quantizeimage|imagick_quantizeimages|imagick_queryfontmetrics|' + 'imagick_queryfonts|imagick_queryformats|imagick_radialblurimage|imagick_raiseimage|imagick_randomthresholdimage|imagick_readimage|' + 'imagick_readimageblob|imagick_readimagefile|imagick_recolorimage|imagick_reducenoiseimage|imagick_removeimage|imagick_removeimageprofile|' + 'imagick_render|imagick_resampleimage|imagick_resetimagepage|imagick_resizeimage|imagick_rollimage|imagick_rotateimage|' + 'imagick_roundcorners|imagick_sampleimage|imagick_scaleimage|imagick_separateimagechannel|imagick_sepiatoneimage|' + 'imagick_setbackgroundcolor|imagick_setcolorspace|imagick_setcompression|imagick_setcompressionquality|imagick_setfilename|' + 'imagick_setfirstiterator|imagick_setfont|imagick_setformat|imagick_setgravity|imagick_setimage|imagick_setimagealphachannel|' + 'imagick_setimageartifact|imagick_setimagebackgroundcolor|imagick_setimagebias|imagick_setimageblueprimary|imagick_setimagebordercolor|' + 'imagick_setimagechanneldepth|imagick_setimageclipmask|imagick_setimagecolormapcolor|imagick_setimagecolorspace|imagick_setimagecompose|' + 'imagick_setimagecompression|imagick_setimagecompressionquality|imagick_setimagedelay|imagick_setimagedepth|imagick_setimagedispose|' + 'imagick_setimageextent|imagick_setimagefilename|imagick_setimageformat|imagick_setimagegamma|imagick_setimagegravity|' + 'imagick_setimagegreenprimary|imagick_setimageindex|imagick_setimageinterlacescheme|imagick_setimageinterpolatemethod|' + 'imagick_setimageiterations|imagick_setimagematte|imagick_setimagemattecolor|imagick_setimageopacity|imagick_setimageorientation|' + 'imagick_setimagepage|imagick_setimageprofile|imagick_setimageproperty|imagick_setimageredprimary|imagick_setimagerenderingintent|' + 'imagick_setimageresolution|imagick_setimagescene|imagick_setimagetickspersecond|imagick_setimagetype|imagick_setimageunits|' + 'imagick_setimagevirtualpixelmethod|imagick_setimagewhitepoint|imagick_setinterlacescheme|imagick_setiteratorindex|imagick_setlastiterator|' + 'imagick_setoption|imagick_setpage|imagick_setpointsize|imagick_setresolution|imagick_setresourcelimit|imagick_setsamplingfactors|' + 'imagick_setsize|imagick_setsizeoffset|imagick_settype|imagick_shadeimage|imagick_shadowimage|imagick_sharpenimage|imagick_shaveimage|' + 'imagick_shearimage|imagick_sigmoidalcontrastimage|imagick_sketchimage|imagick_solarizeimage|imagick_spliceimage|imagick_spreadimage|' + 'imagick_steganoimage|imagick_stereoimage|imagick_stripimage|imagick_swirlimage|imagick_textureimage|imagick_thresholdimage|' + 'imagick_thumbnailimage|imagick_tintimage|imagick_transformimage|imagick_transparentpaintimage|imagick_transposeimage|' + 'imagick_transverseimage|imagick_trimimage|imagick_uniqueimagecolors|imagick_unsharpmaskimage|imagick_valid|imagick_vignetteimage|' + 'imagick_waveimage|imagick_whitethresholdimage|imagick_writeimage|imagick_writeimagefile|imagick_writeimages|imagick_writeimagesfile|' + 'imagickdraw|imagickdraw_affine|imagickdraw_annotation|imagickdraw_arc|imagickdraw_bezier|imagickdraw_circle|imagickdraw_clear|' + 'imagickdraw_clone|imagickdraw_color|imagickdraw_comment|imagickdraw_composite|imagickdraw_construct|imagickdraw_destroy|' + 'imagickdraw_ellipse|imagickdraw_getclippath|imagickdraw_getcliprule|imagickdraw_getclipunits|imagickdraw_getfillcolor|' + 'imagickdraw_getfillopacity|imagickdraw_getfillrule|imagickdraw_getfont|imagickdraw_getfontfamily|imagickdraw_getfontsize|' + 'imagickdraw_getfontstyle|imagickdraw_getfontweight|imagickdraw_getgravity|imagickdraw_getstrokeantialias|imagickdraw_getstrokecolor|' + 'imagickdraw_getstrokedasharray|imagickdraw_getstrokedashoffset|imagickdraw_getstrokelinecap|imagickdraw_getstrokelinejoin|' + 'imagickdraw_getstrokemiterlimit|imagickdraw_getstrokeopacity|imagickdraw_getstrokewidth|imagickdraw_gettextalignment|' + 'imagickdraw_gettextantialias|imagickdraw_gettextdecoration|imagickdraw_gettextencoding|imagickdraw_gettextundercolor|' + 'imagickdraw_getvectorgraphics|imagickdraw_line|imagickdraw_matte|imagickdraw_pathclose|imagickdraw_pathcurvetoabsolute|' + 'imagickdraw_pathcurvetoquadraticbezierabsolute|imagickdraw_pathcurvetoquadraticbezierrelative|' + 'imagickdraw_pathcurvetoquadraticbeziersmoothabsolute|imagickdraw_pathcurvetoquadraticbeziersmoothrelative|imagickdraw_pathcurvetorelative|' + 'imagickdraw_pathcurvetosmoothabsolute|imagickdraw_pathcurvetosmoothrelative|imagickdraw_pathellipticarcabsolute|' + 'imagickdraw_pathellipticarcrelative|imagickdraw_pathfinish|imagickdraw_pathlinetoabsolute|imagickdraw_pathlinetohorizontalabsolute|' + 'imagickdraw_pathlinetohorizontalrelative|imagickdraw_pathlinetorelative|imagickdraw_pathlinetoverticalabsolute|' + 'imagickdraw_pathlinetoverticalrelative|imagickdraw_pathmovetoabsolute|imagickdraw_pathmovetorelative|imagickdraw_pathstart|' + 'imagickdraw_point|imagickdraw_polygon|imagickdraw_polyline|imagickdraw_pop|imagickdraw_popclippath|imagickdraw_popdefs|' + 'imagickdraw_poppattern|imagickdraw_push|imagickdraw_pushclippath|imagickdraw_pushdefs|imagickdraw_pushpattern|imagickdraw_rectangle|' + 'imagickdraw_render|imagickdraw_rotate|imagickdraw_roundrectangle|imagickdraw_scale|imagickdraw_setclippath|imagickdraw_setcliprule|' + 'imagickdraw_setclipunits|imagickdraw_setfillalpha|imagickdraw_setfillcolor|imagickdraw_setfillopacity|imagickdraw_setfillpatternurl|' + 'imagickdraw_setfillrule|imagickdraw_setfont|imagickdraw_setfontfamily|imagickdraw_setfontsize|imagickdraw_setfontstretch|' + 'imagickdraw_setfontstyle|imagickdraw_setfontweight|imagickdraw_setgravity|imagickdraw_setstrokealpha|imagickdraw_setstrokeantialias|' + 'imagickdraw_setstrokecolor|imagickdraw_setstrokedasharray|imagickdraw_setstrokedashoffset|imagickdraw_setstrokelinecap|' + 'imagickdraw_setstrokelinejoin|imagickdraw_setstrokemiterlimit|imagickdraw_setstrokeopacity|imagickdraw_setstrokepatternurl|' + 'imagickdraw_setstrokewidth|imagickdraw_settextalignment|imagickdraw_settextantialias|imagickdraw_settextdecoration|' + 'imagickdraw_settextencoding|imagickdraw_settextundercolor|imagickdraw_setvectorgraphics|imagickdraw_setviewbox|imagickdraw_skewx|' + 'imagickdraw_skewy|imagickdraw_translate|imagickpixel|imagickpixel_clear|imagickpixel_construct|imagickpixel_destroy|imagickpixel_getcolor|' + 'imagickpixel_getcolorasstring|imagickpixel_getcolorcount|imagickpixel_getcolorvalue|imagickpixel_gethsl|imagickpixel_issimilar|' + 'imagickpixel_setcolor|imagickpixel_setcolorvalue|imagickpixel_sethsl|imagickpixeliterator|imagickpixeliterator_clear|' + 'imagickpixeliterator_construct|imagickpixeliterator_destroy|imagickpixeliterator_getcurrentiteratorrow|' + 'imagickpixeliterator_getiteratorrow|imagickpixeliterator_getnextiteratorrow|imagickpixeliterator_getpreviousiteratorrow|' + 'imagickpixeliterator_newpixeliterator|imagickpixeliterator_newpixelregioniterator|imagickpixeliterator_resetiterator|' + 'imagickpixeliterator_setiteratorfirstrow|imagickpixeliterator_setiteratorlastrow|imagickpixeliterator_setiteratorrow|' + 'imagickpixeliterator_synciterator|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|imap_bodystruct|imap_check|' + 'imap_clearflag_full|imap_close|imap_create|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|imap_expunge|imap_fetch_overview|' + 'imap_fetchbody|imap_fetchheader|imap_fetchmime|imap_fetchstructure|imap_fetchtext|imap_gc|imap_get_quota|imap_get_quotaroot|imap_getacl|' + 'imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|imap_listmailbox|imap_listscan|' + 'imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|imap_mailboxmsginfo|imap_mime_header_decode|' + 'imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|imap_rename|imap_renamemailbox|imap_reopen|' + 'imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_savebody|imap_scan|imap_scanmailbox|imap_search|' + 'imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|imap_uid|imap_undelete|' + 'imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implementsinterface|implode|import_request_variables|in_array|include|' + 'include_once|inclued_get_data|inet_ntop|inet_pton|infiniteiterator|ingres_autocommit|ingres_autocommit_state|ingres_charset|ingres_close|' + 'ingres_commit|ingres_connect|ingres_cursor|ingres_errno|ingres_error|ingres_errsqlstate|ingres_escape_string|ingres_execute|' + 'ingres_fetch_array|ingres_fetch_assoc|ingres_fetch_object|ingres_fetch_proc_return|ingres_fetch_row|ingres_field_length|ingres_field_name|' + 'ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|ingres_free_result|ingres_next_error|ingres_num_fields|' + 'ingres_num_rows|ingres_pconnect|ingres_prepare|ingres_query|ingres_result_seek|ingres_rollback|ingres_set_environment|' + 'ingres_unbuffered_query|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|innamespace|inotify_add_watch|inotify_init|inotify_queue_len|' + 'inotify_read|inotify_rm_watch|interface_exists|intl_error_name|intl_get_error_code|intl_get_error_message|intl_is_failure|' + 'intldateformatter|intval|invalidargumentexception|invoke|invokeargs|ip2long|iptcembed|iptcparse|is_a|is_array|is_bool|is_callable|is_dir|' + 'is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|' + 'is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isabstract|' + 'iscloneable|isdisabled|isfinal|isinstance|isinstantiable|isinterface|isinternal|isiterateable|isset|issubclassof|isuserdefined|iterator|' + 'iterator_apply|iterator_count|iterator_to_array|iteratoraggregate|iteratoriterator|java_last_exception_clear|java_last_exception_get|' + 'jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|json_decode|json_encode|' + 'json_last_error|jsonserializable|judy|judy_type|judy_version|juliantojd|kadm5_chpass_principal|kadm5_create_principal|' + 'kadm5_delete_principal|kadm5_destroy|kadm5_flush|kadm5_get_policies|kadm5_get_principal|kadm5_get_principals|kadm5_init_with_password|' + 'kadm5_modify_principal|key|krsort|ksort|lcfirst|lcg_value|lchgrp|lchown|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|' + 'ldap_connect|ldap_count_entries|ldap_delete|ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|' + 'ldap_first_entry|ldap_first_reference|ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|' + 'ldap_get_values_len|ldap_list|ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|' + 'ldap_next_reference|ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_sasl_bind|ldap_search|ldap_set_option|' + 'ldap_set_rebind_proc|ldap_sort|ldap_start_tls|ldap_t61_to_8859|ldap_unbind|lengthexception|levenshtein|libxml_clear_errors|' + 'libxml_disable_entity_loader|libxml_get_errors|libxml_get_last_error|libxml_set_streams_context|libxml_use_internal_errors|libxmlerror|' + 'limititerator|link|linkinfo|list|locale|localeconv|localtime|log|log10|log1p|logicexception|long2ip|lstat|ltrim|lzf_compress|' + 'lzf_decompress|lzf_optimized_for|m_checkstatus|m_completeauthorizations|m_connect|m_connectionerror|m_deletetrans|m_destroyconn|' + 'm_destroyengine|m_getcell|m_getcellbynum|m_getcommadelimited|m_getheader|m_initconn|m_initengine|m_iscommadelimited|m_maxconntimeout|' + 'm_monitor|m_numcolumns|m_numrows|m_parsecommadelimited|m_responsekeys|m_responseparam|m_returnstatus|m_setblocking|m_setdropfile|m_setip|' + 'm_setssl|m_setssl_cafile|m_setssl_files|m_settimeout|m_sslcert_gen_hash|m_transactionssent|m_transinqueue|m_transkeyval|m_transnew|' + 'm_transsend|m_uwait|m_validateidentifier|m_verifyconnection|m_verifysslcert|magic_quotes_runtime|mail|' + 'mailparse_determine_best_xfer_encoding|mailparse_msg_create|mailparse_msg_extract_part|mailparse_msg_extract_part_file|' + 'mailparse_msg_extract_whole_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|mailparse_msg_get_structure|' + 'mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|mailparse_stream_encode|mailparse_uudecode_all|main|max|' + 'maxdb_affected_rows|maxdb_autocommit|maxdb_bind_param|maxdb_bind_result|maxdb_change_user|maxdb_character_set_name|maxdb_client_encoding|' + 'maxdb_close|maxdb_close_long_data|maxdb_commit|maxdb_connect|maxdb_connect_errno|maxdb_connect_error|maxdb_data_seek|maxdb_debug|' + 'maxdb_disable_reads_from_master|maxdb_disable_rpl_parse|maxdb_dump_debug_info|maxdb_embedded_connect|maxdb_enable_reads_from_master|' + 'maxdb_enable_rpl_parse|maxdb_errno|maxdb_error|maxdb_escape_string|maxdb_execute|maxdb_fetch|maxdb_fetch_array|maxdb_fetch_assoc|' + 'maxdb_fetch_field|maxdb_fetch_field_direct|maxdb_fetch_fields|maxdb_fetch_lengths|maxdb_fetch_object|maxdb_fetch_row|maxdb_field_count|' + 'maxdb_field_seek|maxdb_field_tell|maxdb_free_result|maxdb_get_client_info|maxdb_get_client_version|maxdb_get_host_info|maxdb_get_metadata|' + 'maxdb_get_proto_info|maxdb_get_server_info|maxdb_get_server_version|maxdb_info|maxdb_init|maxdb_insert_id|maxdb_kill|maxdb_master_query|' + 'maxdb_more_results|maxdb_multi_query|maxdb_next_result|maxdb_num_fields|maxdb_num_rows|maxdb_options|maxdb_param_count|maxdb_ping|' + 'maxdb_prepare|maxdb_query|maxdb_real_connect|maxdb_real_escape_string|maxdb_real_query|maxdb_report|maxdb_rollback|' + 'maxdb_rpl_parse_enabled|maxdb_rpl_probe|maxdb_rpl_query_type|maxdb_select_db|maxdb_send_long_data|maxdb_send_query|maxdb_server_end|' + 'maxdb_server_init|maxdb_set_opt|maxdb_sqlstate|maxdb_ssl_set|maxdb_stat|maxdb_stmt_affected_rows|maxdb_stmt_bind_param|' + 'maxdb_stmt_bind_result|maxdb_stmt_close|maxdb_stmt_close_long_data|maxdb_stmt_data_seek|maxdb_stmt_errno|maxdb_stmt_error|' + 'maxdb_stmt_execute|maxdb_stmt_fetch|maxdb_stmt_free_result|maxdb_stmt_init|maxdb_stmt_num_rows|maxdb_stmt_param_count|maxdb_stmt_prepare|' + 'maxdb_stmt_reset|maxdb_stmt_result_metadata|maxdb_stmt_send_long_data|maxdb_stmt_sqlstate|maxdb_stmt_store_result|maxdb_store_result|' + 'maxdb_thread_id|maxdb_thread_safe|maxdb_use_result|maxdb_warning_count|mb_check_encoding|mb_convert_case|mb_convert_encoding|' + 'mb_convert_kana|mb_convert_variables|mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|' + 'mb_encode_numericentity|mb_encoding_aliases|mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|' + 'mb_ereg_search_getregs|mb_ereg_search_init|mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|' + 'mb_get_info|mb_http_input|mb_http_output|mb_internal_encoding|mb_language|mb_list_encodings|mb_output_handler|mb_parse_str|' + 'mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_stripos|mb_stristr|' + 'mb_strlen|mb_strpos|mb_strrchr|mb_strrichr|mb_strripos|mb_strrpos|mb_strstr|mb_strtolower|mb_strtoupper|mb_strwidth|' + 'mb_substitute_character|mb_substr|mb_substr_count|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|' + 'mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|' + 'mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|' + 'mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|mcrypt_get_block_size|' + 'mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|mcrypt_module_close|' + 'mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|mcrypt_module_is_block_algorithm|' + 'mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|mcrypt_module_self_test|mcrypt_ofb|md5|md5_file|' + 'mdecrypt_generic|memcache|memcache_debug|memcached|memory_get_peak_usage|memory_get_usage|messageformatter|metaphone|method_exists|mhash|' + 'mhash_count|mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_keypress|' + 'ming_setcubicthreshold|ming_setscale|ming_setswfcompression|ming_useconstants|ming_useswfversion|mkdir|mktime|money_format|mongo|' + 'mongobindata|mongocode|mongocollection|mongoconnectionexception|mongocursor|mongocursorexception|mongocursortimeoutexception|mongodate|' + 'mongodb|mongodbref|mongoexception|mongogridfs|mongogridfscursor|mongogridfsexception|mongogridfsfile|mongoid|mongoint32|mongoint64|' + 'mongomaxkey|mongominkey|mongoregex|mongotimestamp|move_uploaded_file|mpegfile|mqseries_back|mqseries_begin|mqseries_close|mqseries_cmit|' + 'mqseries_conn|mqseries_connx|mqseries_disc|mqseries_get|mqseries_inq|mqseries_open|mqseries_put|mqseries_put1|mqseries_set|' + 'mqseries_strerror|msession_connect|msession_count|msession_create|msession_destroy|msession_disconnect|msession_find|msession_get|' + 'msession_get_array|msession_get_data|msession_inc|msession_list|msession_listvar|msession_lock|msession_plugin|msession_randstr|' + 'msession_set|msession_set_array|msession_set_data|msession_timeout|msession_uniq|msession_unlock|msg_get_queue|msg_queue_exists|' + 'msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql_affected_rows|msql_close|msql_connect|msql_create_db|' + 'msql_createdb|msql_data_seek|msql_db_query|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|msql_fetch_field|msql_fetch_object|' + 'msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|msql_field_type|msql_fieldflags|' + 'msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|msql_list_fields|msql_list_tables|' + 'msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|msql_result|msql_select_db|msql_tablename|' + 'mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|mssql_fetch_assoc|mssql_fetch_batch|' + 'mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|mssql_field_seek|mssql_field_type|' + 'mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|mssql_min_error_severity|' + 'mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|mssql_result|mssql_rows_affected|' + 'mssql_select_db|mt_getrandmax|mt_rand|mt_srand|multipleiterator|mysql_affected_rows|mysql_client_encoding|mysql_close|mysql_connect|' + 'mysql_create_db|mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|' + 'mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|' + 'mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|' + 'mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|' + 'mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|' + 'mysql_select_db|mysql_set_charset|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli|mysqli_bind_param|' + 'mysqli_bind_result|mysqli_client_encoding|mysqli_connect|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_driver|' + 'mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_escape_string|mysqli_execute|mysqli_fetch|mysqli_get_metadata|' + 'mysqli_master_query|mysqli_param_count|mysqli_report|mysqli_result|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_set_opt|mysqli_slave_query|mysqli_stmt|mysqli_warning|mysqlnd_ms_get_stats|' + 'mysqlnd_ms_query_is_select|mysqlnd_ms_set_user_pick_server|mysqlnd_qc_change_handler|mysqlnd_qc_clear_cache|mysqlnd_qc_get_cache_info|' + 'mysqlnd_qc_get_core_stats|mysqlnd_qc_get_handler|mysqlnd_qc_get_query_trace_log|mysqlnd_qc_set_user_handlers|natcasesort|natsort|' + 'ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|' + 'ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|' + 'ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|' + 'ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|' + 'ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|ncurses_filter|' + 'ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|ncurses_has_colors|' + 'ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|ncurses_init_color|' + 'ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|ncurses_keyok|' + 'ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|ncurses_move|' + 'ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|' + 'ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|' + 'ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|' + 'ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|ncurses_putp|' + 'ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|ncurses_resetty|' + 'ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|ncurses_slk_attr|' + 'ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|ncurses_slk_noutrefresh|' + 'ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|ncurses_start_color|' + 'ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|ncurses_ungetmouse|' + 'ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|ncurses_vline|ncurses_waddch|' + 'ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|ncurses_wcolor_set|ncurses_werase|' + 'ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|ncurses_wrefresh|ncurses_wstandend|' + 'ncurses_wstandout|ncurses_wvline|newinstance|newinstanceargs|newt_bell|newt_button|newt_button_bar|newt_centered_window|newt_checkbox|' + 'newt_checkbox_get_value|newt_checkbox_set_flags|newt_checkbox_set_value|newt_checkbox_tree|newt_checkbox_tree_add_item|' + 'newt_checkbox_tree_find_item|newt_checkbox_tree_get_current|newt_checkbox_tree_get_entry_value|newt_checkbox_tree_get_multi_selection|' + 'newt_checkbox_tree_get_selection|newt_checkbox_tree_multi|newt_checkbox_tree_set_current|newt_checkbox_tree_set_entry|' + 'newt_checkbox_tree_set_entry_value|newt_checkbox_tree_set_width|newt_clear_key_buffer|newt_cls|newt_compact_button|' + 'newt_component_add_callback|newt_component_takes_focus|newt_create_grid|newt_cursor_off|newt_cursor_on|newt_delay|newt_draw_form|' + 'newt_draw_root_text|newt_entry|newt_entry_get_value|newt_entry_set|newt_entry_set_filter|newt_entry_set_flags|newt_finished|newt_form|' + 'newt_form_add_component|newt_form_add_components|newt_form_add_hot_key|newt_form_destroy|newt_form_get_current|newt_form_run|' + 'newt_form_set_background|newt_form_set_height|newt_form_set_size|newt_form_set_timer|newt_form_set_width|newt_form_watch_fd|' + 'newt_get_screen_size|newt_grid_add_components_to_form|newt_grid_basic_window|newt_grid_free|newt_grid_get_size|newt_grid_h_close_stacked|' + 'newt_grid_h_stacked|newt_grid_place|newt_grid_set_field|newt_grid_simple_window|newt_grid_v_close_stacked|newt_grid_v_stacked|' + 'newt_grid_wrapped_window|newt_grid_wrapped_window_at|newt_init|newt_label|newt_label_set_text|newt_listbox|newt_listbox_append_entry|' + 'newt_listbox_clear|newt_listbox_clear_selection|newt_listbox_delete_entry|newt_listbox_get_current|newt_listbox_get_selection|' + 'newt_listbox_insert_entry|newt_listbox_item_count|newt_listbox_select_item|newt_listbox_set_current|newt_listbox_set_current_by_key|' + 'newt_listbox_set_data|newt_listbox_set_entry|newt_listbox_set_width|newt_listitem|newt_listitem_get_data|newt_listitem_set|' + 'newt_open_window|newt_pop_help_line|newt_pop_window|newt_push_help_line|newt_radio_get_current|newt_radiobutton|newt_redraw_help_line|' + 'newt_reflow_text|newt_refresh|newt_resize_screen|newt_resume|newt_run_form|newt_scale|newt_scale_set|newt_scrollbar_set|' + 'newt_set_help_callback|newt_set_suspend_callback|newt_suspend|newt_textbox|newt_textbox_get_num_lines|newt_textbox_reflowed|' + 'newt_textbox_set_height|newt_textbox_set_text|newt_vertical_scrollbar|newt_wait_for_key|newt_win_choice|newt_win_entries|newt_win_menu|' + 'newt_win_message|newt_win_messagev|newt_win_ternary|next|ngettext|nl2br|nl_langinfo|norewinditerator|normalizer|notes_body|notes_copy_db|' + 'notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|' + 'notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|nthmac|number_format|' + 'numberformatter|oauth|oauth_get_sbs|oauth_urlencode|oauthexception|oauthprovider|ob_clean|ob_deflatehandler|ob_end_clean|ob_end_flush|' + 'ob_etaghandler|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|ob_gzhandler|ob_iconv_handler|' + 'ob_implicit_flush|ob_inflatehandler|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_array_by_name|oci_bind_by_name|oci_cancel|' + 'oci_client_version|oci_close|oci_collection_append|oci_collection_assign|oci_collection_element_assign|oci_collection_element_get|' + 'oci_collection_free|oci_collection_max|oci_collection_size|oci_collection_trim|oci_commit|oci_connect|oci_define_by_name|oci_error|' + 'oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|' + 'oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_append|' + 'oci_lob_close|oci_lob_copy|oci_lob_eof|oci_lob_erase|oci_lob_export|oci_lob_flush|oci_lob_free|oci_lob_getbuffering|oci_lob_import|' + 'oci_lob_is_equal|oci_lob_load|oci_lob_read|oci_lob_rewind|oci_lob_save|oci_lob_savefile|oci_lob_seek|oci_lob_setbuffering|oci_lob_size|' + 'oci_lob_tell|oci_lob_truncate|oci_lob_write|oci_lob_writetemporary|oci_lob_writetofile|oci_new_collection|oci_new_connect|oci_new_cursor|' + 'oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|oci_server_version|' + 'oci_set_action|oci_set_client_identifier|oci_set_client_info|oci_set_edition|oci_set_module_name|oci_set_prefetch|oci_statement_type|' + 'ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|' + 'ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|' + 'ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|' + 'ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|' + 'ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|' + 'octdec|odbc_autocommit|odbc_binmode|odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|' + 'odbc_data_source|odbc_do|odbc_error|odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|' + 'odbc_fetch_row|odbc_field_len|odbc_field_name|odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|' + 'odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|' + 'odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|' + 'odbc_statistics|odbc_tableprivileges|odbc_tables|openal_buffer_create|openal_buffer_data|openal_buffer_destroy|openal_buffer_get|' + 'openal_buffer_loadwav|openal_context_create|openal_context_current|openal_context_destroy|openal_context_process|openal_context_suspend|' + 'openal_device_close|openal_device_open|openal_listener_get|openal_listener_set|openal_source_create|openal_source_destroy|' + 'openal_source_get|openal_source_pause|openal_source_play|openal_source_rewind|openal_source_set|openal_source_stop|openal_stream|opendir|' + 'openlog|openssl_cipher_iv_length|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_get_public_key|openssl_csr_get_subject|' + 'openssl_csr_new|openssl_csr_sign|openssl_decrypt|openssl_dh_compute_key|openssl_digest|openssl_encrypt|openssl_error_string|' + 'openssl_free_key|openssl_get_cipher_methods|openssl_get_md_methods|openssl_get_privatekey|openssl_get_publickey|openssl_open|' + 'openssl_pkcs12_export|openssl_pkcs12_export_to_file|openssl_pkcs12_read|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|' + 'openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_free|openssl_pkey_get_details|openssl_pkey_get_private|' + 'openssl_pkey_get_public|openssl_pkey_new|openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|' + 'openssl_random_pseudo_bytes|openssl_seal|openssl_sign|openssl_verify|openssl_x509_check_private_key|openssl_x509_checkpurpose|' + 'openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|openssl_x509_parse|openssl_x509_read|ord|outeriterator|' + 'outofboundsexception|outofrangeexception|output_add_rewrite_var|output_reset_rewrite_vars|overflowexception|overload|override_function|' + 'ovrimos_close|ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|' + 'ovrimos_field_len|ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|' + 'ovrimos_num_rows|ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parentiterator|parse_ini_file|parse_ini_string|' + 'parse_str|parse_url|parsekit_compile_file|parsekit_compile_string|parsekit_func_arginfo|passthru|pathinfo|pclose|pcntl_alarm|pcntl_exec|' + 'pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_signal_dispatch|pcntl_sigprocmask|pcntl_sigtimedwait|pcntl_sigwaitinfo|' + 'pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|' + 'pdf_activate_item|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|pdf_add_locallink|pdf_add_nameddest|pdf_add_note|pdf_add_outline|' + 'pdf_add_pdflink|pdf_add_table_cell|pdf_add_textflow|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|pdf_begin_document|' + 'pdf_begin_font|pdf_begin_glyph|pdf_begin_item|pdf_begin_layer|pdf_begin_page|pdf_begin_page_ext|pdf_begin_pattern|pdf_begin_template|' + 'pdf_begin_template_ext|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|pdf_closepath|' + 'pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_create_3dview|pdf_create_action|pdf_create_annotation|' + 'pdf_create_bookmark|pdf_create_field|pdf_create_fieldgroup|pdf_create_gstate|pdf_create_pvf|pdf_create_textflow|pdf_curveto|' + 'pdf_define_layer|pdf_delete|pdf_delete_pvf|pdf_delete_table|pdf_delete_textflow|pdf_encoding_set_char|pdf_end_document|pdf_end_font|' + 'pdf_end_glyph|pdf_end_item|pdf_end_layer|pdf_end_page|pdf_end_page_ext|pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|' + 'pdf_fill_imageblock|pdf_fill_pdfblock|pdf_fill_stroke|pdf_fill_textblock|pdf_findfont|pdf_fit_image|pdf_fit_pdi_page|pdf_fit_table|' + 'pdf_fit_textflow|pdf_fit_textline|pdf_get_apiname|pdf_get_buffer|pdf_get_errmsg|pdf_get_errnum|pdf_get_font|pdf_get_fontname|' + 'pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|' + 'pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_info_font|pdf_info_matchbox|pdf_info_table|pdf_info_textflow|pdf_info_textline|' + 'pdf_initgraphics|pdf_lineto|pdf_load_3ddata|pdf_load_font|pdf_load_iccprofile|pdf_load_image|pdf_makespotcolor|pdf_moveto|pdf_new|' + 'pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|' + 'pdf_open_pdi_document|pdf_open_pdi_page|pdf_open_tiff|pdf_pcos_get_number|pdf_pcos_get_stream|pdf_pcos_get_string|pdf_place_image|' + 'pdf_place_pdi_page|pdf_process_pdi|pdf_rect|pdf_restore|pdf_resume_page|pdf_rotate|pdf_save|pdf_scale|pdf_set_border_color|' + 'pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_gstate|pdf_set_horiz_scaling|pdf_set_info|' + 'pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|pdf_set_info_title|pdf_set_layer_dependency|' + 'pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|pdf_set_value|' + 'pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setdashpattern|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|' + 'pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|' + 'pdf_setrgbcolor_stroke|pdf_shading|pdf_shading_pattern|pdf_shfill|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|' + 'pdf_suspend_page|pdf_translate|pdf_utf16_to_utf8|pdf_utf32_to_utf16|pdf_utf8_to_utf16|pdo|pdo_cubrid_schema|pdo_pgsqllobcreate|' + 'pdo_pgsqllobopen|pdo_pgsqllobunlink|pdo_sqlitecreateaggregate|pdo_sqlitecreatefunction|pdoexception|pdostatement|pfsockopen|' + 'pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|pg_connection_busy|pg_connection_reset|pg_connection_status|' + 'pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|pg_escape_bytea|pg_escape_string|pg_execute|pg_fetch_all|' + 'pg_fetch_all_columns|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|pg_field_is_null|pg_field_name|' + 'pg_field_num|pg_field_prtlen|pg_field_size|pg_field_table|pg_field_type|pg_field_type_oid|pg_free_result|pg_get_notify|pg_get_pid|' + 'pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|pg_lo_open|' + 'pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|pg_options|' + 'pg_parameter_status|pg_pconnect|pg_ping|pg_port|pg_prepare|pg_put_line|pg_query|pg_query_params|pg_result_error|pg_result_error_field|' + 'pg_result_seek|pg_result_status|pg_select|pg_send_execute|pg_send_prepare|pg_send_query|pg_send_query_params|pg_set_client_encoding|' + 'pg_set_error_verbosity|pg_trace|pg_transaction_status|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|pg_version|php_check_syntax|' + 'php_ini_loaded_file|php_ini_scanned_files|php_logo_guid|php_sapi_name|php_strip_whitespace|php_uname|phpcredits|phpinfo|phpversion|pi|' + 'png2wbmp|popen|pos|posix_access|posix_ctermid|posix_errno|posix_get_last_error|posix_getcwd|posix_getegid|posix_geteuid|posix_getgid|' + 'posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|posix_getppid|posix_getpwnam|' + 'posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_initgroups|posix_isatty|posix_kill|posix_mkfifo|posix_mknod|posix_setegid|' + 'posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|posix_uname|pow|preg_filter|' + 'preg_grep|preg_last_error|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|' + 'printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|' + 'printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|' + 'printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|' + 'printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|' + 'printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|property_exists|' + 'ps_add_bookmark|ps_add_launchlink|ps_add_locallink|ps_add_note|ps_add_pdflink|ps_add_weblink|ps_arc|ps_arcn|ps_begin_page|' + 'ps_begin_pattern|ps_begin_template|ps_circle|ps_clip|ps_close|ps_close_image|ps_closepath|ps_closepath_stroke|ps_continue_text|ps_curveto|' + 'ps_delete|ps_end_page|ps_end_pattern|ps_end_template|ps_fill|ps_fill_stroke|ps_findfont|ps_get_buffer|ps_get_parameter|ps_get_value|' + 'ps_hyphenate|ps_include_file|ps_lineto|ps_makespotcolor|ps_moveto|ps_new|ps_open_file|ps_open_image|ps_open_image_file|' + 'ps_open_memory_image|ps_place_image|ps_rect|ps_restore|ps_rotate|ps_save|ps_scale|ps_set_border_color|ps_set_border_dash|' + 'ps_set_border_style|ps_set_info|ps_set_parameter|ps_set_text_pos|ps_set_value|ps_setcolor|ps_setdash|ps_setflat|ps_setfont|ps_setgray|' + 'ps_setlinecap|ps_setlinejoin|ps_setlinewidth|ps_setmiterlimit|ps_setoverprintmode|ps_setpolydash|ps_shading|ps_shading_pattern|ps_shfill|' + 'ps_show|ps_show2|ps_show_boxed|ps_show_xy|ps_show_xy2|ps_string_geometry|ps_stringwidth|ps_stroke|ps_symbol|ps_symbol_name|' + 'ps_symbol_width|ps_translate|pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|' + 'pspell_config_data_dir|pspell_config_dict_dir|pspell_config_ignore|pspell_config_mode|pspell_config_personal|pspell_config_repl|' + 'pspell_config_runtogether|pspell_config_save_repl|pspell_new|pspell_new_config|pspell_new_personal|pspell_save_wordlist|' + 'pspell_store_replacement|pspell_suggest|putenv|px_close|px_create_fp|px_date2string|px_delete|px_delete_record|px_get_field|px_get_info|' + 'px_get_parameter|px_get_record|px_get_schema|px_get_value|px_insert_record|px_new|px_numfields|px_numrecords|px_open_fp|px_put_record|' + 'px_retrieve_record|px_set_blob_file|px_set_parameter|px_set_tablename|px_set_targetencoding|px_set_value|px_timestamp2string|' + 'px_update_record|qdom_error|qdom_tree|quoted_printable_decode|quoted_printable_encode|quotemeta|rad2deg|radius_acct_open|' + 'radius_add_server|radius_auth_open|radius_close|radius_config|radius_create_request|radius_cvt_addr|radius_cvt_int|radius_cvt_string|' + 'radius_demangle|radius_demangle_mppe_key|radius_get_attr|radius_get_vendor_attr|radius_put_addr|radius_put_attr|radius_put_int|' + 'radius_put_string|radius_put_vendor_addr|radius_put_vendor_attr|radius_put_vendor_int|radius_put_vendor_string|' + 'radius_request_authenticator|radius_send_request|radius_server_secret|radius_strerror|rand|range|rangeexception|rar_wrapper_cache_stats|' + 'rararchive|rarentry|rarexception|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|readline_add_history|' + 'readline_callback_handler_install|readline_callback_handler_remove|readline_callback_read_char|readline_clear_history|' + 'readline_completion_function|readline_info|readline_list_history|readline_on_new_line|readline_read_history|readline_redisplay|' + 'readline_write_history|readlink|realpath|realpath_cache_get|realpath_cache_size|recode|recode_file|recode_string|recursivearrayiterator|' + 'recursivecachingiterator|recursivecallbackfilteriterator|recursivedirectoryiterator|recursivefilteriterator|recursiveiterator|' + 'recursiveiteratoriterator|recursiveregexiterator|recursivetreeiterator|reflection|reflectionclass|reflectionexception|reflectionextension|' + 'reflectionfunction|reflectionfunctionabstract|reflectionmethod|reflectionobject|reflectionparameter|reflectionproperty|reflector|' + 'regexiterator|register_shutdown_function|register_tick_function|rename|rename_function|require|require_once|reset|resetValue|' + 'resourcebundle|restore_error_handler|restore_exception_handler|restore_include_path|return|rewind|rewinddir|rmdir|round|rpm_close|' + 'rpm_get_tag|rpm_is_valid|rpm_open|rpm_version|rrd_create|rrd_error|rrd_fetch|rrd_first|rrd_graph|rrd_info|rrd_last|rrd_lastupdate|' + 'rrd_restore|rrd_tune|rrd_update|rrd_xport|rrdcreator|rrdgraph|rrdupdater|rsort|rtrim|runkit_class_adopt|runkit_class_emancipate|' + 'runkit_constant_add|runkit_constant_redefine|runkit_constant_remove|runkit_function_add|runkit_function_copy|runkit_function_redefine|' + 'runkit_function_remove|runkit_function_rename|runkit_import|runkit_lint|runkit_lint_file|runkit_method_add|runkit_method_copy|' + 'runkit_method_redefine|runkit_method_remove|runkit_method_rename|runkit_return_value_used|runkit_sandbox_output_handler|' + 'runkit_superglobals|runtimeexception|samconnection_commit|samconnection_connect|samconnection_constructor|samconnection_disconnect|' + 'samconnection_errno|samconnection_error|samconnection_isconnected|samconnection_peek|samconnection_peekall|samconnection_receive|' + 'samconnection_remove|samconnection_rollback|samconnection_send|samconnection_setDebug|samconnection_subscribe|samconnection_unsubscribe|' + 'sammessage_body|sammessage_constructor|sammessage_header|sca_createdataobject|sca_getservice|sca_localproxy_createdataobject|' + 'sca_soapproxy_createdataobject|scandir|sdo_das_changesummary_beginlogging|sdo_das_changesummary_endlogging|' + 'sdo_das_changesummary_getchangeddataobjects|sdo_das_changesummary_getchangetype|sdo_das_changesummary_getoldcontainer|' + 'sdo_das_changesummary_getoldvalues|sdo_das_changesummary_islogging|sdo_das_datafactory_addpropertytotype|sdo_das_datafactory_addtype|' + 'sdo_das_datafactory_getdatafactory|sdo_das_dataobject_getchangesummary|sdo_das_relational_applychanges|sdo_das_relational_construct|' + 'sdo_das_relational_createrootdataobject|sdo_das_relational_executepreparedquery|sdo_das_relational_executequery|' + 'sdo_das_setting_getlistindex|sdo_das_setting_getpropertyindex|sdo_das_setting_getpropertyname|sdo_das_setting_getvalue|' + 'sdo_das_setting_isset|sdo_das_xml_addtypes|sdo_das_xml_create|sdo_das_xml_createdataobject|sdo_das_xml_createdocument|' + 'sdo_das_xml_document_getrootdataobject|sdo_das_xml_document_getrootelementname|sdo_das_xml_document_getrootelementuri|' + 'sdo_das_xml_document_setencoding|sdo_das_xml_document_setxmldeclaration|sdo_das_xml_document_setxmlversion|sdo_das_xml_loadfile|' + 'sdo_das_xml_loadstring|sdo_das_xml_savefile|sdo_das_xml_savestring|sdo_datafactory_create|sdo_dataobject_clear|' + 'sdo_dataobject_createdataobject|sdo_dataobject_getcontainer|sdo_dataobject_getsequence|sdo_dataobject_gettypename|' + 'sdo_dataobject_gettypenamespaceuri|sdo_exception_getcause|sdo_list_insert|sdo_model_property_getcontainingtype|' + 'sdo_model_property_getdefault|sdo_model_property_getname|sdo_model_property_gettype|sdo_model_property_iscontainment|' + 'sdo_model_property_ismany|sdo_model_reflectiondataobject_construct|sdo_model_reflectiondataobject_export|' + 'sdo_model_reflectiondataobject_getcontainmentproperty|sdo_model_reflectiondataobject_getinstanceproperties|' + 'sdo_model_reflectiondataobject_gettype|sdo_model_type_getbasetype|sdo_model_type_getname|sdo_model_type_getnamespaceuri|' + 'sdo_model_type_getproperties|sdo_model_type_getproperty|sdo_model_type_isabstracttype|sdo_model_type_isdatatype|sdo_model_type_isinstance|' + 'sdo_model_type_isopentype|sdo_model_type_issequencedtype|sdo_sequence_getproperty|sdo_sequence_insert|sdo_sequence_move|seekableiterator|' + 'sem_acquire|sem_get|sem_release|sem_remove|serializable|serialize|session_cache_expire|session_cache_limiter|session_commit|' + 'session_decode|session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|' + 'session_pgsql_add_error|session_pgsql_get_error|session_pgsql_get_field|session_pgsql_reset|session_pgsql_set_field|session_pgsql_status|' + 'session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|' + 'session_unregister|session_unset|session_write_close|setCounterClass|set_error_handler|set_exception_handler|set_file_buffer|' + 'set_include_path|set_magic_quotes_runtime|set_socket_blocking|set_time_limit|setcookie|setlocale|setproctitle|setrawcookie|' + 'setstaticpropertyvalue|setthreadtitle|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_has_var|shm_put_var|' + 'shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|signeurlpaiement|' + 'similar_text|simplexml_import_dom|simplexml_load_file|simplexml_load_string|simplexmlelement|simplexmliterator|sin|sinh|sizeof|sleep|snmp|' + 'snmp2_get|snmp2_getnext|snmp2_real_walk|snmp2_set|snmp2_walk|snmp3_get|snmp3_getnext|snmp3_real_walk|snmp3_set|snmp3_walk|' + 'snmp_get_quick_print|snmp_get_valueretrieval|snmp_read_mib|snmp_set_enum_print|snmp_set_oid_numeric_print|snmp_set_oid_output_format|' + 'snmp_set_quick_print|snmp_set_valueretrieval|snmpget|snmpgetnext|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|soapclient|soapfault|' + 'soapheader|soapparam|soapserver|soapvar|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|socket_create|' + 'socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|socket_last_error|' + 'socket_listen|socket_read|socket_recv|socket_recvfrom|socket_select|socket_send|socket_sendto|socket_set_block|socket_set_blocking|' + 'socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|socket_strerror|socket_write|solr_get_version|solrclient|' + 'solrclientexception|solrdocument|solrdocumentfield|solrexception|solrgenericresponse|solrillegalargumentexception|' + 'solrillegaloperationexception|solrinputdocument|solrmodifiableparams|solrobject|solrparams|solrpingresponse|solrquery|solrqueryresponse|' + 'solrresponse|solrupdateresponse|solrutils|sort|soundex|sphinxclient|spl_autoload|spl_autoload_call|spl_autoload_extensions|' + 'spl_autoload_functions|spl_autoload_register|spl_autoload_unregister|spl_classes|spl_object_hash|splbool|spldoublylinkedlist|splenum|' + 'splfileinfo|splfileobject|splfixedarray|splfloat|splheap|splint|split|spliti|splmaxheap|splminheap|splobjectstorage|splobserver|' + 'splpriorityqueue|splqueue|splstack|splstring|splsubject|spltempfileobject|spoofchecker|sprintf|sql_regcase|sqlite3|sqlite3result|' + 'sqlite3stmt|sqlite_array_query|sqlite_busy_timeout|sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|' + 'sqlite_create_function|sqlite_current|sqlite_error_string|sqlite_escape_string|sqlite_exec|sqlite_factory|sqlite_fetch_all|' + 'sqlite_fetch_array|sqlite_fetch_column_types|sqlite_fetch_object|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|' + 'sqlite_has_more|sqlite_has_prev|sqlite_key|sqlite_last_error|sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|' + 'sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|sqlite_prev|sqlite_query|sqlite_rewind|sqlite_seek|sqlite_single_query|' + 'sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqlite_valid|sqrt|srand|sscanf|ssdeep_fuzzy_compare|' + 'ssdeep_fuzzy_hash|ssdeep_fuzzy_hash_filename|ssh2_auth_hostbased_file|ssh2_auth_none|ssh2_auth_password|ssh2_auth_pubkey_file|' + 'ssh2_connect|ssh2_exec|ssh2_fetch_stream|ssh2_fingerprint|ssh2_methods_negotiated|ssh2_publickey_add|ssh2_publickey_init|' + 'ssh2_publickey_list|ssh2_publickey_remove|ssh2_scp_recv|ssh2_scp_send|ssh2_sftp|ssh2_sftp_lstat|ssh2_sftp_mkdir|ssh2_sftp_readlink|' + 'ssh2_sftp_realpath|ssh2_sftp_rename|ssh2_sftp_rmdir|ssh2_sftp_stat|ssh2_sftp_symlink|ssh2_sftp_unlink|ssh2_shell|ssh2_tunnel|stat|' + 'stats_absolute_deviation|stats_cdf_beta|stats_cdf_binomial|stats_cdf_cauchy|stats_cdf_chisquare|stats_cdf_exponential|stats_cdf_f|' + 'stats_cdf_gamma|stats_cdf_laplace|stats_cdf_logistic|stats_cdf_negative_binomial|stats_cdf_noncentral_chisquare|stats_cdf_noncentral_f|' + 'stats_cdf_poisson|stats_cdf_t|stats_cdf_uniform|stats_cdf_weibull|stats_covariance|stats_den_uniform|stats_dens_beta|stats_dens_cauchy|' + 'stats_dens_chisquare|stats_dens_exponential|stats_dens_f|stats_dens_gamma|stats_dens_laplace|stats_dens_logistic|' + 'stats_dens_negative_binomial|stats_dens_normal|stats_dens_pmf_binomial|stats_dens_pmf_hypergeometric|stats_dens_pmf_poisson|stats_dens_t|' + 'stats_dens_weibull|stats_harmonic_mean|stats_kurtosis|stats_rand_gen_beta|stats_rand_gen_chisquare|stats_rand_gen_exponential|' + 'stats_rand_gen_f|stats_rand_gen_funiform|stats_rand_gen_gamma|stats_rand_gen_ibinomial|stats_rand_gen_ibinomial_negative|' + 'stats_rand_gen_int|stats_rand_gen_ipoisson|stats_rand_gen_iuniform|stats_rand_gen_noncenral_chisquare|stats_rand_gen_noncentral_f|' + 'stats_rand_gen_noncentral_t|stats_rand_gen_normal|stats_rand_gen_t|stats_rand_get_seeds|stats_rand_phrase_to_seeds|stats_rand_ranf|' + 'stats_rand_setall|stats_skew|stats_standard_deviation|stats_stat_binomial_coef|stats_stat_correlation|stats_stat_gennch|' + 'stats_stat_independent_t|stats_stat_innerproduct|stats_stat_noncentral_t|stats_stat_paired_t|stats_stat_percentile|stats_stat_powersum|' + 'stats_variance|stomp|stomp_connect_error|stomp_version|stompexception|stompframe|str_getcsv|str_ireplace|str_pad|str_repeat|str_replace|' + 'str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|stream_bucket_append|stream_bucket_make_writeable|' + 'stream_bucket_new|stream_bucket_prepend|stream_context_create|stream_context_get_default|stream_context_get_options|' + 'stream_context_get_params|stream_context_set_default|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|' + 'stream_encoding|stream_filter_append|stream_filter_prepend|stream_filter_register|stream_filter_remove|stream_get_contents|' + 'stream_get_filters|stream_get_line|stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_is_local|' + 'stream_notification_callback|stream_register_wrapper|stream_resolve_include_path|stream_select|stream_set_blocking|stream_set_read_buffer|' + 'stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_enable_crypto|stream_socket_get_name|' + 'stream_socket_pair|stream_socket_recvfrom|stream_socket_sendto|stream_socket_server|stream_socket_shutdown|stream_supports_lock|' + 'stream_wrapper_register|stream_wrapper_restore|stream_wrapper_unregister|streamwrapper|strftime|strip_tags|stripcslashes|stripos|' + 'stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|' + 'strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|svm|svmmodel|svn_add|' + 'svn_auth_get_parameter|svn_auth_set_parameter|svn_blame|svn_cat|svn_checkout|svn_cleanup|svn_client_version|svn_commit|svn_delete|' + 'svn_diff|svn_export|svn_fs_abort_txn|svn_fs_apply_text|svn_fs_begin_txn2|svn_fs_change_node_prop|svn_fs_check_path|' + 'svn_fs_contents_changed|svn_fs_copy|svn_fs_delete|svn_fs_dir_entries|svn_fs_file_contents|svn_fs_file_length|svn_fs_is_dir|svn_fs_is_file|' + 'svn_fs_make_dir|svn_fs_make_file|svn_fs_node_created_rev|svn_fs_node_prop|svn_fs_props_changed|svn_fs_revision_prop|svn_fs_revision_root|' + 'svn_fs_txn_root|svn_fs_youngest_rev|svn_import|svn_log|svn_ls|svn_mkdir|svn_repos_create|svn_repos_fs|svn_repos_fs_begin_txn_for_commit|' + 'svn_repos_fs_commit_txn|svn_repos_hotcopy|svn_repos_open|svn_repos_recover|svn_revert|svn_status|svn_update|swf_actiongeturl|' + 'swf_actiongotoframe|swf_actiongotolabel|swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|' + 'swf_actiontogglequality|swf_actionwaitforframe|swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|' + 'swf_defineline|swf_definepoly|swf_definerect|swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|' + 'swf_fontslant|swf_fonttracking|swf_getbitmapinfo|swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|' + 'swf_nextid|swf_oncondition|swf_openfile|swf_ortho|swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|' + 'swf_pushmatrix|swf_removeobject|swf_rotate|swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|' + 'swf_shapefillbitmapclip|swf_shapefillbitmaptile|swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|' + 'swf_showframe|swf_startbutton|swf_startdoaction|swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|' + 'swfbitmap|swfbutton|swfdisplayitem|swffill|swffont|swffontchar|swfgradient|swfmorph|swfmovie|swfprebuiltclip|swfshape|swfsound|' + 'swfsoundinstance|swfsprite|swftext|swftextfield|swfvideostream|swish_construct|swish_getmetalist|swish_getpropertylist|swish_prepare|' + 'swish_query|swishresult_getmetalist|swishresult_stem|swishresults_getparsedwords|swishresults_getremovedstopwords|swishresults_nextresult|' + 'swishresults_seekresult|swishsearch_execute|swishsearch_resetlimit|swishsearch_setlimit|swishsearch_setphrasedelimiter|' + 'swishsearch_setsort|swishsearch_setstructure|sybase_affected_rows|sybase_close|sybase_connect|sybase_data_seek|' + 'sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|sybase_fetch_row|' + 'sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|' + 'sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|' + 'sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|sys_get_temp_dir|sys_getloadavg|syslog|system|tag|tan|tanh|' + 'tcpwrap_check|tempnam|textdomain|tidy|tidy_access_count|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_error_buffer|' + 'tidy_get_output|tidy_load_config|tidy_reset_config|tidy_save_config|tidy_set_encoding|tidy_setopt|tidy_warning_count|tidynode|time|' + 'time_nanosleep|time_sleep_until|timezone_abbreviations_list|timezone_identifiers_list|timezone_location_get|timezone_name_from_abbr|' + 'timezone_name_get|timezone_offset_get|timezone_open|timezone_transitions_get|timezone_version_get|tmpfile|token_get_all|token_name|' + 'tokyotyrant|tokyotyrantquery|tokyotyranttable|tostring|tostring|touch|transliterator|traversable|trigger_error|trim|uasort|ucfirst|' + 'ucwords|udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|' + 'udm_check_stored|udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|' + 'udm_free_res|udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|' + 'uksort|umask|underflowexception|unexpectedvalueexception|uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|' + 'urldecode|urlencode|use_soap_error_handler|user_error|usleep|usort|utf8_decode|utf8_encode|v8js|v8jsexception|var_dump|var_export|variant|' + 'variant_abs|variant_add|variant_and|variant_cast|variant_cat|variant_cmp|variant_date_from_timestamp|variant_date_to_timestamp|' + 'variant_div|variant_eqv|variant_fix|variant_get_type|variant_idiv|variant_imp|variant_int|variant_mod|variant_mul|variant_neg|variant_not|' + 'variant_or|variant_pow|variant_round|variant_set|variant_set_type|variant_sub|variant_xor|version_compare|vfprintf|virtual|' + 'vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|' + 'vpopmail_alias_del|vpopmail_alias_del_domain|vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|' + 'vpopmail_del_domain_ex|vpopmail_del_user|vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|' + 'w32api_init_dtype|w32api_invoke_function|w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|' + 'wddx_packet_start|wddx_serialize_value|wddx_serialize_vars|win32_continue_service|win32_create_service|win32_delete_service|' + 'win32_get_last_control_message|win32_pause_service|win32_ps_list_procs|win32_ps_stat_mem|win32_ps_stat_proc|win32_query_service_status|' + 'win32_set_service_status|win32_start_service|win32_start_service_ctrl_dispatcher|win32_stop_service|wincache_fcache_fileinfo|' + 'wincache_fcache_meminfo|wincache_lock|wincache_ocache_fileinfo|wincache_ocache_meminfo|wincache_refresh_if_changed|' + 'wincache_rplist_fileinfo|wincache_rplist_meminfo|wincache_scache_info|wincache_scache_meminfo|wincache_ucache_add|wincache_ucache_cas|' + 'wincache_ucache_clear|wincache_ucache_dec|wincache_ucache_delete|wincache_ucache_exists|wincache_ucache_get|wincache_ucache_inc|' + 'wincache_ucache_info|wincache_ucache_meminfo|wincache_ucache_set|wincache_unlock|wordwrap|xattr_get|xattr_list|xattr_remove|xattr_set|' + 'xattr_supported|xdiff_file_bdiff|xdiff_file_bdiff_size|xdiff_file_bpatch|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|' + 'xdiff_file_patch|xdiff_file_patch_binary|xdiff_file_rabdiff|xdiff_string_bdiff|xdiff_string_bdiff_size|xdiff_string_bpatch|' + 'xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xdiff_string_rabdiff|' + 'xhprof_disable|xhprof_enable|xhprof_sample_disable|xhprof_sample_enable|xml_error_string|xml_get_current_byte_index|' + 'xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|xml_parser_create|' + 'xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|xml_set_default_handler|' + 'xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|xml_set_notation_decl_handler|' + 'xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|xml_set_unparsed_entity_decl_handler|xmlreader|' + 'xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|xmlrpc_is_fault|xmlrpc_parse_method_descriptions|' + 'xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|xmlrpc_server_destroy|' + 'xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xmlwriter_end_attribute|xmlwriter_end_cdata|' + 'xmlwriter_end_comment|xmlwriter_end_document|xmlwriter_end_dtd|xmlwriter_end_dtd_attlist|xmlwriter_end_dtd_element|' + 'xmlwriter_end_dtd_entity|xmlwriter_end_element|xmlwriter_end_pi|xmlwriter_flush|xmlwriter_full_end_element|xmlwriter_open_memory|' + 'xmlwriter_open_uri|xmlwriter_output_memory|xmlwriter_set_indent|xmlwriter_set_indent_string|xmlwriter_start_attribute|' + 'xmlwriter_start_attribute_ns|xmlwriter_start_cdata|xmlwriter_start_comment|xmlwriter_start_document|xmlwriter_start_dtd|' + 'xmlwriter_start_dtd_attlist|xmlwriter_start_dtd_element|xmlwriter_start_dtd_entity|xmlwriter_start_element|xmlwriter_start_element_ns|' + 'xmlwriter_start_pi|xmlwriter_text|xmlwriter_write_attribute|xmlwriter_write_attribute_ns|xmlwriter_write_cdata|xmlwriter_write_comment|' + 'xmlwriter_write_dtd|xmlwriter_write_dtd_attlist|xmlwriter_write_dtd_element|xmlwriter_write_dtd_entity|xmlwriter_write_element|' + 'xmlwriter_write_element_ns|xmlwriter_write_pi|xmlwriter_write_raw|xpath_eval|xpath_eval_expression|xpath_new_context|xpath_register_ns|' + 'xpath_register_ns_auto|xptr_eval|xptr_new_context|xslt_backend_info|xslt_backend_name|xslt_backend_version|xslt_create|xslt_errno|' + 'xslt_error|xslt_free|xslt_getopt|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|xslt_set_object|' + 'xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|xslt_setopt|xsltprocessor|yaml_emit|' + 'yaml_emit_file|yaml_parse|yaml_parse_file|yaml_parse_url|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|yaz_close|yaz_connect|yaz_database|' + 'yaz_element|yaz_errno|yaz_error|yaz_es|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|yaz_range|yaz_record|yaz_scan|' + 'yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|yp_err_string|yp_errno|yp_first|' + 'yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_thread_id|zend_version|zip_close|zip_entry_close|' + 'zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|zip_open|zip_read|' + 'ziparchive|ziparchive_addemptydir|ziparchive_addfile|ziparchive_addfromstring|ziparchive_close|ziparchive_deleteindex|' + 'ziparchive_deletename|ziparchive_extractto|ziparchive_getarchivecomment|ziparchive_getcommentindex|ziparchive_getcommentname|' + 'ziparchive_getfromindex|ziparchive_getfromname|ziparchive_getnameindex|ziparchive_getstatusstring|ziparchive_getstream|' + 'ziparchive_locatename|ziparchive_open|ziparchive_renameindex|ziparchive_renamename|ziparchive_setCommentName|ziparchive_setarchivecomment|' + 'ziparchive_setcommentindex|ziparchive_statindex|ziparchive_statname|ziparchive_unchangeall|ziparchive_unchangearchive|' + 'ziparchive_unchangeindex|ziparchive_unchangename|zlib_get_coding_type').split('|') ); // http://php.net/manual/en/reserved.keywords.php var keywords = lang.arrayToMap( ('abstract|and|array|as|break|case|catch|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|' + 'endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|interface|instanceof|namespace|new|or|private|protected|' + 'public|static|switch|throw|try|use|var|while|xor').split('|') ); // http://php.net/manual/en/reserved.keywords.php var languageConstructs = lang.arrayToMap( ('die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset').split('|') ); var builtinConstants = lang.arrayToMap( ('true|false|null|__CLASS__|__DIR__|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__NAMESPACE__').split('|') ); var builtinVariables = lang.arrayToMap( ('$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|' + '$http_response_header|$argc|$argv').split('|') ); // Discovery done by downloading 'Many HTML files' from: http://php.net/download-docs.php // Then search for files containing 'deprecated' (case-insensitive) and look at each file that turns up. var builtinFunctionsDeprecated = lang.arrayToMap( ('key_exists|cairo_matrix_create_scale|cairo_matrix_create_translate|call_user_method|call_user_method_array|com_addref|com_get|' + 'com_invoke|com_isenum|com_load|com_release|com_set|connection_timeout|cubrid_load_from_glo|cubrid_new_glo|cubrid_save_to_glo|' + 'cubrid_send_glo|define_syslog_variables|dl|ereg|ereg_replace|eregi|eregi_replace|hw_documentattributes|hw_documentbodytag|' + 'hw_documentsize|hw_outputdocument|imagedashedline|maxdb_bind_param|maxdb_bind_result|maxdb_client_encoding|maxdb_close_long_data|' + 'maxdb_execute|maxdb_fetch|maxdb_get_metadata|maxdb_param_count|maxdb_send_long_data|mcrypt_ecb|mcrypt_generic_end|mime_content_type|' + 'mysql_createdb|mysql_dbname|mysql_db_query|mysql_drop_db|mysql_dropdb|mysql_escape_string|mysql_fieldflags|mysql_fieldflags|' + 'mysql_fieldname|mysql_fieldtable|mysql_fieldtype|mysql_freeresult|mysql_listdbs|mysql_list_fields|mysql_listfields|mysql_list_tables|' + 'mysql_listtables|mysql_numfields|mysql_numrows|mysql_selectdb|mysql_tablename|mysqli_bind_param|mysqli_bind_result|' + 'mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_execute|' + 'mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_slave_query|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|' + 'ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|' + 'ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|' + 'ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|' + 'ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|' + 'ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|PDF_add_annotation|PDF_add_bookmark|' + 'PDF_add_launchlink|PDF_add_locallink|PDF_add_note|PDF_add_outline|PDF_add_pdflink|PDF_add_weblink|PDF_attach_file|PDF_begin_page|' + 'PDF_begin_template|PDF_close_pdi|PDF_close|PDF_findfont|PDF_get_font|PDF_get_fontname|PDF_get_fontsize|PDF_get_image_height|' + 'PDF_get_image_width|PDF_get_majorversion|PDF_get_minorversion|PDF_get_pdi_parameter|PDF_get_pdi_value|PDF_open_ccitt|PDF_open_file|' + 'PDF_open_gif|PDF_open_image_file|PDF_open_image|PDF_open_jpeg|PDF_open_pdi|PDF_open_tiff|PDF_place_image|PDF_place_pdi_page|' + 'PDF_set_border_color|PDF_set_border_dash|PDF_set_border_style|PDF_set_char_spacing|PDF_set_duration|PDF_set_horiz_scaling|' + 'PDF_set_info_author|PDF_set_info_creator|PDF_set_info_keywords|PDF_set_info_subject|PDF_set_info_title|PDF_set_leading|' + 'PDF_set_text_matrix|PDF_set_text_rendering|PDF_set_text_rise|PDF_set_word_spacing|PDF_setgray_fill|PDF_setgray_stroke|PDF_setgray|' + 'PDF_setpolydash|PDF_setrgbcolor_fill|PDF_setrgbcolor_stroke|PDF_setrgbcolor|PDF_show_boxed|php_check_syntax|px_set_tablename|' + 'px_set_targetencoding|runkit_sandbox_output_handler|session_is_registered|session_register|session_unregister' + 'set_magic_quotes_runtime|magic_quotes_runtime|set_socket_blocking|socket_set_blocking|set_socket_timeout|socket_set_timeout|split|spliti|' + 'sql_regcase').split('|') ); var keywordsDeprecated = lang.arrayToMap( ('cfunction|old_function').split('|') ); var futureReserved = lang.arrayToMap([]); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "support.php_tag", // php open tag regex : "<\\?(?:php|\\=)" }, { token : "support.php_tag", // php close tag regex : "\\?>" }, { token : "comment", regex : "<\\!--", next : "htmlcomment" }, { token : "meta.tag", regex : "<style", next : "css" }, { token : "meta.tag", // opening tag regex : "<\\/?[-_a-zA-Z0-9:]+", next : "htmltag" }, { token : 'meta.tag', regex : '<\!DOCTYPE.*?>' }, { token : "comment", regex : "\\/\\/.*$" }, { token : "comment", regex : "#.*$" }, docComment.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)" }, { token : "string", // " string start regex : '"', next : "qqstring" }, { token : "string", // ' string start regex : "'", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", // constants regex : "\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|" + "ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|" + "HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|" + "L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|" + "VERSION))|__COMPILER_HALT_OFFSET__)\\b" }, { token : "constant.language", // constants regex : "\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|" + "SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|" + "O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|" + "R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|" + "YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|" + "ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|" + "T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|" + "HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|" + "I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|" + "O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|" + "L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|" + "M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|" + "OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|" + "T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else if(value.match(/^(\$[a-zA-Z][a-zA-Z0-9_]*|self|parent)$/)) return "variable"; return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : '\\\\(?:[nrtvef\\\\"$]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})' }, { token : "constant.language.escape", regex : /\$[\w\d]+(?:\[[\w\d]+\])?/ }, { token : "constant.language.escape", regex : /\$\{[^"\}]+\}?/ // this is wrong but ok for now }, { token : "string", regex : '"', next : "start" }, { token : "string", regex : '.+?' } ], "qstring" : [ { token : "constant.language.escape", regex : "\\\\['\\\\]" }, { token : "string", regex : "'", next : "start" }, { token : "string", regex : ".+?" } ], "htmlcomment" : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", regex : ".+" } ], "htmltag" : [ { token : "meta.tag", regex : ">", next : "start" }, { token : "text", regex : "[-_a-zA-Z0-9:]+" }, { token : "text", regex : "\\s+" }, { token : "string", regex : '".*?"' }, { token : "string", regex : "'.*?'" } ], "css" : [ { token : "meta.tag", regex : "<\/style>", next : "htmltag" }, { token : "meta.tag", regex : ">" }, { token : 'text', regex : "(?:media|type|href)" }, { token : 'string', regex : '=".*?"' }, { token : "paren.lparen", regex : "\{", next : "cssdeclaration" }, { token : "keyword", regex : "#[A-Za-z0-9\-\_\.]+" }, { token : "variable", regex : "\\.[A-Za-z0-9\-\_\.]+" }, { token : "constant", regex : "[A-Za-z0-9]+" } ], "cssdeclaration" : [ { token : "support.type", regex : "[\-a-zA-Z]+", next : "cssvalue" }, { token : "paren.rparen", regex : '\}', next : "css" } ], "cssvalue" : [ { token : "text", regex : "\:" }, { token : "constant", regex : "#[0-9a-zA-Z]+" }, { token : "text", regex : "[\-\_0-9a-zA-Z\"' ,%]+" }, { token : "text", regex : ";", next : "cssdeclaration" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(PhpHighlightRules, TextHighlightRules); exports.PhpHighlightRules = PhpHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/mode/coldfusion', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/coldfusion_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var XmlMode = require("./xml").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ColdfusionHighlightRules = require("./coldfusion_highlight_rules").ColdfusionHighlightRules; var Mode = function() { XmlMode.call(this); var highlighter = new ColdfusionHighlightRules(); this.$tokenizer = new Tokenizer(highlighter.getRules()); this.$embeds = highlighter.getEmbeds(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); }; oop.inherits(Mode, XmlMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules()); this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var xmlUtil = require("./xml_util"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [{ token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "xml_pe", regex : "<\\!.*?>" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "constant.character.entity", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }, { token : "text", regex : "[^<]+" }], cdata : [{ token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "(?:[^\\]]|\\](?!\\]>))+" }], comment : [{ token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" }] }; xmlUtil.tag(this.$rules, "tag", "start"); }; oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var formTags = lang.arrayToMap( ("button|form|input|label|select|textarea").split("|") ); var tableTags = lang.arrayToMap( ("table|tbody|td|tfoot|th|tr").split("|") ); function string(state) { return [{ token : "string", regex : '".*?"' }, { token : "string", // multi line string start merge : true, regex : '["].*', next : state + "_qqstring" }, { token : "string", regex : "'.*?'" }, { token : "string", // multi line string start merge : true, regex : "['].*", next : state + "_qstring" }]; } function multiLineString(quote, state) { return [{ token : "string", merge : true, regex : ".*?" + quote, next : state }, { token : "string", merge : true, regex : '.+' }]; } exports.tag = function(states, name, nextState) { states[name] = [{ token : "text", regex : "\\s+" }, { //token : "meta.tag", token : function(value) { if ( value==='a' ) { return "meta.tag.anchor"; } else if ( value==='img' ) { return "meta.tag.image"; } else if ( value==='script' ) { return "meta.tag.script"; } else if ( value==='style' ) { return "meta.tag.style"; } else if (formTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.form"; } else if (tableTags.hasOwnProperty(value.toLowerCase())) { return "meta.tag.table"; } else { return "meta.tag"; } }, merge : true, regex : "[-_a-zA-Z0-9:]+", next : name + "_embed_attribute_list" }, { token: "empty", regex: "", next : name + "_embed_attribute_list" }]; states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list"); states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list"); states[name + "_embed_attribute_list"] = [{ token : "meta.tag", merge : true, regex : "\/?>", next : nextState }, { token : "keyword.operator", regex : "=" }, { token : "entity.other.attribute-name", regex : "[-_a-zA-Z0-9:]+" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "text", regex : "\\s+" }].concat(string(name)); }; }); define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var XmlBehaviour = function () { this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == '<') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return false; } else { return { text: '<>', selection: [1, 1] } } } else if (text == '>') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '>') { // need some kind of matching check here return { text: '', selection: [1, 1] } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } }); } oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) { var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (tag.closing) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()]) return ""; if (tag.selfClosing) return ""; if (tag.value.indexOf("/" + tag.tagName) !== -1) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var value = ""; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.indexOf("meta.tag") === 0) value += token.value; else value += lang.stringRepeat(" ", token.value.length); } return this._parseTag(value); }; this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/; this._parseTag = function(tag) { var match = this.tagRe.exec(tag); var column = this.tagRe.lastIndex || 0; this.tagRe.lastIndex = 0; return { value: tag, match: match ? match[2] : "", closing: match ? !!match[3] : false, selfClosing: match ? !!match[5] || match[2] == "/>" : false, tagName: match ? match[4] : "", column: match[1] ? column + match[1].length : column }; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var start; do { if (token.type.indexOf("meta.tag") === 0) { if (!start) { var start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; } value += token.value; if (value.indexOf(">") !== -1) { var tag = this._parseTag(value); tag.start = start; tag.end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; iterator.stepForward(); return tag; } } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var value = ""; var end; do { if (token.type.indexOf("meta.tag") === 0) { if (!end) { end = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() + token.value.length }; } value = token.value + value; if (value.indexOf("<") !== -1) { var tag = this._parseTag(value); tag.end = end; tag.start = { row: iterator.getCurrentTokenRow(), column: iterator.getCurrentTokenColumn() }; iterator.stepBackward(); return tag; } } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.voidElements[tag.tagName]) { return; } else if (this.voidElements[top.tagName]) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag.match) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.column); var start = { row: row, column: firstTag.column + firstTag.tagName.length + 2 }; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag) } } } else { var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length); var end = { row: row, column: firstTag.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; return Range.fromPoints(tag.start, end); } } else { stack.push(tag) } } } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); 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); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("csslint", function(e) { var errors = []; e.data.forEach(function(message) { errors.push({ row: message.line - 1, column: message.col - 1, text: message.message, type: message.type, lint: message }); }); session.setAnnotations(errors); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CssHighlightRules = function() { var properties = lang.arrayToMap( ("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|") ); var functions = lang.arrayToMap( ("rgb|rgba|url|attr|counter|counters").split("|") ); var constants = lang.arrayToMap( ("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|") ); var colors = lang.arrayToMap( ("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" + "purple|red|silver|teal|white|yellow").split("|") ); var fonts = lang.arrayToMap( ("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" + "symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" + "serif|monospace").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var base_ruleset = [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "ruleset_comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : ["constant.numeric"], regex : "([0-9]+)" }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : function(value) { if (properties.hasOwnProperty(value.toLowerCase())) { return "support.type"; } else if (functions.hasOwnProperty(value.toLowerCase())) { return "support.function"; } else if (constants.hasOwnProperty(value.toLowerCase())) { return "support.constant"; } else if (colors.hasOwnProperty(value.toLowerCase())) { return "support.constant.color"; } else if (fonts.hasOwnProperty(value.toLowerCase())) { return "support.constant.fonts"; } else { return "text"; } }, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" } ]; var ruleset = lang.copyArray(base_ruleset); ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "start" }); var media_ruleset = lang.copyArray( base_ruleset ); media_ruleset.unshift({ token : "paren.rparen", regex : "\\}", next: "media" }); var base_comment = [{ token : "comment", // comment spanning whole line merge : true, regex : ".+" }]; var comment = lang.copyArray(base_comment); comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }); var media_comment = lang.copyArray(base_comment); media_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "media" }); var ruleset_comment = lang.copyArray(base_comment); ruleset_comment.unshift({ token : "comment", // closing comment regex : ".*?\\*\\/", next : "ruleset" }); this.$rules = { "start" : [{ token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token: "paren.lparen", regex: "\\{", next: "ruleset" }, { token: "string", regex: "@.*?{", next: "media" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "media" : [ { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "media_comment" }, { token: "paren.lparen", regex: "\\{", next: "media_ruleset" },{ token: "string", regex: "\\}", next: "start" },{ token: "keyword", regex: "#[a-z0-9-_]+" },{ token: "variable", regex: "\\.[a-z0-9-_]+" },{ token: "string", regex: ":[a-z0-9-_]+" },{ token: "constant", regex: "[a-z0-9-_]+" }], "comment" : comment, "ruleset" : ruleset, "ruleset_comment" : ruleset_comment, "media_ruleset" : media_ruleset, "media_comment" : media_comment }; }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); define('ace/mode/coldfusion_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/text_highlight_rules', 'ace/mode/xml_util'], function(require, exports, module) { var oop = require("../lib/oop"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var xml_util = require("./xml_util"); var ColdfusionHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [ { token : "text", merge : true, regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", merge : true, regex : "<\\!--", next : "comment" }, { token : "meta.tag", regex : "<(?=\s*script)", next : "script" }, { token : "meta.tag", regex : "<(?=\s*style)", next : "style" }, { token : "meta.tag", // opening tag regex : "<\\/?", next : "tag" }, { token : "text", regex : "\\s+" }, { token : "text", regex : "[^<]+" } ], cdata : [ { token : "text", regex : "\\]\\]>", next : "start" }, { token : "text", merge : true, regex : "\\s+" }, { token : "text", merge : true, regex : ".+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token : "comment", merge : true, regex : ".+" } ] }; xml_util.tag(this.$rules, "tag", "start"); xml_util.tag(this.$rules, "style", "css-start"); xml_util.tag(this.$rules, "script", "js-start"); this.embedRules(JavaScriptHighlightRules, "js-", [{ token: "comment", regex: "\\/\\/.*(?=<\\/script>)", next: "tag" }, { token: "meta.tag", regex: "<\\/(?=script)", next: "tag" }]); this.embedRules(CssHighlightRules, "css-", [{ token: "meta.tag", regex: "<\\/(?=style)", next: "tag" }]); }; oop.inherits(ColdfusionHighlightRules, TextHighlightRules); exports.ColdfusionHighlightRules = ColdfusionHighlightRules; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Shlomo Zalman Heigh <shlomozalmanheigh AT gmail DOT 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 ***** */ define('ace/mode/ruby', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ruby_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new RubyHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/ruby_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var RubyHighlightRules = function() { var builtinFunctions = lang.arrayToMap( ("abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" + "assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" + "assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" + "assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" + "assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" + "assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" + "attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" + "caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" + "exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" + "gsub!|get_via_redirect|h|host!|https?|https!|include|Integer|lambda|link_to|" + "link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" + "p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" + "raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" + "set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" + "throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" + "render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" + "content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" + "fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" + "time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" + "select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" + "file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" + "protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" + "send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" + "validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" + "validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" + "authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" + "filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" + "translate|localize|extract_locale_from_tld|t|l|caches_page|expire_page|caches_action|expire_action|" + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + "has_many|has_one|belongs_to|has_and_belongs_to_many").split("|") ); var keywords = lang.arrayToMap( ("alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" + "__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" + "redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield").split("|") ); var buildinConstants = lang.arrayToMap( ("true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" + "RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING").split("|") ); var builtinVariables = lang.arrayToMap( ("\$DEBUG|\$defout|\$FILENAME|\$LOAD_PATH|\$SAFE|\$stdin|\$stdout|\$stderr|\$VERBOSE|" + "$!|root_url|flash|session|cookies|params|request|response|logger").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "comment", // multi line comment merge : true, regex : "^\=begin$", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // backtick string regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]" }, { token : "text", // namespaces aren't symbols regex : "::" }, { token : "variable.instancce", // instance variable regex : "@{1,2}(?:[a-zA-Z_]|\d)+" }, { token : "variable.class", // class name regex : "[A-Z](?:[a-zA-Z_]|\d)+" }, { token : "string", // symbol regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "self") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : "^\=end$", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; }; oop.inherits(RubyHighlightRules, TextHighlightRules); exports.RubyHighlightRules = RubyHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/tomorrow', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-tomorrow"; exports.cssText = "\ .ace-tomorrow .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-tomorrow .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-tomorrow .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-tomorrow .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-tomorrow .ace_scroller {\ background-color: #FFFFFF;\ }\ \ .ace-tomorrow .ace_text-layer {\ cursor: text;\ color: #4D4D4C;\ }\ \ .ace-tomorrow .ace_cursor {\ border-left: 2px solid #AEAFAD;\ }\ \ .ace-tomorrow .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #AEAFAD;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_selection {\ background: #D6D6D6;\ }\ \ .ace-tomorrow.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #FFFFFF;\ border-radius: 2px;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_step {\ background: rgb(255, 255, 0);\ }\ \ .ace-tomorrow .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #D1D1D1;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_active_line {\ background: #EFEFEF;\ }\ \ .ace-tomorrow .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-tomorrow .ace_marker-layer .ace_selected_word {\ border: 1px solid #D6D6D6;\ }\ \ .ace-tomorrow .ace_invisible {\ color: #D1D1D1;\ }\ \ .ace-tomorrow .ace_keyword, .ace-tomorrow .ace_meta {\ color:#8959A8;\ }\ \ .ace-tomorrow .ace_keyword.ace_operator {\ color:#3E999F;\ }\ \ .ace-tomorrow .ace_constant.ace_language {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_constant.ace_numeric {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_constant.ace_other {\ color:#666969;\ }\ \ .ace-tomorrow .ace_invalid {\ color:#FFFFFF;\ background-color:#C82829;\ }\ \ .ace-tomorrow .ace_invalid.ace_deprecated {\ color:#FFFFFF;\ background-color:#8959A8;\ }\ \ .ace-tomorrow .ace_support.ace_constant {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_fold {\ background-color: #4271AE;\ border-color: #4D4D4C;\ }\ \ .ace-tomorrow .ace_support.ace_function {\ color:#4271AE;\ }\ \ .ace-tomorrow .ace_storage {\ color:#8959A8;\ }\ \ .ace-tomorrow .ace_storage.ace_type, .ace-tomorrow .ace_support.ace_type{\ color:#8959A8;\ }\ \ .ace-tomorrow .ace_variable {\ color:#4271AE;\ }\ \ .ace-tomorrow .ace_variable.ace_parameter {\ color:#F5871F;\ }\ \ .ace-tomorrow .ace_string {\ color:#718C00;\ }\ \ .ace-tomorrow .ace_string.ace_regexp {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_comment {\ color:#8E908C;\ }\ \ .ace-tomorrow .ace_variable {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_meta.ace_tag {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_entity.ace_other.ace_attribute-name {\ color:#C82829;\ }\ \ .ace-tomorrow .ace_entity.ace_name.ace_function {\ color:#4271AE;\ }\ \ .ace-tomorrow .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-tomorrow .ace_markup.ace_heading {\ color:#718C00;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Garen J. Torikian <gjtorikian AT gmail DOT 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 ***** */ define('ace/mode/c9search', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/c9search_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/c9search'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var C9SearchHighlightRules = require("./c9search_highlight_rules").C9SearchHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var C9StyleFoldMode = require("./folding/c9search").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new C9SearchHighlightRules().getRules(), "i"); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new C9StyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); // ignore braces in comments var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/c9search_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var C9SearchHighlightRules = function() { // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : ["constant.numeric", "text", "text"], regex : "(^\\s+[0-9]+)(:\\s*)(.+)" }, { token : ["string", "text"], // single line regex : "(.+)(:$)" } ] }; }; oop.inherits(C9SearchHighlightRules, TextHighlightRules); exports.C9SearchHighlightRules = C9SearchHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/c9search', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /[a-zA-Z](:)\s*$/; this.foldingStopMarker = /^(\s*)$/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i, false, true); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/twilight', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-twilight"; exports.cssText = "\ .ace-twilight .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-twilight .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-twilight .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-twilight .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-twilight .ace_scroller {\ background-color: #141414;\ }\ \ .ace-twilight .ace_text-layer {\ cursor: text;\ color: #F8F8F8;\ }\ \ .ace-twilight .ace_cursor {\ border-left: 2px solid #A7A7A7;\ }\ \ .ace-twilight .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #A7A7A7;\ }\ \ .ace-twilight .ace_marker-layer .ace_selection {\ background: rgba(221, 240, 255, 0.20);\ }\ \ .ace-twilight.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #141414;\ border-radius: 2px;\ }\ \ .ace-twilight .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-twilight .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(255, 255, 255, 0.25);\ }\ \ .ace-twilight .ace_marker-layer .ace_active_line {\ background: rgba(255, 255, 255, 0.031);\ }\ \ .ace-twilight .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-twilight .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(221, 240, 255, 0.20);\ }\ \ .ace-twilight .ace_invisible {\ color: rgba(255, 255, 255, 0.25);\ }\ \ .ace-twilight .ace_keyword, .ace-twilight .ace_meta {\ color:#CDA869;\ }\ \ .ace-twilight .ace_constant, .ace-twilight .ace_constant.ace_other {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_constant.ace_character, {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_constant.ace_character.ace_escape, {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_invalid.ace_illegal {\ color:#F8F8F8;\ background-color:rgba(86, 45, 86, 0.75);\ }\ \ .ace-twilight .ace_invalid.ace_deprecated {\ text-decoration:underline;\ font-style:italic;\ color:#D2A8A1;\ }\ \ .ace-twilight .ace_support {\ color:#9B859D;\ }\ \ .ace-twilight .ace_support.ace_constant {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_fold {\ background-color: #AC885B;\ border-color: #F8F8F8;\ }\ \ .ace-twilight .ace_support.ace_function {\ color:#DAD085;\ }\ \ .ace-twilight .ace_storage {\ color:#F9EE98;\ }\ \ .ace-twilight .ace_variable {\ color:#AC885B;\ }\ \ .ace-twilight .ace_string {\ color:#8F9D6A;\ }\ \ .ace-twilight .ace_string.ace_regexp {\ color:#E9C062;\ }\ \ .ace-twilight .ace_comment {\ font-style:italic;\ color:#5F5A60;\ }\ \ .ace-twilight .ace_variable {\ color:#7587A6;\ }\ \ .ace-twilight .ace_xml_pe {\ color:#494949;\ }\ \ .ace-twilight .ace_meta.ace_tag {\ color:#AC885B;\ }\ \ .ace-twilight .ace_entity.ace_name.ace_function {\ color:#AC885B;\ }\ \ .ace-twilight .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-twilight .ace_markup.ace_heading {\ color:#CF6A4C;\ }\ \ .ace-twilight .ace_markup.ace_list {\ color:#F9EE98;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
define('ace/mode/scala', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/scala_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var JavaScriptMode = require("./javascript").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ScalaHighlightRules = require("./scala_highlight_rules").ScalaHighlightRules; var Mode = function() { JavaScriptMode.call(this); this.$tokenizer = new Tokenizer(new ScalaHighlightRules().getRules()); }; oop.inherits(Mode, JavaScriptMode); (function() { this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "regex_allowed") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || state == "regex_allowed") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); 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); exports.Mode = Mode; }); define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var unicode = require("../unicode"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function() { // see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects var globals = lang.arrayToMap( // Constructors ("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // E4X "Namespace|QName|XML|XMLList|" + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + // Errors "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + "SyntaxError|TypeError|URIError|" + // Non-constructor functions "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + "isNaN|parseFloat|parseInt|" + // Other "JSON|Math|" + // Pseudo "this|arguments|prototype|window|document" ).split("|") ); var keywords = lang.arrayToMap( ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); // keywords which can be followed by regular expressions var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield"; var deprecated = lang.arrayToMap( ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); var definitions = lang.arrayToMap(("const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") ); var futureReserved = lang.arrayToMap( ("class|enum|extends|super|export|implements|private|" + "public|interface|package|protected|static").split("|") ); // TODO: Unicode escape sequences var identifierRe = "[" + unicode.packages.L + "\\$_][" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\\$_]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : /\/\/.*$/ }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { // match stuff like: Sound.prototype.play = function() { } token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: Sound.prototype.play = myfunc token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)", next: "function_arguments" }, { // match stuff like: Sound.play = function() { } token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: play = function() { } token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // match regular function like: function myFunc(arg) { } token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { // match stuff like: foobar: function() { } token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { // Attempt to match : function() { } (this is for issues with 'foo': function() { }) token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "constant.language.boolean", regex : /(?:true|false)\b/ }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "regex_allowed" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/ }, { token : function(value) { if (globals.hasOwnProperty(value)) return "variable.language"; else if (deprecated.hasOwnProperty(value)) return "invalid.deprecated"; else if (definitions.hasOwnProperty(value)) return "storage.type"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : identifierRe }, { token : "keyword.operator", regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/, next : "regex_allowed" }, { token : "punctuation.operator", regex : /\?|\:|\,|\;|\./, next : "regex_allowed" }, { token : "paren.lparen", regex : /[\[({]/, next : "regex_allowed" }, { token : "paren.rparen", regex : /[\])}]/ }, { token : "keyword.operator", regex : /\/=?/, next : "regex_allowed" }, { token: "comment", regex: /^#!.*$/ }, { token : "text", regex : /\s+/ } ], // regular expressions are only allowed after certain tokens. This // makes sure we don't mix up regexps with the divison operator "regex_allowed": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/.*$" }, { token: "string.regexp", regex: "\\/", next: "regex", merge: true }, { token : "text", regex : "\\s+" }, { // immediately return to the start mode without matching // anything token: "empty", regex: "", next: "start" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { // flag token: "string.regexp", regex: "/\\w*", next: "start", merge: true }, { token: "string.regexp", regex: "[^\\\\/\\[]+", merge: true }, { token: "string.regexp.charachterclass", regex: "\\[", next: "regex_character_class", merge: true }, { token: "empty", regex: "", next: "start" } ], "regex_character_class": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp.charachterclass", regex: "]", next: "regex", merge: true }, { token: "string.regexp.charachterclass", regex: "[^\\\\\\]]+", merge: true }, { token: "empty", regex: "", next: "start" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe, }, { token: "punctuation.operator", regex: "[, ]+", merge: true }, { token: "punctuation.operator", regex: "$", merge: true }, { token: "empty", regex: "", next: "start" } ], "comment_regex_allowed" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "regex_allowed" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", merge : true, next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : '[^"\\\\]+', merge : true }, { token : "string", regex : "\\\\$", next : "qqstring", merge : true }, { token : "string", regex : '"|$', next : "start", merge : true } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "[^'\\\\]+", merge : true }, { token : "string", regex : "\\\\$", next : "qstring", merge : true }, { token : "string", regex : "'|$", next : "start", merge : true } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); }); define('ace/mode/scala_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ScalaHighlightRules = function() { // taken from http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html var keywords = lang.arrayToMap( ( "case|default|do|else|for|if|match|while|throw|return|try|catch|finally|yield|" + "abstract|class|def|extends|final|forSome|implicit|implicits|import|lazy|new|object|" + "override|package|private|protected|sealed|super|this|trait|type|val|var|with" ).split("|") ); var buildinConstants = lang.arrayToMap( ("true|false").split("|") ); var langClasses = lang.arrayToMap( ("AbstractMethodError|AssertionError|ClassCircularityError|"+ "ClassFormatError|Deprecated|EnumConstantNotPresentException|"+ "ExceptionInInitializerError|IllegalAccessError|"+ "IllegalThreadStateException|InstantiationError|InternalError|"+ "NegativeArraySizeException|NoSuchFieldError|Override|Process|"+ "ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+ "SuppressWarnings|TypeNotPresentException|UnknownError|"+ "UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+ "InstantiationException|IndexOutOfBoundsException|"+ "ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+ "NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+ "SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+ "InterruptedException|NoSuchMethodException|IllegalAccessException|"+ "UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+ "Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+ "NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+ "NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+ "Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+ "Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+ "StackOverflowError|OutOfMemoryError|VirtualMachineError|"+ "ArrayStoreException|ClassCastException|LinkageError|"+ "NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+ "Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+ "Cloneable|Class|CharSequence|Comparable|String|Object|" + "Unit|Any|AnyVal|AnyRef|Null|ScalaObject|Singleton|Seq|Iterable|List|" + "Option|Array|Char|Byte|Short|Int|Long|Nothing" ).split("|") ); var importClasses = lang.arrayToMap( ("").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", regex : '"""', next : "tstring" }, { token : "string", regex : '"(?=.)', // " strings can't span multiple lines next : "string" }, { token : "symbol.constant", // single line regex : "'[\\w\\d_]+" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (langClasses.hasOwnProperty(value)) return "support.function"; else if (importClasses.hasOwnProperty(value)) return "support.function"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "string" : [ { token : "escape", regex : '\\\\"', }, { token : "string", merge : true, regex : '"', next : "start" }, { token : "string.invalid", regex : '[^"\\\\]*$', next : "start" }, { token : "string", regex : '[^"\\\\]+', merge : true } ], "tstring" : [ { token : "string", // closing comment regex : '"{3,5}', next : "start" }, { token : "string", // comment spanning whole line merge : true, regex : ".+?" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(ScalaHighlightRules, TextHighlightRules); exports.ScalaHighlightRules = ScalaHighlightRules; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/crimson_editor', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssText = ".ace-crimson-editor .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-crimson-editor .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-crimson-editor .ace_gutter {\ background: #e8e8e8;\ color: #333;\ overflow : hidden;\ }\ \ .ace-crimson-editor .ace_gutter-layer {\ width: 100%;\ text-align: right;\ }\ \ .ace-crimson-editor .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-crimson-editor .ace_text-layer {\ cursor: text;\ color: rgb(64, 64, 64);\ }\ \ .ace-crimson-editor .ace_cursor {\ border-left: 2px solid black;\ }\ \ .ace-crimson-editor .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid black;\ }\ \ .ace-crimson-editor .ace_line .ace_invisible {\ color: rgb(191, 191, 191);\ }\ \ .ace-crimson-editor .ace_line .ace_identifier {\ color: black;\ }\ \ .ace-crimson-editor .ace_line .ace_keyword {\ color: blue;\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_buildin {\ color: rgb(88, 72, 246);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_language {\ color: rgb(255, 156, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_library {\ color: rgb(6, 150, 14);\ }\ \ .ace-crimson-editor .ace_line .ace_invalid {\ text-decoration: line-through;\ color: rgb(224, 0, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_fold {\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_function {\ color: rgb(192, 0, 0);\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_constant {\ color: rgb(6, 150, 14);\ }\ \ .ace-crimson-editor .ace_line .ace_support.ace_type,\ .ace-crimson-editor .ace_line .ace_support.ace_class {\ color: rgb(109, 121, 222);\ }\ \ .ace-crimson-editor .ace_line .ace_keyword.ace_operator {\ color: rgb(49, 132, 149);\ }\ \ .ace-crimson-editor .ace_line .ace_string {\ color: rgb(128, 0, 128);\ }\ \ .ace-crimson-editor .ace_line .ace_comment {\ color: rgb(76, 136, 107);\ }\ \ .ace-crimson-editor .ace_line .ace_comment.ace_doc {\ color: rgb(0, 102, 255);\ }\ \ .ace-crimson-editor .ace_line .ace_comment.ace_doc.ace_tag {\ color: rgb(128, 159, 191);\ }\ \ .ace-crimson-editor .ace_line .ace_constant.ace_numeric {\ color: rgb(0, 0, 64);\ }\ \ .ace-crimson-editor .ace_line .ace_variable {\ color: rgb(0, 64, 128);\ }\ \ .ace-crimson-editor .ace_line .ace_xml_pe {\ color: rgb(104, 104, 91);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_selection {\ background: rgb(181, 213, 255);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_step {\ background: rgb(252, 255, 0);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_stack {\ background: rgb(164, 229, 101);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgb(192, 192, 192);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_active_line {\ background: rgb(232, 242, 254);\ }\ \ .ace-crimson-editor .ace_meta.ace_tag {\ color:rgb(28, 2, 255);\ }\ \ .ace-crimson-editor .ace_marker-layer .ace_selected_word {\ background: rgb(250, 250, 255);\ border: 1px solid rgb(200, 200, 250);\ }\ \ .ace-crimson-editor .ace_string.ace_regex {\ color: rgb(192, 0, 192);\ }"; exports.cssClass = "ace-crimson-editor"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Sergi Mansilla <sergi AT ajax DOT org> * * 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 ***** */ define('ace/mode/ocaml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ocaml_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var OcamlHighlightRules = require("./ocaml_highlight_rules").OcamlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new OcamlHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); var indenter = /(?:[({[=:]|[-=]>|\b(?:else|try|with))\s*$/; (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var i, line; var outdent = true; var re = /^\s*\(\*(.*)\*\)/; for (i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } var range = new Range(0, 0, 0, 0); for (i=startRow; i<= endRow; i++) { line = doc.getLine(i); range.start.row = i; range.end.row = i; range.end.column = line.length; doc.replace(range, outdent ? line.match(re)[1] : "(*" + line + "*)"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.$tokenizer.getLineTokens(line, state).tokens; if (!(tokens.length && tokens[tokens.length - 1].type === 'comment') && state === 'start' && indenter.test(line)) indent += tab; return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/ocaml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var OcamlHighlightRules = function() { var keywords = lang.arrayToMap(( "and|as|assert|begin|class|constraint|do|done|downto|else|end|" + "exception|external|for|fun|function|functor|if|in|include|" + "inherit|initializer|lazy|let|match|method|module|mutable|new|" + "object|of|open|or|private|rec|sig|struct|then|to|try|type|val|" + "virtual|when|while|with").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false").split("|") ); var builtinFunctions = lang.arrayToMap(( "abs|abs_big_int|abs_float|abs_num|abstract_tag|accept|access|acos|add|" + "add_available_units|add_big_int|add_buffer|add_channel|add_char|" + "add_initializer|add_int_big_int|add_interfaces|add_num|add_string|" + "add_substitute|add_substring|alarm|allocated_bytes|allow_only|" + "allow_unsafe_modules|always|append|appname_get|appname_set|" + "approx_num_exp|approx_num_fix|arg|argv|arith_status|array|" + "array1_of_genarray|array2_of_genarray|array3_of_genarray|asin|asr|" + "assoc|assq|at_exit|atan|atan2|auto_synchronize|background|basename|" + "beginning_of_input|big_int_of_int|big_int_of_num|big_int_of_string|bind|" + "bind_class|bind_tag|bits|bits_of_float|black|blit|blit_image|blue|bool|" + "bool_of_string|bounded_full_split|bounded_split|bounded_split_delim|" + "bprintf|break|broadcast|bscanf|button_down|c_layout|capitalize|cardinal|" + "cardinal|catch|catch_break|ceil|ceiling_num|channel|char|char_of_int|" + "chdir|check|check_suffix|chmod|choose|chop_extension|chop_suffix|chown|" + "chown|chr|chroot|classify_float|clear|clear_available_units|" + "clear_close_on_exec|clear_graph|clear_nonblock|clear_parser|" + "close|close|closeTk|close_box|close_graph|close_in|close_in_noerr|" + "close_out|close_out_noerr|close_process|close_process|" + "close_process_full|close_process_in|close_process_out|close_subwindow|" + "close_tag|close_tbox|closedir|closedir|closure_tag|code|combine|" + "combine|combine|command|compact|compare|compare_big_int|compare_num|" + "complex32|complex64|concat|conj|connect|contains|contains_from|contents|" + "copy|cos|cosh|count|count|counters|create|create_alarm|create_image|" + "create_matrix|create_matrix|create_matrix|create_object|" + "create_object_and_run_initializers|create_object_opt|create_process|" + "create_process|create_process_env|create_process_env|create_table|" + "current|current_dir_name|current_point|current_x|current_y|curveto|" + "custom_tag|cyan|data_size|decr|decr_num|default_available_units|delay|" + "delete_alarm|descr_of_in_channel|descr_of_out_channel|destroy|diff|dim|" + "dim1|dim2|dim3|dims|dirname|display_mode|div|div_big_int|div_num|" + "double_array_tag|double_tag|draw_arc|draw_char|draw_circle|draw_ellipse|" + "draw_image|draw_poly|draw_poly_line|draw_rect|draw_segments|draw_string|" + "dummy_pos|dummy_table|dump_image|dup|dup2|elements|empty|end_of_input|" + "environment|eprintf|epsilon_float|eq_big_int|eq_num|equal|err_formatter|" + "error_message|escaped|establish_server|executable_name|execv|execve|execvp|" + "execvpe|exists|exists2|exit|exp|failwith|fast_sort|fchmod|fchown|field|" + "file|file_exists|fill|fill_arc|fill_circle|fill_ellipse|fill_poly|fill_rect|" + "filter|final_tag|finalise|find|find_all|first_chars|firstkey|flatten|" + "float|float32|float64|float_of_big_int|float_of_bits|float_of_int|" + "float_of_num|float_of_string|floor|floor_num|flush|flush_all|flush_input|" + "flush_str_formatter|fold|fold_left|fold_left2|fold_right|fold_right2|" + "for_all|for_all2|force|force_newline|force_val|foreground|fork|" + "format_of_string|formatter_of_buffer|formatter_of_out_channel|" + "fortran_layout|forward_tag|fprintf|frexp|from|from_channel|from_file|" + "from_file_bin|from_function|from_string|fscanf|fst|fstat|ftruncate|" + "full_init|full_major|full_split|gcd_big_int|ge_big_int|ge_num|" + "genarray_of_array1|genarray_of_array2|genarray_of_array3|get|" + "get_all_formatter_output_functions|get_approx_printing|get_copy|" + "get_ellipsis_text|get_error_when_null_denominator|get_floating_precision|" + "get_formatter_output_functions|get_formatter_tag_functions|get_image|" + "get_margin|get_mark_tags|get_max_boxes|get_max_indent|get_method|" + "get_method_label|get_normalize_ratio|get_normalize_ratio_when_printing|" + "get_print_tags|get_state|get_variable|getcwd|getegid|getegid|getenv|" + "getenv|getenv|geteuid|geteuid|getgid|getgid|getgrgid|getgrgid|getgrnam|" + "getgrnam|getgroups|gethostbyaddr|gethostbyname|gethostname|getitimer|" + "getlogin|getpeername|getpid|getppid|getprotobyname|getprotobynumber|" + "getpwnam|getpwuid|getservbyname|getservbyport|getsockname|getsockopt|" + "getsockopt_float|getsockopt_int|getsockopt_optint|gettimeofday|getuid|" + "global_replace|global_substitute|gmtime|green|grid|group_beginning|" + "group_end|gt_big_int|gt_num|guard|handle_unix_error|hash|hash_param|" + "hd|header_size|i|id|ignore|in_channel_length|in_channel_of_descr|incr|" + "incr_num|index|index_from|inet_addr_any|inet_addr_of_string|infinity|" + "infix_tag|init|init_class|input|input_binary_int|input_byte|input_char|" + "input_line|input_value|int|int16_signed|int16_unsigned|int32|int64|" + "int8_signed|int8_unsigned|int_of_big_int|int_of_char|int_of_float|" + "int_of_num|int_of_string|integer_num|inter|interactive|inv|invalid_arg|" + "is_block|is_empty|is_implicit|is_int|is_int_big_int|is_integer_num|" + "is_relative|iter|iter2|iteri|join|junk|key_pressed|kill|kind|kprintf|" + "kscanf|land|last_chars|layout|lazy_from_fun|lazy_from_val|lazy_is_val|" + "lazy_tag|ldexp|le_big_int|le_num|length|lexeme|lexeme_char|lexeme_end|" + "lexeme_end_p|lexeme_start|lexeme_start_p|lineto|link|list|listen|lnot|" + "loadfile|loadfile_private|localtime|lock|lockf|log|log10|logand|lognot|" + "logor|logxor|lor|lower_window|lowercase|lseek|lsl|lsr|lstat|lt_big_int|" + "lt_num|lxor|magenta|magic|mainLoop|major|major_slice|make|make_formatter|" + "make_image|make_lexer|make_matrix|make_self_init|map|map2|map_file|mapi|" + "marshal|match_beginning|match_end|matched_group|matched_string|max|" + "max_array_length|max_big_int|max_elt|max_float|max_int|max_num|" + "max_string_length|mem|mem_assoc|mem_assq|memq|merge|min|min_big_int|" + "min_elt|min_float|min_int|min_num|minor|minus_big_int|minus_num|" + "minus_one|mkdir|mkfifo|mktime|mod|mod_big_int|mod_float|mod_num|modf|" + "mouse_pos|moveto|mul|mult_big_int|mult_int_big_int|mult_num|nan|narrow|" + "nat_of_num|nativeint|neg|neg_infinity|new_block|new_channel|new_method|" + "new_variable|next|nextkey|nice|nice|no_scan_tag|norm|norm2|not|npeek|" + "nth|nth_dim|num_digits_big_int|num_dims|num_of_big_int|num_of_int|" + "num_of_nat|num_of_ratio|num_of_string|O|obj|object_tag|ocaml_version|" + "of_array|of_channel|of_float|of_int|of_int32|of_list|of_nativeint|" + "of_string|one|openTk|open_box|open_connection|open_graph|open_hbox|" + "open_hovbox|open_hvbox|open_in|open_in_bin|open_in_gen|open_out|" + "open_out_bin|open_out_gen|open_process|open_process_full|open_process_in|" + "open_process_out|open_subwindow|open_tag|open_tbox|open_temp_file|" + "open_vbox|opendbm|opendir|openfile|or|os_type|out_channel_length|" + "out_channel_of_descr|output|output_binary_int|output_buffer|output_byte|" + "output_char|output_string|output_value|over_max_boxes|pack|params|" + "parent_dir_name|parse|parse_argv|partition|pause|peek|pipe|pixels|" + "place|plot|plots|point_color|polar|poll|pop|pos_in|pos_out|pow|" + "power_big_int_positive_big_int|power_big_int_positive_int|" + "power_int_positive_big_int|power_int_positive_int|power_num|" + "pp_close_box|pp_close_tag|pp_close_tbox|pp_force_newline|" + "pp_get_all_formatter_output_functions|pp_get_ellipsis_text|" + "pp_get_formatter_output_functions|pp_get_formatter_tag_functions|" + "pp_get_margin|pp_get_mark_tags|pp_get_max_boxes|pp_get_max_indent|" + "pp_get_print_tags|pp_open_box|pp_open_hbox|pp_open_hovbox|pp_open_hvbox|" + "pp_open_tag|pp_open_tbox|pp_open_vbox|pp_over_max_boxes|pp_print_as|" + "pp_print_bool|pp_print_break|pp_print_char|pp_print_cut|pp_print_float|" + "pp_print_flush|pp_print_if_newline|pp_print_int|pp_print_newline|" + "pp_print_space|pp_print_string|pp_print_tab|pp_print_tbreak|" + "pp_set_all_formatter_output_functions|pp_set_ellipsis_text|" + "pp_set_formatter_out_channel|pp_set_formatter_output_functions|" + "pp_set_formatter_tag_functions|pp_set_margin|pp_set_mark_tags|" + "pp_set_max_boxes|pp_set_max_indent|pp_set_print_tags|pp_set_tab|" + "pp_set_tags|pred|pred_big_int|pred_num|prerr_char|prerr_endline|" + "prerr_float|prerr_int|prerr_newline|prerr_string|print|print_as|" + "print_bool|print_break|print_char|print_cut|print_endline|print_float|" + "print_flush|print_if_newline|print_int|print_newline|print_space|" + "print_stat|print_string|print_tab|print_tbreak|printf|prohibit|" + "public_method_label|push|putenv|quo_num|quomod_big_int|quote|raise|" + "raise_window|ratio_of_num|rcontains_from|read|read_float|read_int|" + "read_key|read_line|readdir|readdir|readlink|really_input|receive|recv|" + "recvfrom|red|ref|regexp|regexp_case_fold|regexp_string|" + "regexp_string_case_fold|register|register_exception|rem|remember_mode|" + "remove|remove_assoc|remove_assq|rename|replace|replace_first|" + "replace_matched|repr|reset|reshape|reshape_1|reshape_2|reshape_3|rev|" + "rev_append|rev_map|rev_map2|rewinddir|rgb|rhs_end|rhs_end_pos|rhs_start|" + "rhs_start_pos|rindex|rindex_from|rlineto|rmdir|rmoveto|round_num|" + "run_initializers|run_initializers_opt|scanf|search_backward|" + "search_forward|seek_in|seek_out|select|self|self_init|send|sendto|set|" + "set_all_formatter_output_functions|set_approx_printing|" + "set_binary_mode_in|set_binary_mode_out|set_close_on_exec|" + "set_close_on_exec|set_color|set_ellipsis_text|" + "set_error_when_null_denominator|set_field|set_floating_precision|" + "set_font|set_formatter_out_channel|set_formatter_output_functions|" + "set_formatter_tag_functions|set_line_width|set_margin|set_mark_tags|" + "set_max_boxes|set_max_indent|set_method|set_nonblock|set_nonblock|" + "set_normalize_ratio|set_normalize_ratio_when_printing|set_print_tags|" + "set_signal|set_state|set_tab|set_tag|set_tags|set_text_size|" + "set_window_title|setgid|setgid|setitimer|setitimer|setsid|setsid|" + "setsockopt|setsockopt|setsockopt_float|setsockopt_float|setsockopt_int|" + "setsockopt_int|setsockopt_optint|setsockopt_optint|setuid|setuid|" + "shift_left|shift_left|shift_left|shift_right|shift_right|shift_right|" + "shift_right_logical|shift_right_logical|shift_right_logical|show_buckets|" + "shutdown|shutdown|shutdown_connection|shutdown_connection|sigabrt|" + "sigalrm|sigchld|sigcont|sigfpe|sighup|sigill|sigint|sigkill|sign_big_int|" + "sign_num|signal|signal|sigpending|sigpending|sigpipe|sigprocmask|" + "sigprocmask|sigprof|sigquit|sigsegv|sigstop|sigsuspend|sigsuspend|" + "sigterm|sigtstp|sigttin|sigttou|sigusr1|sigusr2|sigvtalrm|sin|singleton|" + "sinh|size|size|size_x|size_y|sleep|sleep|sleep|slice_left|slice_left|" + "slice_left_1|slice_left_2|slice_right|slice_right|slice_right_1|" + "slice_right_2|snd|socket|socket|socket|socketpair|socketpair|sort|sound|" + "split|split_delim|sprintf|sprintf|sqrt|sqrt|sqrt_big_int|square_big_int|" + "square_num|sscanf|stable_sort|stable_sort|stable_sort|stable_sort|stable_sort|" + "stable_sort|stat|stat|stat|stat|stat|stats|stats|std_formatter|stdbuf|" + "stderr|stderr|stderr|stdib|stdin|stdin|stdin|stdout|stdout|stdout|" + "str_formatter|string|string_after|string_before|string_match|" + "string_of_big_int|string_of_bool|string_of_float|string_of_format|" + "string_of_inet_addr|string_of_inet_addr|string_of_int|string_of_num|" + "string_partial_match|string_tag|sub|sub|sub_big_int|sub_left|sub_num|" + "sub_right|subset|subset|substitute_first|substring|succ|succ|" + "succ|succ|succ_big_int|succ_num|symbol_end|symbol_end_pos|symbol_start|" + "symbol_start_pos|symlink|symlink|sync|synchronize|system|system|system|" + "tag|take|tan|tanh|tcdrain|tcdrain|tcflow|tcflow|tcflush|tcflush|" + "tcgetattr|tcgetattr|tcsendbreak|tcsendbreak|tcsetattr|tcsetattr|" + "temp_file|text_size|time|time|time|timed_read|timed_write|times|times|" + "tl|tl|tl|to_buffer|to_channel|to_float|to_hex|to_int|to_int32|to_list|" + "to_list|to_list|to_nativeint|to_string|to_string|to_string|to_string|" + "to_string|top|top|total_size|transfer|transp|truncate|truncate|truncate|" + "truncate|truncate|truncate|try_lock|umask|umask|uncapitalize|uncapitalize|" + "uncapitalize|union|union|unit_big_int|unlink|unlink|unlock|unmarshal|" + "unsafe_blit|unsafe_fill|unsafe_get|unsafe_get|unsafe_set|unsafe_set|" + "update|uppercase|uppercase|uppercase|uppercase|usage|utimes|utimes|wait|" + "wait|wait|wait|wait_next_event|wait_pid|wait_read|wait_signal|" + "wait_timed_read|wait_timed_write|wait_write|waitpid|white|" + "widen|window_id|word_size|wrap|wrap_abort|write|yellow|yield|zero|zero_big_int|" + "Arg|Arith_status|Array|Array1|Array2|Array3|ArrayLabels|Big_int|Bigarray|" + "Buffer|Callback|CamlinternalOO|Char|Complex|Condition|Dbm|Digest|Dynlink|" + "Event|Filename|Format|Gc|Genarray|Genlex|Graphics|GraphicsX11|Hashtbl|" + "Int32|Int64|LargeFile|Lazy|Lexing|List|ListLabels|Make|Map|Marshal|" + "MoreLabels|Mutex|Nativeint|Num|Obj|Oo|Parsing|Pervasives|Printexc|" + "Printf|Queue|Random|Scanf|Scanning|Set|Sort|Stack|State|StdLabels|Str|" + "Stream|String|StringLabels|Sys|Thread|ThreadUnix|Tk|Unix|UnixLabels|Weak" ).split("|")); var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; this.$rules = { "start" : [ { token : "comment", regex : '\\(\\*.*?\\*\\)\\s*?$' }, { token : "comment", merge : true, regex : '\\(\\*.*', next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single char regex : "'.'" }, { token : "string", // " string merge : true, regex : '"', next : "qstring" }, { token : "constant.numeric", // imaginary regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+\\.|\\-\\.|\\*\\.|\\/\\.|#|;;|\\+|\\-|\\*|\\*\\*\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|<-|=" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\)", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qstring" : [ { token : "string", regex : '"', next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(OcamlHighlightRules, TextHighlightRules); exports.OcamlHighlightRules = OcamlHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/clouds', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-clouds"; exports.cssText = "\ .ace-clouds .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-clouds .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-clouds .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-clouds .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-clouds .ace_scroller {\ background-color: #FFFFFF;\ }\ \ .ace-clouds .ace_text-layer {\ cursor: text;\ color: #000000;\ }\ \ .ace-clouds .ace_cursor {\ border-left: 2px solid #000000;\ }\ \ .ace-clouds .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #000000;\ }\ \ .ace-clouds .ace_marker-layer .ace_selection {\ background: #BDD5FC;\ }\ \ .ace-clouds.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #FFFFFF;\ border-radius: 2px;\ }\ \ .ace-clouds .ace_marker-layer .ace_step {\ background: rgb(255, 255, 0);\ }\ \ .ace-clouds .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #BFBFBF;\ }\ \ .ace-clouds .ace_marker-layer .ace_active_line {\ background: #FFFBD1;\ }\ \ .ace-clouds .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-clouds .ace_marker-layer .ace_selected_word {\ border: 1px solid #BDD5FC;\ }\ \ .ace-clouds .ace_invisible {\ color: #BFBFBF;\ }\ \ .ace-clouds .ace_keyword, .ace-clouds .ace_meta {\ color:#AF956F;\ }\ \ .ace-clouds .ace_keyword.ace_operator {\ color:#484848;\ }\ \ .ace-clouds .ace_constant.ace_language {\ color:#39946A;\ }\ \ .ace-clouds .ace_constant.ace_numeric {\ color:#46A609;\ }\ \ .ace-clouds .ace_invalid {\ background-color:#FF002A;\ }\ \ .ace-clouds .ace_fold {\ background-color: #AF956F;\ border-color: #000000;\ }\ \ .ace-clouds .ace_support.ace_function {\ color:#C52727;\ }\ \ .ace-clouds .ace_storage {\ color:#C52727;\ }\ \ .ace-clouds .ace_string {\ color:#5D90CD;\ }\ \ .ace-clouds .ace_comment {\ color:#BCC8BA;\ }\ \ .ace-clouds .ace_entity.ace_other.ace_attribute-name {\ color:#606060;\ }\ \ .ace-clouds .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
define('ace/mode/golang', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/golang_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var GolangHighlightRules = require("./golang_highlight_rules").GolangHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new GolangHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; };//end getNextLineIndent this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/golang_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var GolangHighlightRules = function() { var keywords = lang.arrayToMap( ("true|else|false|break|case|return|goto|if|const|" + "continue|struct|default|switch|for|" + "func|import|package|chan|defer|fallthrough|go|interface|map|range" + "select|type|var").split("|") ); var buildinConstants = lang.arrayToMap( ("nit|true|false|iota").split("|") ); this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant", // <CONSTANT> regex : "<[a-zA-Z0-9.]+>" }, { token : "keyword", // pre-compiler directivs regex : "(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); } oop.inherits(GolangHighlightRules, TextHighlightRules); exports.GolangHighlightRules = GolangHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Wolfgang Meier * William Candillon <wcandillon AT gmail DOT 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 ***** */ define('ace/mode/xquery', ['require', 'exports', 'module' , 'ace/worker/worker_client', 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xquery_highlight_rules', 'ace/mode/behaviour/xquery', 'ace/range'], function(require, exports, module) { var WorkerClient = require("../worker/worker_client").WorkerClient; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var XQueryHighlightRules = require("./xquery_highlight_rules").XQueryHighlightRules; var XQueryBehaviour = require("./behaviour/xquery").XQueryBehaviour; //var XQueryBackgroundHighlighter = require("./xquery_background_highlighter").XQueryBackgroundHighlighter; var Range = require("../range").Range; var Mode = function(parent) { this.$tokenizer = new Tokenizer(new XQueryHighlightRules().getRules()); this.$behaviour = new XQueryBehaviour(parent); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var match = line.match(/\s*(?:then|else|return|[{\(]|<\w+>)\s*$/); if (match) indent += tab; return indent; }; this.checkOutdent = function(state, line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*[\}\)]/.test(input); }; this.autoOutdent = function(state, doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*[\}\)])/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; this.toggleCommentLines = function(state, doc, startRow, endRow) { var i, line; var outdent = true; var re = /^\s*\(:(.*):\)/; for (i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } var range = new Range(0, 0, 0, 0); for (i=startRow; i<= endRow; i++) { line = doc.getLine(i); range.start.row = i; range.end.row = i; range.end.column = line.length; doc.replace(range, outdent ? line.match(re)[1] : "(:" + line + ":)"); } }; this.createWorker = function(session) { this.$deltas = []; var worker = new WorkerClient(["ace"], "worker-xquery.js", "ace/mode/xquery_worker", "XQueryWorker"); var that = this; session.getDocument().on('change', function(evt){ that.$deltas.push(evt.data); }); worker.attachToDocument(session.getDocument()); worker.on("start", function(e) { //console.log("start"); that.$deltas = []; }); worker.on("error", function(e) { session.setAnnotations([e.data]); }); worker.on("ok", function(e) { session.clearAnnotations(); }); worker.on("highlight", function(tokens) { var firstRow = 0; var lastRow = session.getLength() - 1; var lines = tokens.data.lines; var states = tokens.data.states; for(var i=0; i < that.$deltas.length; i++) { var delta = that.$deltas[i]; if (delta.action === "insertLines") { var newLineCount = delta.lines.length; for (var i = 0; i < newLineCount; i++) { lines.splice(delta.range.start.row + i, 0, undefined); states.splice(delta.range.start.row + i, 0, undefined); } } else if (delta.action === "insertText") { if (session.getDocument().isNewLine(delta.text)) { lines.splice(delta.range.end.row, 0, undefined); states.splice(delta.range.end.row, 0, undefined); } else { lines[delta.range.start.row] = undefined; states[delta.range.start.row] = undefined; } } else if (delta.action === "removeLines") { var oldLineCount = delta.lines.length; lines.splice(delta.range.start.row, oldLineCount); states.splice(delta.range.start.row, oldLineCount); } else if (delta.action === "removeText") { if (session.getDocument().isNewLine(delta.text)) { lines[delta.range.start.row] = undefined; lines.splice(delta.range.end.row, 1); states[delta.range.start.row] = undefined; states.splice(delta.range.end.row, 1); } else { lines[delta.range.start.row] = undefined; states[delta.range.start.row] = undefined; } } } session.bgTokenizer.lines = lines; session.bgTokenizer.states = states; session.bgTokenizer.fireUpdateEvent(firstRow, lastRow); }); return worker; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/xquery_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XQueryHighlightRules = function() { var keywords = lang.arrayToMap( ("after|ancestor|ancestor-or-self|and|as|ascending|attribute|before|case|cast|castable|child|collation|comment|copy|count|declare|default|delete|descendant|descendant-or-self|descending|div|document|document-node|element|else|empty|empty-sequence|end|eq|every|except|first|following|following-sibling|for|function|ge|group|gt|idiv|if|import|insert|instance|intersect|into|is|item|last|le|let|lt|mod|modify|module|namespace|namespace-node|ne|node|only|or|order|ordered|parent|preceding|preceding-sibling|processing-instruction|rename|replace|return|satisfies|schema-attribute|schema-element|self|some|stable|start|switch|text|to|treat|try|typeswitch|union|unordered|validate|where|with|xquery|contains|paragraphs|sentences|times|words|by|collectionreturn|variable|version|option|when|encoding|toswitch|catch|tumbling|sliding|window|at|using|stemming|collection|schema|while|on|nodes|index|external|then|in|updating|value|of|containsbreak|loop|continue|exit|returning").split("|") ); // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { start : [ { token : "text", regex : "<\\!\\[CDATA\\[", next : "cdata" }, { token : "xml_pe", regex : "<\\?.*?\\?>" }, { token : "comment", regex : "<\\!--", next : "comment" }, { token : "comment", regex : "\\(:", next : "comment" }, { token : "text", // opening tag regex : "<\\/?", next : "tag" }, { token : "constant", // number regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "variable", // variable regex : "\\$[a-zA-Z_][a-zA-Z0-9_\\-:]*\\b" }, { token: "string", regex : '".*?"' }, { token: "string", regex : "'.*?'" }, { token : "text", regex : "\\s+" }, { token: "support.function", regex: "\\w[\\w+_\\-:]+(?=\\()" }, { token : function(value) { if (keywords[value]) return "keyword"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token: "keyword.operator", regex: "\\*|=|<|>|\\-|\\+" }, { token: "lparen", regex: "[[({]" }, { token: "rparen", regex: "[\\])}]" } ], tag : [ { token : "text", regex : ">", next : "start" }, { token : "meta.tag", regex : "[-_a-zA-Z0-9:]+" }, { token : "text", regex : "\\s+" }, { token : "string", regex : '".*?"' }, { token : "string", regex : "'.*?'" } ], cdata : [ { token : "comment", regex : "\\]\\]>", next : "start" }, { token : "comment", regex : "\\s+" }, { token : "comment", regex : "(?:[^\\]]|\\](?!\\]>))+" } ], comment : [ { token : "comment", regex : ".*?-->", next : "start" }, { token: "comment", regex : ".*:\\)", next : "start" }, { token : "comment", regex : ".+" } ] }; }; oop.inherits(XQueryHighlightRules, TextHighlightRules); exports.XQueryHighlightRules = XQueryHighlightRules; }); define('ace/mode/behaviour/xquery', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require('../behaviour').Behaviour; var CstyleBehaviour = require('./cstyle').CstyleBehaviour; var XQueryBehaviour = function (parent) { this.inherit(CstyleBehaviour, ["braces", "parens", "string_dquotes"]); // Get string behaviour this.parent = parent; this.add("brackets", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChars = line.substring(cursor.column, cursor.column + 2); if (rightChars == '</') { var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString(); var next_indent = this.$getIndent(session.doc.getLine(cursor.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] } } } return false; }); // Check for open tag if user enters / and auto-close it. this.add("slash", "insertion", function (state, action, editor, session, text) { if (text == "/") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (cursor.column > 0 && line.charAt(cursor.column - 1) == "<") { line = line.substring(0, cursor.column) + "/" + line.substring(cursor.column); var lines = session.doc.getAllLines(); lines[cursor.row] = line; // call mode helper to close the tag if possible parent.exec("closeTag", lines.join(session.doc.getNewLineCharacter()), cursor.row); } } return false; }); } oop.inherits(XQueryBehaviour, Behaviour); exports.XQueryBehaviour = XQueryBehaviour; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/pastel_on_dark', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-pastel-on-dark"; exports.cssText = "\ .ace-pastel-on-dark .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-pastel-on-dark .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-pastel-on-dark .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-pastel-on-dark .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-pastel-on-dark .ace_scroller {\ background-color: #2C2828;\ }\ \ .ace-pastel-on-dark .ace_text-layer {\ cursor: text;\ color: #8F938F;\ }\ \ .ace-pastel-on-dark .ace_cursor {\ border-left: 2px solid #A7A7A7;\ }\ \ .ace-pastel-on-dark .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #A7A7A7;\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_selection {\ background: rgba(221, 240, 255, 0.20);\ }\ \ .ace-pastel-on-dark.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #2C2828;\ border-radius: 2px;\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(255, 255, 255, 0.25);\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_active_line {\ background: rgba(255, 255, 255, 0.031);\ }\ \ .ace-pastel-on-dark .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-pastel-on-dark .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(221, 240, 255, 0.20);\ }\ \ .ace-pastel-on-dark .ace_invisible {\ color: rgba(255, 255, 255, 0.25);\ }\ \ .ace-pastel-on-dark .ace_keyword, .ace-pastel-on-dark .ace_meta {\ color:#757aD8;\ }\ \ .ace-pastel-on-dark .ace_keyword.ace_operator {\ color:#797878;\ }\ \ .ace-pastel-on-dark .ace_constant, .ace-pastel-on-dark .ace_constant.ace_other {\ color:#4FB7C5;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_character, {\ color:#4FB7C5;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_character.ace_escape, {\ color:#4FB7C5;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_language {\ color:#DE8E30;\ }\ \ .ace-pastel-on-dark .ace_constant.ace_numeric {\ color:#CCCCCC;\ }\ \ .ace-pastel-on-dark .ace_invalid {\ color:#F8F8F8;\ background-color:rgba(86, 45, 86, 0.75);\ }\ \ .ace-pastel-on-dark .ace_invalid.ace_illegal {\ color:#F8F8F8;\ background-color:rgba(86, 45, 86, 0.75);\ }\ \ .ace-pastel-on-dark .ace_invalid.ace_deprecated {\ text-decoration:underline;\ font-style:italic;\ color:#D2A8A1;\ }\ \ .ace-pastel-on-dark .ace_fold {\ background-color: #757aD8;\ border-color: #8F938F;\ }\ \ .ace-pastel-on-dark .ace_support.ace_function {\ color:#AEB2F8;\ }\ \ .ace-pastel-on-dark .ace_string {\ color:#66A968;\ }\ \ .ace-pastel-on-dark .ace_string.ace_regexp {\ color:#E9C062;\ }\ \ .ace-pastel-on-dark .ace_comment {\ color:#A6C6FF;\ }\ \ .ace-pastel-on-dark .ace_variable {\ color:#BEBF55;\ }\ \ .ace-pastel-on-dark .ace_variable.ace_language {\ color:#C1C144;\ }\ \ .ace-pastel-on-dark .ace_xml_pe {\ color:#494949;\ }\ \ .ace-pastel-on-dark .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Rich Healey <richo AT psych0tik DOT net> * * 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 ***** */ define('ace/mode/sh', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sh_highlight_rules', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new ShHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens; if (!tokens) return false; // ignore trailing comments do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { // outdenting in sh is slightly different because it always applies // to the next line and only of a new line is inserted row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/sh_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ShHighlightRules = function() { var reservedKeywords = lang.arrayToMap( ('!|{|}|case|do|done|elif|else|'+ 'esac|fi|for|if|in|then|until|while|'+ '&|;|export|local|read|typeset|unset|'+ 'elif|select|set' ).split('|') ); var languageConstructs = lang.arrayToMap( ('[|]|alias|bg|bind|break|builtin|'+ 'cd|command|compgen|complete|continue|'+ 'dirs|disown|echo|enable|eval|exec|'+ 'exit|fc|fg|getopts|hash|help|history|'+ 'jobs|kill|let|logout|popd|printf|pushd|'+ 'pwd|return|set|shift|shopt|source|'+ 'suspend|test|times|trap|type|ulimit|'+ 'umask|unalias|wait' ).split('|') ); var integer = "(?:(?:[1-9]\\d*)|(?:0))"; // var integer = "(?:" + decimalInteger + ")"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; var fileDescriptor = "(?:&" + intPart + ")"; var variableName = "[a-zA-Z][a-zA-Z0-9_]*"; var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))"; var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))"; var func = "(?:" + variableName + "\\s*\\(\\))"; this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // " string regex : '"(?:[^\\\\]|\\\\.)*?"' }, { token : "variable.language", regex : builtinVariable }, { token : "variable", regex : variable }, { token : "support.function", regex : func, }, { token : "support.function", regex : fileDescriptor }, { token : "string", // ' string regex : "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (reservedKeywords.hasOwnProperty(value)) return "keyword"; else if (languageConstructs.hasOwnProperty(value)) return "constant.language"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!=" }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" }, { token : "text", regex : "\\s+" } ] }; }; oop.inherits(ShHighlightRules, TextHighlightRules); exports.ShHighlightRules = ShHighlightRules; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/cobalt', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-cobalt"; exports.cssText = "\ .ace-cobalt .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-cobalt .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-cobalt .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-cobalt .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-cobalt .ace_scroller {\ background-color: #002240;\ }\ \ .ace-cobalt .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-cobalt .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-cobalt .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-cobalt .ace_marker-layer .ace_selection {\ background: rgba(179, 101, 57, 0.75);\ }\ \ .ace-cobalt.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #002240;\ border-radius: 2px;\ }\ \ .ace-cobalt .ace_marker-layer .ace_step {\ background: rgb(127, 111, 19);\ }\ \ .ace-cobalt .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(255, 255, 255, 0.15);\ }\ \ .ace-cobalt .ace_marker-layer .ace_active_line {\ background: rgba(0, 0, 0, 0.35);\ }\ \ .ace-cobalt .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-cobalt .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(179, 101, 57, 0.75);\ }\ \ .ace-cobalt .ace_invisible {\ color: rgba(255, 255, 255, 0.15);\ }\ \ .ace-cobalt .ace_keyword, .ace-cobalt .ace_meta {\ color:#FF9D00;\ }\ \ .ace-cobalt .ace_constant, .ace-cobalt .ace_constant.ace_other {\ color:#FF628C;\ }\ \ .ace-cobalt .ace_constant.ace_character, {\ color:#FF628C;\ }\ \ .ace-cobalt .ace_constant.ace_character.ace_escape, {\ color:#FF628C;\ }\ \ .ace-cobalt .ace_invalid {\ color:#F8F8F8;\ background-color:#800F00;\ }\ \ .ace-cobalt .ace_support {\ color:#80FFBB;\ }\ \ .ace-cobalt .ace_support.ace_constant {\ color:#EB939A;\ }\ \ .ace-cobalt .ace_fold {\ background-color: #FF9D00;\ border-color: #FFFFFF;\ }\ \ .ace-cobalt .ace_support.ace_function {\ color:#FFB054;\ }\ \ .ace-cobalt .ace_storage {\ color:#FFEE80;\ }\ \ .ace-cobalt .ace_string.ace_regexp {\ color:#80FFC2;\ }\ \ .ace-cobalt .ace_comment {\ font-style:italic;\ color:#0088FF;\ }\ \ .ace-cobalt .ace_variable {\ color:#CCCCCC;\ }\ \ .ace-cobalt .ace_variable.ace_language {\ color:#FF80E1;\ }\ \ .ace-cobalt .ace_meta.ace_tag {\ color:#9EFFFF;\ }\ \ .ace-cobalt .ace_markup.ace_underline {\ text-decoration:underline;\ }\ \ .ace-cobalt .ace_markup.ace_heading {\ color:#C8E4FD;\ background-color:#001221;\ }\ \ .ace-cobalt .ace_markup.ace_list {\ background-color:#130D26;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * 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 ***** */ define('ace/mode/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/diff_highlight_rules', 'ace/mode/folding/diff'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HighlightRules = require("./diff_highlight_rules").DiffHighlightRules; var FoldMode = require("./folding/diff").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new HighlightRules().getRules(), "i"); this.foldingRules = new FoldMode(["diff", "index", "\\+{3}", "@@|\\*{5}"], "i"); }; oop.inherits(Mode, TextMode); (function() { }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/diff_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DiffHighlightRules = function() { // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [{ "regex": "^(?:\\*{15}|={67}|-{3}|\\+{3})$", "token": "punctuation.definition.separator.diff", "name": "keyword" }, { //diff.range.unified "regex": "^(@@)(\\s*.+?\\s*)(@@)(.*)$", "token": [ "constant", "constant.numeric", "constant", "comment.doc.tag" ] }, { //diff.range.normal "regex": "^(\\d+)([,\\d]+)(a|d|c)(\\d+)([,\\d]+)(.*)$", "token": [ "constant.numeric", "punctuation.definition.range.diff", "constant.function", "constant.numeric", "punctuation.definition.range.diff", "invalid" ], "name": "meta." }, { "regex": "^(?:(\\-{3}|\\+{3}|\\*{3})( .+))$", "token": [ "constant.numeric", "meta.tag" ] }, { // added "regex": "^([!+>])(.*?)(\\s*)$", "token": [ "support.constant", "text", "invalid" ], }, { // removed "regex": "^([<\\-])(.*?)(\\s*)$", "token": [ "support.function", "string", "invalid" ], }, { "regex": "^(diff)(\\s+--\\w+)?(.+?)( .+)?$", "token": ["variable", "variable", "keyword", "variable"] }, { "regex": "^Index.+$", "token": "variable" }, { "regex": "^(.*?)(\\s*)$", "token": ["invisible", "invalid"] } ] }; }; oop.inherits(DiffHighlightRules, TextHighlightRules); exports.DiffHighlightRules = DiffHighlightRules; }); define('ace/mode/folding/diff', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function(levels, flag) { this.regExpList = levels; this.flag = flag; this.foldingStartMarker = RegExp("^(" + levels.join("|") + ")", this.flag); }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var start = {row: row, column: line.length}; var regList = this.regExpList; for (var i = 1; i <= regList.length; i++) { var re = RegExp("^(" + regList.slice(0, i).join("|") + ")", this.flag); if (re.test(line)) break; } for (var l = session.getLength(); ++row < l; ) { line = session.getLine(row); if (re.test(line)) break } if (row == start.row + 1) return; return Range.fromPoints(start, {row: row - 1, column: line.length}); }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ /** * Define a module along with a payload * @param module a name for the payload * @param payload a function to call with (require, exports, module) params */ (function() { var ACE_NAMESPACE = ""; var global = (function() { return this; })(); var _define = function(module, deps, payload) { if (typeof module !== 'string') { if (_define.original) _define.original.apply(window, arguments); else { console.error('dropping module because define wasn\'t a string.'); console.trace(); } return; } if (arguments.length == 2) payload = deps; if (!_define.modules) _define.modules = {}; _define.modules[module] = payload; }; var _require = function(parentId, module, callback) { if (Object.prototype.toString.call(module) === "[object Array]") { var params = []; for (var i = 0, l = module.length; i < l; ++i) { var dep = lookup(parentId, module[i]); if (!dep && _require.original) return _require.original.apply(window, arguments); params.push(dep); } if (callback) { callback.apply(null, params); } } else if (typeof module === 'string') { var payload = lookup(parentId, module); if (!payload && _require.original) return _require.original.apply(window, arguments); if (callback) { callback(); } return payload; } else { if (_require.original) return _require.original.apply(window, arguments); } }; var normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = base + "/" + moduleName; while(moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; var lookup = function(parentId, moduleName) { moduleName = normalizeModule(parentId, moduleName); var module = _define.modules[moduleName]; if (!module) { return null; } if (typeof module === 'function') { var exports = {}; var mod = { id: moduleName, uri: '', exports: exports, packaged: true }; var req = function(module, callback) { return _require(moduleName, module, callback); }; var returnValue = module(req, exports, mod); exports = returnValue || mod.exports; // cache the resulting module object for next time _define.modules[moduleName] = exports; return exports; } return module; }; function exportAce(ns) { if (typeof requirejs !== "undefined") { var define = global.define; global.define = function(id, deps, callback) { if (typeof callback !== "function") return define.apply(this, arguments); return define(id, deps, function(require, exports, module) { if (deps[2] == "module") module.packaged = true; return callback.apply(this, arguments); }); }; global.define.packaged = true; return; } var require = function(module, callback) { return _require("", module, callback); }; require.packaged = true; var root = global; if (ns) { if (!global[ns]) global[ns] = {}; root = global[ns]; } if (root.define) _define.original = root.define; root.define = _define; if (root.require) _require.original = root.require; root.require = require; } exportAce(ACE_NAMESPACE); })(); /** * class Ace * * The main class required to set up an Ace instance in the browser. * * **/ define('ace/ace', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers', 'ace/lib/dom', 'ace/lib/event', 'ace/editor', 'ace/edit_session', 'ace/undomanager', 'ace/virtual_renderer', 'ace/multi_select', 'ace/worker/worker_client', 'ace/keyboard/hash_handler', 'ace/keyboard/state_handler', 'ace/placeholder', 'ace/config', 'ace/theme/textmate'], function(require, exports, module) { require("./lib/fixoldbrowsers"); var Dom = require("./lib/dom"); var Event = require("./lib/event"); var Editor = require("./editor").Editor; var EditSession = require("./edit_session").EditSession; var UndoManager = require("./undomanager").UndoManager; var Renderer = require("./virtual_renderer").VirtualRenderer; var MultiSelect = require("./multi_select").MultiSelect; // The following require()s are for inclusion in the built ace file require("./worker/worker_client"); require("./keyboard/hash_handler"); require("./keyboard/state_handler"); require("./placeholder"); exports.config = require("./config"); exports.edit = function(el) { if (typeof(el) == "string") { el = document.getElementById(el); } if (el.env && el.env.editor instanceof Editor) return el.env.editor; var doc = new EditSession(Dom.getInnerText(el)); doc.setUndoManager(new UndoManager()); el.innerHTML = ''; var editor = new Editor(new Renderer(el, require("./theme/textmate"))); new MultiSelect(editor); editor.setSession(doc); var env = {}; env.document = doc; env.editor = editor; editor.resize(); Event.addListener(window, "resize", function() { editor.resize(); }); el.env = env; // Store env on editor such that it can be accessed later on from // the returned object. editor.env = env; return editor; }; }); // vim:set ts=4 sts=4 sw=4 st: // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { require("./regexp"); require("./es5-shim"); }); define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { //--------------------------------- // Private variables //--------------------------------- var real = { exec: RegExp.prototype.exec, test: RegExp.prototype.test, match: String.prototype.match, replace: String.prototype.replace, split: String.prototype.split }, compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups compliantLastIndexIncrement = function () { var x = /^/g; real.test.call(x, ""); return !x.lastIndex; }(); if (compliantLastIndexIncrement && compliantExecNpcg) return; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match = real.exec.apply(this, arguments), name, r2; if ( typeof(str) == 'string' && match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match real.replace.call(str.slice(match.index), r2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undefined) match[i] = undefined; } }); } // Attach named capture properties if (this._xregexp && this._xregexp.captureNames) { for (var i = 1; i < match.length; i++) { name = this._xregexp.captureNames[i - 1]; if (name) match[name] = match[i]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } return match; }; // Don't override `test` if it won't change anything if (!compliantLastIndexIncrement) { // Fix browser bug in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the overriden // `exec` would take care of the `lastIndex` fix var match = real.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; return !!match; }; } //--------------------------------- // Private helper functions //--------------------------------- function getNativeFlags (regex) { return (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "") + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 (regex.sticky ? "y" : ""); }; function indexOf (array, item, from) { if (Array.prototype.indexOf) // Use the native array method if available return array.indexOf(item, from); for (var i = from || 0; i < array.length; i++) { if (array[i] === item) return i; } return -1; }; }); // vim: ts=4 sts=4 sw=4 expandtab // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA // -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA // -- bryanforbes Bryan Forbes XXX TODO License or CLA // -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence // -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License // -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License // -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) // -- iwyg XXX TODO License or CLA // -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License // -- xavierm02 Montillet Xavier XXX TODO License or CLA // -- Raynos Raynos XXX TODO License or CLA // -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License // -- rwldrn Rick Waldron Copyright (C) 2011 MIT License // -- lexer Alexey Zakharov XXX TODO License or CLA /*! Copyright (c) 2009, 280 North Inc. http://280north.com/ MIT License. http://github.com/280north/narwhal/blob/master/README.md */ define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * * @module */ /*whatsupdoc*/ // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (typeof target != "function") throw new TypeError(); // TODO message // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (result !== null && Object(result) === result) return result; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(slice.call(arguments)) ); } }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; } // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); // If JS engine supports accessors creating shortcuts. var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } // // Array // ===== // // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray if (!Array.isArray) { Array.isArray = function isArray(obj) { return toString(obj) == "[object Array]"; }; } // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var self = toObject(this), thisp = arguments[1], i = 0, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object context fun.call(thisp, self[i], i, self); } i++; } }; } // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var self = toObject(this), length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, self); } return result; }; } // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, result = [], thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) result.push(self[i]); } return result; }; } // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, self)) return false; } return true; }; } // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var self = toObject(this), length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, self)) return true; } return false; }; } // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value and an empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) throw new TypeError(); // TODO message } while (true); } for (; i < length; i++) { if (i in self) result = fun.call(void 0, result, self[i], i, self); } return result; }; } // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var self = toObject(this), length = self.length >>> 0; // If no callback function or if callback is not a callable function if (toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } // no value to return if no initial value, empty array if (!length && arguments.length == 1) throw new TypeError(); // TODO message var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) throw new TypeError(); // TODO message } while (true); } do { if (i in this) result = fun.call(void 0, result, self[i], i, self); } while (i--); return result; }; } // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = 0; if (arguments.length > 1) i = toInteger(arguments[1]); // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = toObject(this), length = self.length >>> 0; if (!length) return -1; var i = length - 1; if (arguments.length > 1) i = Math.min(i, toInteger(arguments[1])); // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) return i; } return -1; }; } // // Object // ====== // // ES5 15.2.3.2 // http://es5.github.com/#x15.2.3.2 if (!Object.getPrototypeOf) { // https://github.com/kriskowal/es5-shim/issues#issue/2 // http://ejohn.org/blog/objectgetprototypeof/ // recommended by fschaefer on github Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } // ES5 15.2.3.3 // http://es5.github.com/#x15.2.3.3 if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); // If object does not owns property return undefined immediately. if (!owns(object, property)) return; var descriptor, getter, setter; // If object has a property then it's for sure both `enumerable` and // `configurable`. descriptor = { enumerable: true, configurable: true }; // If JS engine supports accessor properties then property may be a // getter or setter. if (supportsAccessors) { // Unfortunately `__lookupGetter__` will return a getter even // if object has own non getter property along with a same named // inherited getter. To avoid misbehavior we temporary remove // `__proto__` so that `__lookupGetter__` will return getter only // if it's owned by an object. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); // Once we have getter and setter we can put values back. object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; // If it was accessor property we're done and return here // in order to avoid adding `value` to the descriptor. return descriptor; } } // If we got this far we know that object has an own property that is // not an accessor so we set it as a value and return descriptor. descriptor.value = object[property]; return descriptor; }; } // ES5 15.2.3.4 // http://es5.github.com/#x15.2.3.4 if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } // ES5 15.2.3.5 // http://es5.github.com/#x15.2.3.5 if (!Object.create) { Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = { "__proto__": null }; } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); // IE has no built-in implementation of `Object.getPrototypeOf` // neither `__proto__`, but this manually setting `__proto__` will // guarantee that `Object.getPrototypeOf` will work as expected with // objects created using `Object.create` object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } // ES5 15.2.3.6 // http://es5.github.com/#x15.2.3.6 // Patch for WebKit and IE8 standard mode // Designed by hax <hax.github.com> // related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 // IE8 Reference: // http://msdn.microsoft.com/en-us/library/dd282900.aspx // http://msdn.microsoft.com/en-us/library/dd229916.aspx // WebKit Bugs: // https://bugs.webkit.org/show_bug.cgi?id=36423 function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { // returns falsy } } // check whether defineProperty works if it's given. Otherwise, // shim partially. if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); // make a valiant attempt to use the real defineProperty // for I8's DOM elements. if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { // try the shim if the real one doesn't work } } // If it's a data property. if (owns(descriptor, "value")) { // fail silently if "writable", "enumerable", or "configurable" // are requested but not supported /* // alternate approach: if ( // can't implement these features; allow false but not true !(owns(descriptor, "writable") ? descriptor.writable : true) || !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || !(owns(descriptor, "configurable") ? descriptor.configurable : true) ) throw new RangeError( "This implementation of Object.defineProperty does not " + "support configurable, enumerable, or writable." ); */ if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { // As accessors are supported only on engines implementing // `__proto__` we can safely override `__proto__` while defining // a property to make sure that we don't hit an inherited // accessor. var prototype = object.__proto__; object.__proto__ = prototypeOfObject; // Deleting a property anyway since getter / setter may be // defined on object itself. delete object[property]; object[property] = descriptor.value; // Setting original `__proto__` back now. object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); // If we got that far then getters and setters can be defined !! if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } // ES5 15.2.3.7 // http://es5.github.com/#x15.2.3.7 if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } // ES5 15.2.3.8 // http://es5.github.com/#x15.2.3.8 if (!Object.seal) { Object.seal = function seal(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.9 // http://es5.github.com/#x15.2.3.9 if (!Object.freeze) { Object.freeze = function freeze(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // detect a Rhino bug and patch it try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } // ES5 15.2.3.10 // http://es5.github.com/#x15.2.3.10 if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { // this is misleading and breaks feature-detection, but // allows "securable" code to "gracefully" degrade to working // but insecure code. return object; }; } // ES5 15.2.3.11 // http://es5.github.com/#x15.2.3.11 if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } // ES5 15.2.3.12 // http://es5.github.com/#x15.2.3.12 if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } // ES5 15.2.3.13 // http://es5.github.com/#x15.2.3.13 if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { // 1. If Type(O) is not Object throw a TypeError exception. if (Object(object) === object) { throw new TypeError(); // TODO message } // 2. Return the Boolean value of the [[Extensible]] internal property of O. var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 if (!Object.keys) { // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) hasDontEnumBug = false; Object.keys = function keys(object) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError("Object.keys called on a non-object"); var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { Date.prototype.toISOString = function toISOString() { var result, length, value, year; if (!isFinite(this)) throw new RangeError; // the date time string format is specified in 15.9.1.15. result = [this.getUTCMonth() + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = this.getUTCFullYear(); year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two digits. if (value < 10) result[length] = "0" + value; } // pad milliseconds to have three digits. return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; } } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). if (!Date.prototype.toJSON) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be ToPrimitive(O, hint Number). // 3. If tv is a Number and is not finite, return null. // XXX // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof this.toISOString != "function") throw new TypeError(); // TODO message // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return this.toISOString(); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function(NativeDate) { // Date.length === 7 var Date = function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length == 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); }; // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:\\.(\\d{3}))?" + // milliseconds capture ")?" + "(?:" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) Date[key] = NativeDate[key]; // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { match.shift(); // kill match[0], the full match // parse months, days, hours, minutes, seconds, and milliseconds for (var i = 1; i < 7; i++) { // provide default values if necessary match[i] = +(match[i] || (i < 3 ? 1 : 0)); // match[1] is the month. Months are 0-11 in JavaScript // `Date` objects, but 1-12 in ISO notation, so we // decrement. if (i == 1) match[i]--; } // parse the UTC offset component var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); // compute the explicit time zone offset if specified var offset = 0; if (sign) { // detect invalid offsets and return early if (hourOffset > 23 || minuteOffset > 59) return NaN; // express the provided time zone offset in minutes. The offset is // negative for time zones west of UTC; positive otherwise. offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); } // Date.UTC for years between 0 and 99 converts year to 1900 + year // The Gregorian calendar has a 400-year cycle, so // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years var year = +match[0]; if (0 <= year && year <= 99) { match[0] = year + 400; return NativeDate.UTC.apply(this, match) + offset - 12622780800000; } // compute a new UTC date value, accounting for the optional offset return NativeDate.UTC.apply(this, match) + offset; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // // String // ====== // // ES5 15.5.4.20 // http://es5.github.com/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer var toInteger = function (n) { n = +n; if (n !== n) // isNaN n = 0; else if (n !== 0 && n !== (1/0) && n !== -(1/0)) n = (n > 0 || -1) * Math.floor(Math.abs(n)); return n; }; var prepareString = "a"[0] != "a", // ES5 9.9 // http://es5.github.com/#x9.9 toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError(); // TODO message } // If the implementation doesn't support by-index access of // string characters (ex. IE < 7), split the string if (prepareString && typeof o == "string" && o) { return o.split(""); } return Object(o); }; }); define('ace/lib/dom', ['require', 'exports', 'module' ], function(require, exports, module) { var XHTML_NS = "http://www.w3.org/1999/xhtml"; exports.createElement = function(tag, ns) { return document.createElementNS ? document.createElementNS(ns || XHTML_NS, tag) : document.createElement(tag); }; exports.setText = function(elem, text) { if (elem.innerText !== undefined) { elem.innerText = text; } if (elem.textContent !== undefined) { elem.textContent = text; } }; exports.hasCssClass = function(el, name) { var classes = el.className.split(/\s+/g); return classes.indexOf(name) !== -1; }; exports.addCssClass = function(el, name) { if (!exports.hasCssClass(el, name)) { el.className += " " + name; } }; exports.removeCssClass = function(el, name) { var classes = el.className.split(/\s+/g); while (true) { var index = classes.indexOf(name); if (index == -1) { break; } classes.splice(index, 1); } el.className = classes.join(" "); }; exports.toggleCssClass = function(el, name) { var classes = el.className.split(/\s+/g), add = true; while (true) { var index = classes.indexOf(name); if (index == -1) { break; } add = false; classes.splice(index, 1); } if(add) classes.push(name); el.className = classes.join(" "); return add; }; exports.setCssClass = function(node, className, include) { if (include) { exports.addCssClass(node, className); } else { exports.removeCssClass(node, className); } }; exports.hasCssString = function(id, doc) { var index = 0, sheets; doc = doc || document; if (doc.createStyleSheet && (sheets = doc.styleSheets)) { while (index < sheets.length) if (sheets[index++].owningElement.id === id) return true; } else if ((sheets = doc.getElementsByTagName("style"))) { while (index < sheets.length) if (sheets[index++].id === id) return true; } return false; }; exports.importCssString = function importCssString(cssText, id, doc) { doc = doc || document; // If style is already imported return immediately. if (id && exports.hasCssString(id, doc)) return null; var style; if (doc.createStyleSheet) { style = doc.createStyleSheet(); style.cssText = cssText; if (id) style.owningElement.id = id; } else { style = doc.createElementNS ? doc.createElementNS(XHTML_NS, "style") : doc.createElement("style"); style.appendChild(doc.createTextNode(cssText)); if (id) style.id = id; var head = doc.getElementsByTagName("head")[0] || doc.documentElement; head.appendChild(style); } }; exports.importCssStylsheet = function(uri, doc) { if (doc.createStyleSheet) { doc.createStyleSheet(uri); } else { var link = exports.createElement('link'); link.rel = 'stylesheet'; link.href = uri; var head = doc.getElementsByTagName("head")[0] || doc.documentElement; head.appendChild(link); } }; exports.getInnerWidth = function(element) { return ( parseInt(exports.computedStyle(element, "paddingLeft"), 10) + parseInt(exports.computedStyle(element, "paddingRight"), 10) + element.clientWidth ); }; exports.getInnerHeight = function(element) { return ( parseInt(exports.computedStyle(element, "paddingTop"), 10) + parseInt(exports.computedStyle(element, "paddingBottom"), 10) + element.clientHeight ); }; if (window.pageYOffset !== undefined) { exports.getPageScrollTop = function() { return window.pageYOffset; }; exports.getPageScrollLeft = function() { return window.pageXOffset; }; } else { exports.getPageScrollTop = function() { return document.body.scrollTop; }; exports.getPageScrollLeft = function() { return document.body.scrollLeft; }; } if (window.getComputedStyle) exports.computedStyle = function(element, style) { if (style) return (window.getComputedStyle(element, "") || {})[style] || ""; return window.getComputedStyle(element, "") || {}; }; else exports.computedStyle = function(element, style) { if (style) return element.currentStyle[style]; return element.currentStyle; }; exports.scrollbarWidth = function(document) { var inner = exports.createElement("p"); inner.style.width = "100%"; inner.style.minWidth = "0px"; inner.style.height = "200px"; var outer = exports.createElement("div"); var style = outer.style; style.position = "absolute"; style.left = "-10000px"; style.overflow = "hidden"; style.width = "200px"; style.minWidth = "0px"; style.height = "150px"; outer.appendChild(inner); var body = document.body || document.documentElement; body.appendChild(outer); var noScrollbar = inner.offsetWidth; style.overflow = "scroll"; var withScrollbar = inner.offsetWidth; if (noScrollbar == withScrollbar) { withScrollbar = outer.clientWidth; } body.removeChild(outer); return noScrollbar-withScrollbar; }; exports.setInnerHtml = function(el, innerHtml) { var element = el.cloneNode(false);//document.createElement("div"); element.innerHTML = innerHtml; el.parentNode.replaceChild(element, el); return element; }; exports.setInnerText = function(el, innerText) { var document = el.ownerDocument; if (document.body && "textContent" in document.body) el.textContent = innerText; else el.innerText = innerText; }; exports.getInnerText = function(el) { var document = el.ownerDocument; if (document.body && "textContent" in document.body) return el.textContent; else return el.innerText || el.textContent || ""; }; exports.getParentWindow = function(document) { return document.defaultView || document.parentWindow; }; }); define('ace/lib/event', ['require', 'exports', 'module' , 'ace/lib/keys', 'ace/lib/useragent', 'ace/lib/dom'], function(require, exports, module) { var keys = require("./keys"); var useragent = require("./useragent"); var dom = require("./dom"); exports.addListener = function(elem, type, callback) { if (elem.addEventListener) { return elem.addEventListener(type, callback, false); } if (elem.attachEvent) { var wrapper = function() { callback(window.event); }; callback._wrapper = wrapper; elem.attachEvent("on" + type, wrapper); } }; exports.removeListener = function(elem, type, callback) { if (elem.removeEventListener) { return elem.removeEventListener(type, callback, false); } if (elem.detachEvent) { elem.detachEvent("on" + type, callback._wrapper || callback); } }; exports.stopEvent = function(e) { exports.stopPropagation(e); exports.preventDefault(e); return false; }; exports.stopPropagation = function(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; }; exports.preventDefault = function(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; }; exports.getButton = function(e) { if (e.type == "dblclick") return 0; else if (e.type == "contextmenu") return 2; // DOM Event if (e.preventDefault) { return e.button; } // old IE else { return {1:0, 2:2, 4:1}[e.button]; } }; if (document.documentElement.setCapture) { exports.capture = function(el, eventHandler, releaseCaptureHandler) { function onMouseMove(e) { eventHandler(e); return exports.stopPropagation(e); } var called = false; function onReleaseCapture(e) { eventHandler(e); if (!called) { called = true; releaseCaptureHandler(e); } exports.removeListener(el, "mousemove", eventHandler); exports.removeListener(el, "mouseup", onReleaseCapture); exports.removeListener(el, "losecapture", onReleaseCapture); el.releaseCapture(); } exports.addListener(el, "mousemove", eventHandler); exports.addListener(el, "mouseup", onReleaseCapture); exports.addListener(el, "losecapture", onReleaseCapture); el.setCapture(); }; } else { exports.capture = function(el, eventHandler, releaseCaptureHandler) { function onMouseMove(e) { eventHandler(e); e.stopPropagation(); } function onMouseUp(e) { eventHandler && eventHandler(e); releaseCaptureHandler && releaseCaptureHandler(e); document.removeEventListener("mousemove", onMouseMove, true); document.removeEventListener("mouseup", onMouseUp, true); e.stopPropagation(); } document.addEventListener("mousemove", onMouseMove, true); document.addEventListener("mouseup", onMouseUp, true); }; } exports.addMouseWheelListener = function(el, callback) { var factor = 8; var listener = function(e) { if (e.wheelDelta !== undefined) { if (e.wheelDeltaX !== undefined) { e.wheelX = -e.wheelDeltaX / factor; e.wheelY = -e.wheelDeltaY / factor; } else { e.wheelX = 0; e.wheelY = -e.wheelDelta / factor; } } else { if (e.axis && e.axis == e.HORIZONTAL_AXIS) { e.wheelX = (e.detail || 0) * 5; e.wheelY = 0; } else { e.wheelX = 0; e.wheelY = (e.detail || 0) * 5; } } callback(e); }; exports.addListener(el, "DOMMouseScroll", listener); exports.addListener(el, "mousewheel", listener); }; exports.addMultiMouseDownListener = function(el, timeouts, eventHandler, callbackName) { var clicks = 0; var startX, startY, timer; var eventNames = { 2: "dblclick", 3: "tripleclick", 4: "quadclick" }; var listener = function(e) { if (exports.getButton(e) != 0) { clicks = 0; } else { var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5; if (!timer || isNewClick) clicks = 0; clicks += 1; if (timer) clearTimeout(timer) timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); } if (clicks == 1) { startX = e.clientX; startY = e.clientY; } eventHandler[callbackName]("mousedown", e); if (clicks > 4) clicks = 0; else if (clicks > 1) return eventHandler[callbackName](eventNames[clicks], e); }; exports.addListener(el, "mousedown", listener); useragent.isOldIE && exports.addListener(el, "dblclick", listener); }; function normalizeCommandKeys(callback, e, keyCode) { var hashId = 0; if (useragent.isOpera && useragent.isMac) { hashId = 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0); } else { hashId = 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0); } if (keyCode in keys.MODIFIER_KEYS) { switch (keys.MODIFIER_KEYS[keyCode]) { case "Alt": hashId = 2; break; case "Shift": hashId = 4; break; case "Ctrl": hashId = 1; break; default: hashId = 8; break; } keyCode = 0; } if (hashId & 8 && (keyCode == 91 || keyCode == 93)) { keyCode = 0; } // If there is no hashID and the keyCode is not a function key, then // we don't call the callback as we don't handle a command key here // (it's a normal key/character input). if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) { return false; } return callback(e, hashId, keyCode); } exports.addCommandKeyListener = function(el, callback) { var addListener = exports.addListener; if (useragent.isOldGecko || useragent.isOpera) { // Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown // event if the user pressed the key for a longer time. Instead, the // keydown event was fired once and later on only the keypress event. // To emulate the 'right' keydown behavior, the keyCode of the initial // keyDown event is stored and in the following keypress events the // stores keyCode is used to emulate a keyDown event. var lastKeyDownKeyCode = null; addListener(el, "keydown", function(e) { lastKeyDownKeyCode = e.keyCode; }); addListener(el, "keypress", function(e) { return normalizeCommandKeys(callback, e, lastKeyDownKeyCode); }); } else { var lastDown = null; addListener(el, "keydown", function(e) { lastDown = e.keyIdentifier || e.keyCode; return normalizeCommandKeys(callback, e, e.keyCode); }); } }; if (window.postMessage) { var postMessageId = 1; exports.nextTick = function(callback, win) { win = win || window; var messageName = "zero-timeout-message-" + postMessageId; exports.addListener(win, "message", function listener(e) { if (e.data == messageName) { exports.stopPropagation(e); exports.removeListener(win, "message", listener); callback(); } }); win.postMessage(messageName, "*"); }; } else { exports.nextTick = function(callback, win) { win = win || window; window.setTimeout(callback, 0); }; } }); // Most of the following code is taken from SproutCore with a few changes. define('ace/lib/keys', ['require', 'exports', 'module' , 'ace/lib/oop'], function(require, exports, module) { var oop = require("./oop"); var Keys = (function() { var ret = { MODIFIER_KEYS: { 16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta' }, KEY_MODS: { "ctrl": 1, "alt": 2, "option" : 2, "shift": 4, "meta": 8, "command": 8 }, FUNCTION_KEYS : { 8 : "Backspace", 9 : "Tab", 13 : "Return", 19 : "Pause", 27 : "Esc", 32 : "Space", 33 : "PageUp", 34 : "PageDown", 35 : "End", 36 : "Home", 37 : "Left", 38 : "Up", 39 : "Right", 40 : "Down", 44 : "Print", 45 : "Insert", 46 : "Delete", 96 : "Numpad0", 97 : "Numpad1", 98 : "Numpad2", 99 : "Numpad3", 100: "Numpad4", 101: "Numpad5", 102: "Numpad6", 103: "Numpad7", 104: "Numpad8", 105: "Numpad9", 112: "F1", 113: "F2", 114: "F3", 115: "F4", 116: "F5", 117: "F6", 118: "F7", 119: "F8", 120: "F9", 121: "F10", 122: "F11", 123: "F12", 144: "Numlock", 145: "Scrolllock" }, PRINTABLE_KEYS: { 32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', 54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a', 66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h', 73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o', 80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v', 87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.', 188: ',', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\', 221: ']', 222: '\'' } }; // A reverse map of FUNCTION_KEYS for (var i in ret.FUNCTION_KEYS) { var name = ret.FUNCTION_KEYS[i].toUpperCase(); ret[name] = parseInt(i, 10); } // Add the MODIFIER_KEYS, FUNCTION_KEYS and PRINTABLE_KEYS to the KEY // variables as well. oop.mixin(ret, ret.MODIFIER_KEYS); oop.mixin(ret, ret.PRINTABLE_KEYS); oop.mixin(ret, ret.FUNCTION_KEYS); return ret; })(); oop.mixin(exports, Keys); exports.keyCodeToString = function(keyCode) { return (Keys[keyCode] || String.fromCharCode(keyCode)).toLowerCase(); } }); define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) { exports.inherits = (function() { var tempCtor = function() {}; return function(ctor, superCtor) { tempCtor.prototype = superCtor.prototype; ctor.super_ = superCtor.prototype; ctor.prototype = new tempCtor(); ctor.prototype.constructor = ctor; }; }()); exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); define('ace/lib/useragent', ['require', 'exports', 'module' ], function(require, exports, module) { var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); var ua = navigator.userAgent; // Is the user using a browser that identifies itself as Windows exports.isWin = (os == "win"); // Is the user using a browser that identifies itself as Mac OS exports.isMac = (os == "mac"); // Is the user using a browser that identifies itself as Linux exports.isLinux = (os == "linux"); exports.isIE = navigator.appName == "Microsoft Internet Explorer" && parseFloat(navigator.userAgent.match(/MSIE ([0-9]+[\.0-9]+)/)[1]); exports.isOldIE = exports.isIE && exports.isIE < 9; // Is this Firefox or related? exports.isGecko = exports.isMozilla = window.controllers && window.navigator.product === "Gecko"; // oldGecko == rev < 2.0 exports.isOldGecko = exports.isGecko && parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1], 10) < 4; // Is this Opera exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; // Is the user using a browser that identifies itself as WebKit exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined; exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined; exports.isAIR = ua.indexOf("AdobeAIR") >= 0; exports.isIPad = ua.indexOf("iPad") >= 0; exports.isTouchPad = ua.indexOf("TouchPad") >= 0; exports.OS = { LINUX: "LINUX", MAC: "MAC", WINDOWS: "WINDOWS" }; exports.getOS = function() { if (exports.isMac) { return exports.OS.MAC; } else if (exports.isLinux) { return exports.OS.LINUX; } else { return exports.OS.WINDOWS; } }; }); define('ace/editor', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers', 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/useragent', 'ace/keyboard/textinput', 'ace/mouse/mouse_handler', 'ace/mouse/fold_handler', 'ace/keyboard/keybinding', 'ace/edit_session', 'ace/search', 'ace/range', 'ace/lib/event_emitter', 'ace/commands/command_manager', 'ace/commands/default_commands'], function(require, exports, module) { require("./lib/fixoldbrowsers"); var oop = require("./lib/oop"); var lang = require("./lib/lang"); var useragent = require("./lib/useragent"); var TextInput = require("./keyboard/textinput").TextInput; var MouseHandler = require("./mouse/mouse_handler").MouseHandler; var FoldHandler = require("./mouse/fold_handler").FoldHandler; //var TouchHandler = require("./touch_handler").TouchHandler; var KeyBinding = require("./keyboard/keybinding").KeyBinding; var EditSession = require("./edit_session").EditSession; var Search = require("./search").Search; var Range = require("./range").Range; var EventEmitter = require("./lib/event_emitter").EventEmitter; var CommandManager = require("./commands/command_manager").CommandManager; var defaultCommands = require("./commands/default_commands").commands; /** * new Editor(renderer, session) * - renderer (VirtualRenderer): Associated `VirtualRenderer` that draws everything * - session (EditSession): The `EditSession` to refer to * * Creates a new `Editor` object. * **/ var Editor = function(renderer, session) { var container = renderer.getContainerElement(); this.container = container; this.renderer = renderer; this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands); this.textInput = new TextInput(renderer.getTextAreaContainer(), this); this.renderer.textarea = this.textInput.getElement(); this.keyBinding = new KeyBinding(this); // TODO detect touch event support if (useragent.isIPad) { //this.$mouseHandler = new TouchHandler(this); } else { this.$mouseHandler = new MouseHandler(this); new FoldHandler(this); } this.$blockScrolling = 0; this.$search = new Search().set({ wrap: true }); this.setSession(session || new EditSession("")); }; (function(){ oop.implement(this, EventEmitter); this.setKeyboardHandler = function(keyboardHandler) { this.keyBinding.setKeyboardHandler(keyboardHandler); }; this.getKeyboardHandler = function() { return this.keyBinding.getKeyboardHandler(); }; this.setSession = function(session) { if (this.session == session) return; if (this.session) { var oldSession = this.session; this.session.removeEventListener("change", this.$onDocumentChange); this.session.removeEventListener("changeMode", this.$onChangeMode); this.session.removeEventListener("tokenizerUpdate", this.$onTokenizerUpdate); this.session.removeEventListener("changeTabSize", this.$onChangeTabSize); this.session.removeEventListener("changeWrapLimit", this.$onChangeWrapLimit); this.session.removeEventListener("changeWrapMode", this.$onChangeWrapMode); this.session.removeEventListener("onChangeFold", this.$onChangeFold); this.session.removeEventListener("changeFrontMarker", this.$onChangeFrontMarker); this.session.removeEventListener("changeBackMarker", this.$onChangeBackMarker); this.session.removeEventListener("changeBreakpoint", this.$onChangeBreakpoint); this.session.removeEventListener("changeAnnotation", this.$onChangeAnnotation); this.session.removeEventListener("changeOverwrite", this.$onCursorChange); this.session.removeEventListener("changeScrollTop", this.$onScrollTopChange); this.session.removeEventListener("changeLeftTop", this.$onScrollLeftChange); var selection = this.session.getSelection(); selection.removeEventListener("changeCursor", this.$onCursorChange); selection.removeEventListener("changeSelection", this.$onSelectionChange); } this.session = session; this.$onDocumentChange = this.onDocumentChange.bind(this); session.addEventListener("change", this.$onDocumentChange); this.renderer.setSession(session); this.$onChangeMode = this.onChangeMode.bind(this); session.addEventListener("changeMode", this.$onChangeMode); this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this); session.addEventListener("tokenizerUpdate", this.$onTokenizerUpdate); this.$onChangeTabSize = this.renderer.updateText.bind(this.renderer); session.addEventListener("changeTabSize", this.$onChangeTabSize); this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this); session.addEventListener("changeWrapLimit", this.$onChangeWrapLimit); this.$onChangeWrapMode = this.onChangeWrapMode.bind(this); session.addEventListener("changeWrapMode", this.$onChangeWrapMode); this.$onChangeFold = this.onChangeFold.bind(this); session.addEventListener("changeFold", this.$onChangeFold); this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this); this.session.addEventListener("changeFrontMarker", this.$onChangeFrontMarker); this.$onChangeBackMarker = this.onChangeBackMarker.bind(this); this.session.addEventListener("changeBackMarker", this.$onChangeBackMarker); this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this); this.session.addEventListener("changeBreakpoint", this.$onChangeBreakpoint); this.$onChangeAnnotation = this.onChangeAnnotation.bind(this); this.session.addEventListener("changeAnnotation", this.$onChangeAnnotation); this.$onCursorChange = this.onCursorChange.bind(this); this.session.addEventListener("changeOverwrite", this.$onCursorChange); this.$onScrollTopChange = this.onScrollTopChange.bind(this); this.session.addEventListener("changeScrollTop", this.$onScrollTopChange); this.$onScrollLeftChange = this.onScrollLeftChange.bind(this); this.session.addEventListener("changeScrollLeft", this.$onScrollLeftChange); this.selection = session.getSelection(); this.selection.addEventListener("changeCursor", this.$onCursorChange); this.$onSelectionChange = this.onSelectionChange.bind(this); this.selection.addEventListener("changeSelection", this.$onSelectionChange); this.onChangeMode(); this.$blockScrolling += 1; this.onCursorChange(); this.$blockScrolling -= 1; this.onScrollTopChange(); this.onScrollLeftChange(); this.onSelectionChange(); this.onChangeFrontMarker(); this.onChangeBackMarker(); this.onChangeBreakpoint(); this.onChangeAnnotation(); this.session.getUseWrapMode() && this.renderer.adjustWrapLimit(); this.renderer.updateFull(); this._emit("changeSession", { session: session, oldSession: oldSession }); }; this.getSession = function() { return this.session; }; this.setValue = function(val, cursorPos) { this.session.doc.setValue(val); if (!cursorPos) this.selectAll(); else if (cursorPos == 1) this.navigateFileEnd(); else if (cursorPos == -1) this.navigateFileStart(); return val; }; this.getValue = function() { return this.session.getValue(); }; this.getSelection = function() { return this.selection; }; this.resize = function(force) { this.renderer.onResize(force); }; this.setTheme = function(theme) { this.renderer.setTheme(theme); }; this.getTheme = function() { return this.renderer.getTheme(); }; this.setStyle = function(style) { this.renderer.setStyle(style); }; this.unsetStyle = function(style) { this.renderer.unsetStyle(style); }; this.setFontSize = function(size) { this.container.style.fontSize = size; this.renderer.updateFontSize(); }; this.$highlightBrackets = function() { if (this.session.$bracketHighlight) { this.session.removeMarker(this.session.$bracketHighlight); this.session.$bracketHighlight = null; } if (this.$highlightPending) { return; } // perform highlight async to not block the browser during navigation var self = this; this.$highlightPending = true; setTimeout(function() { self.$highlightPending = false; var pos = self.session.findMatchingBracket(self.getCursorPosition()); if (pos) { var range = new Range(pos.row, pos.column, pos.row, pos.column+1); self.session.$bracketHighlight = self.session.addMarker(range, "ace_bracket", "text"); } }, 10); }; this.focus = function() { // Safari needs the timeout // iOS and Firefox need it called immediately // to be on the save side we do both var _self = this; setTimeout(function() { _self.textInput.focus(); }); this.textInput.focus(); }; this.isFocused = function() { return this.textInput.isFocused(); }; this.blur = function() { this.textInput.blur(); }; this.onFocus = function() { if (this.$isFocused) return; this.$isFocused = true; this.renderer.showCursor(); this.renderer.visualizeFocus(); this._emit("focus"); }; this.onBlur = function() { if (!this.$isFocused) return; this.$isFocused = false; this.renderer.hideCursor(); this.renderer.visualizeBlur(); this._emit("blur"); }; this.$cursorChange = function() { this.renderer.updateCursor(); }; this.onDocumentChange = function(e) { var delta = e.data; var range = delta.range; var lastRow; if (range.start.row == range.end.row && delta.action != "insertLines" && delta.action != "removeLines") lastRow = range.end.row; else lastRow = Infinity; this.renderer.updateLines(range.start.row, lastRow); this._emit("change", e); // update cursor because tab characters can influence the cursor position this.$cursorChange(); }; this.onTokenizerUpdate = function(e) { var rows = e.data; this.renderer.updateLines(rows.first, rows.last); }; this.onScrollTopChange = function() { this.renderer.scrollToY(this.session.getScrollTop()); }; this.onScrollLeftChange = function() { this.renderer.scrollToX(this.session.getScrollLeft()); }; this.onCursorChange = function() { this.$cursorChange(); if (!this.$blockScrolling) { this.renderer.scrollCursorIntoView(); } this.$highlightBrackets(); this.$updateHighlightActiveLine(); }; this.$updateHighlightActiveLine = function() { var session = this.getSession(); if (session.$highlightLineMarker) session.removeMarker(session.$highlightLineMarker); session.$highlightLineMarker = null; if (this.$highlightActiveLine) { var cursor = this.getCursorPosition(); var foldLine = this.session.getFoldLine(cursor.row); if ((this.getSelectionStyle() != "line" || !this.selection.isMultiLine())) { var range; if (foldLine) { range = new Range(foldLine.start.row, 0, foldLine.end.row + 1, 0); } else { range = new Range(cursor.row, 0, cursor.row+1, 0); } session.$highlightLineMarker = session.addMarker(range, "ace_active_line", "background"); } } }; this.onSelectionChange = function(e) { var session = this.session; if (session.$selectionMarker) { session.removeMarker(session.$selectionMarker); } session.$selectionMarker = null; if (!this.selection.isEmpty()) { var range = this.selection.getRange(); var style = this.getSelectionStyle(); session.$selectionMarker = session.addMarker(range, "ace_selection", style); } else { this.$updateHighlightActiveLine(); } var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp() this.session.highlight(re); }; this.$getSelectionHighLightRegexp = function() { var session = this.session; var selection = this.getSelectionRange(); if (selection.isEmpty() || selection.isMultiLine()) return; var startOuter = selection.start.column - 1; var endOuter = selection.end.column + 1; var line = session.getLine(selection.start.row); var lineCols = line.length; var needle = line.substring(Math.max(startOuter, 0), Math.min(endOuter, lineCols)); // Make sure the outer characters are not part of the word. if ((startOuter >= 0 && /^[\w\d]/.test(needle)) || (endOuter <= lineCols && /[\w\d]$/.test(needle))) return; needle = line.substring(selection.start.column, selection.end.column); if (!/^[\w\d]+$/.test(needle)) return; var re = this.$search.$assembleRegExp({ wholeWord: true, caseSensitive: true, needle: needle }); return re; }; this.onChangeFrontMarker = function() { this.renderer.updateFrontMarkers(); }; this.onChangeBackMarker = function() { this.renderer.updateBackMarkers(); }; this.onChangeBreakpoint = function() { this.renderer.updateBreakpoints(); }; this.onChangeAnnotation = function() { this.renderer.setAnnotations(this.session.getAnnotations()); }; this.onChangeMode = function() { this.renderer.updateText(); }; this.onChangeWrapLimit = function() { this.renderer.updateFull(); }; this.onChangeWrapMode = function() { this.renderer.onResize(true); }; this.onChangeFold = function() { // Update the active line marker as due to folding changes the current // line range on the screen might have changed. this.$updateHighlightActiveLine(); // TODO: This might be too much updating. Okay for now. this.renderer.updateFull(); }; this.getCopyText = function() { var text = ""; if (!this.selection.isEmpty()) text = this.session.getTextRange(this.getSelectionRange()); this._emit("copy", text); return text; }; this.onCopy = function() { this.commands.exec("copy", this); }; this.onCut = function() { this.commands.exec("cut", this); }; this.onPaste = function(text) { this._emit("paste", text); this.insert(text); }; this.insert = function(text) { var session = this.session; var mode = session.getMode(); var cursor = this.getCursorPosition(); if (this.getBehavioursEnabled()) { // Get a transform if the current mode wants one. var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text); if (transform) text = transform.text; } text = text.replace("\t", this.session.getTabString()); // remove selected text if (!this.selection.isEmpty()) { cursor = this.session.remove(this.getSelectionRange()); this.clearSelection(); } else if (this.session.getOverwrite()) { var range = new Range.fromPoints(cursor, cursor); range.end.column += text.length; this.session.remove(range); } this.clearSelection(); var start = cursor.column; var lineState = session.getState(cursor.row); var shouldOutdent = mode.checkOutdent(lineState, session.getLine(cursor.row), text); var line = session.getLine(cursor.row); var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString()); var end = session.insert(cursor, text); if (transform && transform.selection) { if (transform.selection.length == 2) { // Transform relative to the current column this.selection.setSelectionRange( new Range(cursor.row, start + transform.selection[0], cursor.row, start + transform.selection[1])); } else { // Transform relative to the current row. this.selection.setSelectionRange( new Range(cursor.row + transform.selection[0], transform.selection[1], cursor.row + transform.selection[2], transform.selection[3])); } } var lineState = session.getState(cursor.row); // TODO disabled multiline auto indent // possibly doing the indent before inserting the text // if (cursor.row !== end.row) { if (session.getDocument().isNewLine(text)) { this.moveCursorTo(cursor.row+1, 0); var size = session.getTabSize(); var minIndent = Number.MAX_VALUE; for (var row = cursor.row + 1; row <= end.row; ++row) { var indent = 0; line = session.getLine(row); for (var i = 0; i < line.length; ++i) if (line.charAt(i) == '\t') indent += size; else if (line.charAt(i) == ' ') indent += 1; else break; if (/[^\s]/.test(line)) minIndent = Math.min(indent, minIndent); } for (var row = cursor.row + 1; row <= end.row; ++row) { var outdent = minIndent; line = session.getLine(row); for (var i = 0; i < line.length && outdent > 0; ++i) if (line.charAt(i) == '\t') outdent -= size; else if (line.charAt(i) == ' ') outdent -= 1; session.remove(new Range(row, 0, row, i)); } session.indentRows(cursor.row + 1, end.row, lineIndent); } if (shouldOutdent) mode.autoOutdent(lineState, session, cursor.row); }; this.onTextInput = function(text) { this.keyBinding.onTextInput(text); }; this.onCommandKey = function(e, hashId, keyCode) { this.keyBinding.onCommandKey(e, hashId, keyCode); }; this.setOverwrite = function(overwrite) { this.session.setOverwrite(overwrite); }; this.getOverwrite = function() { return this.session.getOverwrite(); }; this.toggleOverwrite = function() { this.session.toggleOverwrite(); }; this.setScrollSpeed = function(speed) { this.$mouseHandler.setScrollSpeed(speed); }; this.getScrollSpeed = function() { return this.$mouseHandler.getScrollSpeed(); }; this.setDragDelay = function(dragDelay) { this.$mouseHandler.setDragDelay(dragDelay); }; this.getDragDelay = function() { return this.$mouseHandler.getDragDelay(); }; this.$selectionStyle = "line"; this.setSelectionStyle = function(style) { if (this.$selectionStyle == style) return; this.$selectionStyle = style; this.onSelectionChange(); this._emit("changeSelectionStyle", {data: style}); }; this.getSelectionStyle = function() { return this.$selectionStyle; }; this.$highlightActiveLine = true; this.setHighlightActiveLine = function(shouldHighlight) { if (this.$highlightActiveLine == shouldHighlight) return; this.$highlightActiveLine = shouldHighlight; this.$updateHighlightActiveLine(); }; this.getHighlightActiveLine = function() { return this.$highlightActiveLine; }; this.$highlightGutterLine = true; this.setHighlightGutterLine = function(shouldHighlight) { if (this.$highlightGutterLine == shouldHighlight) return; this.renderer.setHighlightGutterLine(shouldHighlight); this.$highlightGutterLine = shouldHighlight; }; this.getHighlightGutterLine = function() { return this.$highlightGutterLine; }; this.$highlightSelectedWord = true; this.setHighlightSelectedWord = function(shouldHighlight) { if (this.$highlightSelectedWord == shouldHighlight) return; this.$highlightSelectedWord = shouldHighlight; this.$onSelectionChange(); }; this.getHighlightSelectedWord = function() { return this.$highlightSelectedWord; }; this.setAnimatedScroll = function(shouldAnimate){ this.renderer.setAnimatedScroll(shouldAnimate); }; this.getAnimatedScroll = function(){ return this.renderer.getAnimatedScroll(); }; this.setShowInvisibles = function(showInvisibles) { if (this.getShowInvisibles() == showInvisibles) return; this.renderer.setShowInvisibles(showInvisibles); }; this.getShowInvisibles = function() { return this.renderer.getShowInvisibles(); }; this.setShowPrintMargin = function(showPrintMargin) { this.renderer.setShowPrintMargin(showPrintMargin); }; this.getShowPrintMargin = function() { return this.renderer.getShowPrintMargin(); }; this.setPrintMarginColumn = function(showPrintMargin) { this.renderer.setPrintMarginColumn(showPrintMargin); }; this.getPrintMarginColumn = function() { return this.renderer.getPrintMarginColumn(); }; this.$readOnly = false; this.setReadOnly = function(readOnly) { this.$readOnly = readOnly; }; this.getReadOnly = function() { return this.$readOnly; }; this.$modeBehaviours = true; this.setBehavioursEnabled = function (enabled) { this.$modeBehaviours = enabled; }; this.getBehavioursEnabled = function () { return this.$modeBehaviours; }; this.setShowFoldWidgets = function(show) { var gutter = this.renderer.$gutterLayer; if (gutter.getShowFoldWidgets() == show) return; this.renderer.$gutterLayer.setShowFoldWidgets(show); this.$showFoldWidgets = show; this.renderer.updateFull(); }; this.getShowFoldWidgets = function() { return this.renderer.$gutterLayer.getShowFoldWidgets(); }; this.setFadeFoldWidgets = function(show) { this.renderer.setFadeFoldWidgets(show); }; this.getFadeFoldWidgets = function() { return this.renderer.getFadeFoldWidgets(); }; this.remove = function(dir) { if (this.selection.isEmpty()){ if (dir == "left") this.selection.selectLeft(); else this.selection.selectRight(); } var range = this.getSelectionRange(); if (this.getBehavioursEnabled()) { var session = this.session; var state = session.getState(range.start.row); var new_range = session.getMode().transformAction(state, 'deletion', this, session, range); if (new_range) range = new_range; } this.session.remove(range); this.clearSelection(); }; this.removeWordRight = function() { if (this.selection.isEmpty()) this.selection.selectWordRight(); this.session.remove(this.getSelectionRange()); this.clearSelection(); }; this.removeWordLeft = function() { if (this.selection.isEmpty()) this.selection.selectWordLeft(); this.session.remove(this.getSelectionRange()); this.clearSelection(); }; this.removeToLineStart = function() { if (this.selection.isEmpty()) this.selection.selectLineStart(); this.session.remove(this.getSelectionRange()); this.clearSelection(); }; this.removeToLineEnd = function() { if (this.selection.isEmpty()) this.selection.selectLineEnd(); var range = this.getSelectionRange(); if (range.start.column == range.end.column && range.start.row == range.end.row) { range.end.column = 0; range.end.row++; } this.session.remove(range); this.clearSelection(); }; this.splitLine = function() { if (!this.selection.isEmpty()) { this.session.remove(this.getSelectionRange()); this.clearSelection(); } var cursor = this.getCursorPosition(); this.insert("\n"); this.moveCursorToPosition(cursor); }; this.transposeLetters = function() { if (!this.selection.isEmpty()) { return; } var cursor = this.getCursorPosition(); var column = cursor.column; if (column === 0) return; var line = this.session.getLine(cursor.row); var swap, range; if (column < line.length) { swap = line.charAt(column) + line.charAt(column-1); range = new Range(cursor.row, column-1, cursor.row, column+1); } else { swap = line.charAt(column-1) + line.charAt(column-2); range = new Range(cursor.row, column-2, cursor.row, column); } this.session.replace(range, swap); }; this.toLowerCase = function() { var originalRange = this.getSelectionRange(); if (this.selection.isEmpty()) { this.selection.selectWord(); } var range = this.getSelectionRange(); var text = this.session.getTextRange(range); this.session.replace(range, text.toLowerCase()); this.selection.setSelectionRange(originalRange); }; this.toUpperCase = function() { var originalRange = this.getSelectionRange(); if (this.selection.isEmpty()) { this.selection.selectWord(); } var range = this.getSelectionRange(); var text = this.session.getTextRange(range); this.session.replace(range, text.toUpperCase()); this.selection.setSelectionRange(originalRange); }; this.indent = function() { var session = this.session; var range = this.getSelectionRange(); if (range.start.row < range.end.row || range.start.column < range.end.column) { var rows = this.$getSelectedRows(); session.indentRows(rows.first, rows.last, "\t"); } else { var indentString; if (this.session.getUseSoftTabs()) { var size = session.getTabSize(), position = this.getCursorPosition(), column = session.documentToScreenColumn(position.row, position.column), count = (size - column % size); indentString = lang.stringRepeat(" ", count); } else indentString = "\t"; return this.insert(indentString); } }; this.blockOutdent = function() { var selection = this.session.getSelection(); this.session.outdentRows(selection.getRange()); }; this.toggleCommentLines = function() { var state = this.session.getState(this.getCursorPosition().row); var rows = this.$getSelectedRows(); this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last); }; this.removeLines = function() { var rows = this.$getSelectedRows(); var range; if (rows.first === 0 || rows.last+1 < this.session.getLength()) range = new Range(rows.first, 0, rows.last+1, 0); else range = new Range( rows.first-1, this.session.getLine(rows.first-1).length, rows.last, this.session.getLine(rows.last).length ); this.session.remove(range); this.clearSelection(); }; this.moveLinesDown = function() { this.$moveLines(function(firstRow, lastRow) { return this.session.moveLinesDown(firstRow, lastRow); }); }; this.moveLinesUp = function() { this.$moveLines(function(firstRow, lastRow) { return this.session.moveLinesUp(firstRow, lastRow); }); }; this.moveText = function(range, toPosition) { if (this.$readOnly) return null; return this.session.moveText(range, toPosition); }; this.copyLinesUp = function() { this.$moveLines(function(firstRow, lastRow) { this.session.duplicateLines(firstRow, lastRow); return 0; }); }; this.copyLinesDown = function() { this.$moveLines(function(firstRow, lastRow) { return this.session.duplicateLines(firstRow, lastRow); }); }; this.$moveLines = function(mover) { var rows = this.$getSelectedRows(); var selection = this.selection; if (!selection.isMultiLine()) { var range = selection.getRange(); var reverse = selection.isBackwards(); } var linesMoved = mover.call(this, rows.first, rows.last); if (range) { range.start.row += linesMoved; range.end.row += linesMoved; selection.setSelectionRange(range, reverse); } else { selection.setSelectionAnchor(rows.last+linesMoved+1, 0); selection.$moveSelection(function() { selection.moveCursorTo(rows.first+linesMoved, 0); }); } }; this.$getSelectedRows = function() { var range = this.getSelectionRange().collapseRows(); return { first: range.start.row, last: range.end.row }; }; this.onCompositionStart = function(text) { this.renderer.showComposition(this.getCursorPosition()); }; this.onCompositionUpdate = function(text) { this.renderer.setCompositionText(text); }; this.onCompositionEnd = function() { this.renderer.hideComposition(); }; this.getFirstVisibleRow = function() { return this.renderer.getFirstVisibleRow(); }; this.getLastVisibleRow = function() { return this.renderer.getLastVisibleRow(); }; this.isRowVisible = function(row) { return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow()); }; this.isRowFullyVisible = function(row) { return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow()); }; this.$getVisibleRowCount = function() { return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1; }; this.$moveByPage = function(dir, select) { var renderer = this.renderer; var config = this.renderer.layerConfig; var rows = dir * Math.floor(config.height / config.lineHeight); this.$blockScrolling++; if (select == true) { this.selection.$moveSelection(function(){ this.moveCursorBy(rows, 0); }); } else if (select == false) { this.selection.moveCursorBy(rows, 0); this.selection.clearSelection(); } this.$blockScrolling--; var scrollTop = renderer.scrollTop; renderer.scrollBy(0, rows * config.lineHeight); if (select != null) renderer.scrollCursorIntoView(null, 0.5); renderer.animateScrolling(scrollTop); }; this.selectPageDown = function() { this.$moveByPage(1, true); }; this.selectPageUp = function() { this.$moveByPage(-1, true); }; this.gotoPageDown = function() { this.$moveByPage(1, false); }; this.gotoPageUp = function() { this.$moveByPage(-1, false); }; this.scrollPageDown = function() { this.$moveByPage(1); }; this.scrollPageUp = function() { this.$moveByPage(-1); }; this.scrollToRow = function(row) { this.renderer.scrollToRow(row); }; this.scrollToLine = function(line, center, animate, callback) { this.renderer.scrollToLine(line, center, animate, callback); }; this.centerSelection = function() { var range = this.getSelectionRange(); var line = Math.floor(range.start.row + (range.end.row - range.start.row) / 2); this.renderer.scrollToLine(line, true); }; this.getCursorPosition = function() { return this.selection.getCursor(); }; this.getCursorPositionScreen = function() { return this.session.documentToScreenPosition(this.getCursorPosition()); }; this.getSelectionRange = function() { return this.selection.getRange(); }; this.selectAll = function() { this.$blockScrolling += 1; this.selection.selectAll(); this.$blockScrolling -= 1; }; this.clearSelection = function() { this.selection.clearSelection(); }; this.moveCursorTo = function(row, column) { this.selection.moveCursorTo(row, column); }; this.moveCursorToPosition = function(pos) { this.selection.moveCursorToPosition(pos); }; this.jumpToMatching = function() { var cursor = this.getCursorPosition(); var pos = this.session.findMatchingBracket(cursor); if (!pos) { cursor.column += 1; pos = this.session.findMatchingBracket(cursor); } if (!pos) { cursor.column -= 2; pos = this.session.findMatchingBracket(cursor); } if (pos) { this.clearSelection(); this.moveCursorTo(pos.row, pos.column); } }; this.gotoLine = function(lineNumber, column, animate) { this.selection.clearSelection(); this.session.unfold({row: lineNumber - 1, column: column || 0}); this.$blockScrolling += 1; this.moveCursorTo(lineNumber - 1, column || 0); this.$blockScrolling -= 1; if (!this.isRowFullyVisible(lineNumber - 1)) this.scrollToLine(lineNumber - 1, true, animate); }; this.navigateTo = function(row, column) { this.clearSelection(); this.moveCursorTo(row, column); }; this.navigateUp = function(times) { this.selection.clearSelection(); times = times || 1; this.selection.moveCursorBy(-times, 0); }; this.navigateDown = function(times) { this.selection.clearSelection(); times = times || 1; this.selection.moveCursorBy(times, 0); }; this.navigateLeft = function(times) { if (!this.selection.isEmpty()) { var selectionStart = this.getSelectionRange().start; this.moveCursorToPosition(selectionStart); } else { times = times || 1; while (times--) { this.selection.moveCursorLeft(); } } this.clearSelection(); }; this.navigateRight = function(times) { if (!this.selection.isEmpty()) { var selectionEnd = this.getSelectionRange().end; this.moveCursorToPosition(selectionEnd); } else { times = times || 1; while (times--) { this.selection.moveCursorRight(); } } this.clearSelection(); }; this.navigateLineStart = function() { this.selection.moveCursorLineStart(); this.clearSelection(); }; this.navigateLineEnd = function() { this.selection.moveCursorLineEnd(); this.clearSelection(); }; this.navigateFileEnd = function() { var scrollTop = this.renderer.scrollTop; this.selection.moveCursorFileEnd(); this.clearSelection(); this.renderer.animateScrolling(scrollTop); }; this.navigateFileStart = function() { var scrollTop = this.renderer.scrollTop; this.selection.moveCursorFileStart(); this.clearSelection(); this.renderer.animateScrolling(scrollTop); }; this.navigateWordRight = function() { this.selection.moveCursorWordRight(); this.clearSelection(); }; this.navigateWordLeft = function() { this.selection.moveCursorWordLeft(); this.clearSelection(); }; this.replace = function(replacement, options) { if (options) this.$search.set(options); var range = this.$search.find(this.session); var replaced = 0; if (!range) return replaced; if (this.$tryReplace(range, replacement)) { replaced = 1; } if (range !== null) { this.selection.setSelectionRange(range); this.renderer.scrollSelectionIntoView(range.start, range.end); } return replaced; }; this.replaceAll = function(replacement, options) { if (options) { this.$search.set(options); } var ranges = this.$search.findAll(this.session); var replaced = 0; if (!ranges.length) return replaced; this.$blockScrolling += 1; var selection = this.getSelectionRange(); this.clearSelection(); this.selection.moveCursorTo(0, 0); for (var i = ranges.length - 1; i >= 0; --i) { if(this.$tryReplace(ranges[i], replacement)) { replaced++; } } this.selection.setSelectionRange(selection); this.$blockScrolling -= 1; return replaced; }; this.$tryReplace = function(range, replacement) { var input = this.session.getTextRange(range); replacement = this.$search.replace(input, replacement); if (replacement !== null) { range.end = this.session.replace(range, replacement); return range; } else { return null; } }; this.getLastSearchOptions = function() { return this.$search.getOptions(); }; this.find = function(needle, options, animate) { if (!options) options = {}; if (typeof needle == "string" || needle instanceof RegExp) options.needle = needle; else if (typeof needle == "object") oop.mixin(options, needle); var range = this.selection.getRange(); if (options.needle == null) { needle = this.session.getTextRange(range) || this.$search.$options.needle; if (!needle) { range = this.session.getWordRange(range.start.row, range.start.column); needle = this.session.getTextRange(range); } this.$search.set({needle: needle}); } this.$search.set(options); if (!options.start) this.$search.set({start: range}); var newRange = this.$search.find(this.session); if (options.preventScroll) return newRange; if (newRange) { this.revealRange(newRange, animate); return newRange; } // clear selection if nothing is found if (options.backwards) range.start = range.end; else range.end = range.start; this.selection.setRange(range); }; this.findNext = function(options, animate) { this.find({skipCurrent: true, backwards: false}, options, animate); }; this.findPrevious = function(options, animate) { this.find(options, {skipCurrent: true, backwards: true}, animate); }; this.revealRange = function(range, animate) { this.$blockScrolling += 1; this.session.unfold(range); this.selection.setSelectionRange(range); this.$blockScrolling -= 1; var scrollTop = this.renderer.scrollTop; this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5); if (animate != false) this.renderer.animateScrolling(scrollTop); }; this.undo = function() { this.$blockScrolling++; this.session.getUndoManager().undo(); this.$blockScrolling--; this.renderer.scrollCursorIntoView(null, 0.5); }; this.redo = function() { this.$blockScrolling++; this.session.getUndoManager().redo(); this.$blockScrolling--; this.renderer.scrollCursorIntoView(null, 0.5); }; this.destroy = function() { this.renderer.destroy(); }; }).call(Editor.prototype); exports.Editor = Editor; }); define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { return new Array(count + 1).join(string); }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function (obj) { if (typeof obj != "object") { return obj; } var copy = obj.constructor(); for (var key in obj) { if (typeof obj[key] == "object") { copy[key] = this.deepCopy(obj[key]); } else { copy[key] = obj[key]; } } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; return deferred; }; }); define('ace/keyboard/textinput', ['require', 'exports', 'module' , 'ace/lib/event', 'ace/lib/useragent', 'ace/lib/dom'], function(require, exports, module) { var event = require("../lib/event"); var useragent = require("../lib/useragent"); var dom = require("../lib/dom"); var TextInput = function(parentNode, host) { var text = dom.createElement("textarea"); if (useragent.isTouchPad) text.setAttribute("x-palm-disable-auto-cap", true); text.setAttribute("wrap", "off"); text.style.top = "-2em"; parentNode.insertBefore(text, parentNode.firstChild); var PLACEHOLDER = useragent.isIE ? "\x01" : "\x01"; sendText(); var inCompostion = false; var copied = false; var pasted = false; var tempStyle = ''; function reset(full) { try { if (full) { text.value = PLACEHOLDER; text.selectionStart = 0; text.selectionEnd = 1; } else text.select(); } catch (e) {} } function sendText(valueToSend) { if (!copied) { var value = valueToSend || text.value; if (value) { if (value.length > 1) { if (value.charAt(0) == PLACEHOLDER) value = value.substr(1); else if (value.charAt(value.length - 1) == PLACEHOLDER) value = value.slice(0, -1); } if (value && value != PLACEHOLDER) { if (pasted) host.onPaste(value); else host.onTextInput(value); } } } copied = false; pasted = false; // Safari doesn't fire copy events if no text is selected reset(true); } var onTextInput = function(e) { if (!inCompostion) sendText(e.data); setTimeout(function () { if (!inCompostion) reset(true); }, 0); }; var onPropertyChange = function(e) { setTimeout(function() { if (!inCompostion) sendText(); }, 0); }; var onCompositionStart = function(e) { inCompostion = true; host.onCompositionStart(); setTimeout(onCompositionUpdate, 0); }; var onCompositionUpdate = function() { if (!inCompostion) return; host.onCompositionUpdate(text.value); }; var onCompositionEnd = function(e) { inCompostion = false; host.onCompositionEnd(); }; var onCopy = function(e) { copied = true; var copyText = host.getCopyText(); if(copyText) text.value = copyText; else e.preventDefault(); reset(); setTimeout(function () { sendText(); }, 0); }; var onCut = function(e) { copied = true; var copyText = host.getCopyText(); if(copyText) { text.value = copyText; host.onCut(); } else e.preventDefault(); reset(); setTimeout(function () { sendText(); }, 0); }; event.addCommandKeyListener(text, host.onCommandKey.bind(host)); event.addListener(text, "input", useragent.isIE ? onPropertyChange : onTextInput); event.addListener(text, "paste", function(e) { // Mark that the next input text comes from past. pasted = true; // Some browsers support the event.clipboardData API. Use this to get // the pasted content which increases speed if pasting a lot of lines. if (e.clipboardData && e.clipboardData.getData) { sendText(e.clipboardData.getData("text/plain")); e.preventDefault(); } else { // If a browser doesn't support any of the things above, use the regular // method to detect the pasted input. onPropertyChange(); } }); if ("onbeforecopy" in text && typeof clipboardData !== "undefined") { event.addListener(text, "beforecopy", function(e) { if (tempStyle) return; // without this text is copied when contextmenu is shown var copyText = host.getCopyText(); if (copyText) clipboardData.setData("Text", copyText); else e.preventDefault(); }); event.addListener(parentNode, "keydown", function(e) { if (e.ctrlKey && e.keyCode == 88) { var copyText = host.getCopyText(); if (copyText) { clipboardData.setData("Text", copyText); host.onCut(); } event.preventDefault(e); } }); event.addListener(text, "cut", onCut); // for ie9 context menu } else if (useragent.isOpera) { event.addListener(parentNode, "keydown", function(e) { if ((useragent.isMac && !e.metaKey) || !e.ctrlKey) return; if ((e.keyCode == 88 || e.keyCode == 67)) { var copyText = host.getCopyText(); if (copyText) { text.value = copyText; text.select(); if (e.keyCode == 88) host.onCut(); } } }); } else { event.addListener(text, "copy", onCopy); event.addListener(text, "cut", onCut); } event.addListener(text, "compositionstart", onCompositionStart); if (useragent.isGecko) { event.addListener(text, "text", onCompositionUpdate); } if (useragent.isWebKit) { event.addListener(text, "keyup", onCompositionUpdate); } event.addListener(text, "compositionend", onCompositionEnd); event.addListener(text, "blur", function() { host.onBlur(); }); event.addListener(text, "focus", function() { host.onFocus(); reset(); }); this.focus = function() { host.onFocus(); reset(); text.focus(); }; this.blur = function() { text.blur(); }; function isFocused() { return document.activeElement === text; } this.isFocused = isFocused; this.getElement = function() { return text; }; this.onContextMenu = function(e) { if (!tempStyle) tempStyle = text.style.cssText; text.style.cssText = "position:fixed; z-index:100000;" + //"background:rgba(250, 0, 0, 0.3); opacity:1;" + "left:" + (e.clientX - 2) + "px; top:" + (e.clientY - 2) + "px;"; if (host.selection.isEmpty()) text.value = ""; if (e.type != "mousedown") return; if (host.renderer.$keepTextAreaAtCursor) host.renderer.$keepTextAreaAtCursor = null; event.capture(host.container, function(e) { text.style.left = e.clientX - 2 + "px"; text.style.top = e.clientY - 2 + "px"; }, onContextMenuClose); }; function onContextMenuClose() { setTimeout(function () { if (tempStyle) { text.style.cssText = tempStyle; tempStyle = ''; } sendText(); if (host.renderer.$keepTextAreaAtCursor == null) { host.renderer.$keepTextAreaAtCursor = true; host.renderer.$moveTextAreaToCursor(); } }, 0); }; this.onContextMenuClose = onContextMenuClose; // firefox fires contextmenu event after opening it if (!useragent.isGecko) event.addListener(text, "contextmenu", function(e) { host.textInput.onContextMenu(e); onContextMenuClose() }); }; exports.TextInput = TextInput; }); define('ace/mouse/mouse_handler', ['require', 'exports', 'module' , 'ace/lib/event', 'ace/mouse/default_handlers', 'ace/mouse/default_gutter_handler', 'ace/mouse/mouse_event', 'ace/mouse/dragdrop'], function(require, exports, module) { var event = require("../lib/event"); var DefaultHandlers = require("./default_handlers").DefaultHandlers; var DefaultGutterHandler = require("./default_gutter_handler").GutterHandler; var MouseEvent = require("./mouse_event").MouseEvent; var DragdropHandler = require("./dragdrop").DragdropHandler; var MouseHandler = function(editor) { this.editor = editor; new DefaultHandlers(this); new DefaultGutterHandler(this); new DragdropHandler(this); event.addListener(editor.container, "mousedown", function(e) { editor.focus(); return event.preventDefault(e); }); var mouseTarget = editor.renderer.getMouseEventTarget(); event.addListener(mouseTarget, "click", this.onMouseEvent.bind(this, "click")); event.addListener(mouseTarget, "mousemove", this.onMouseMove.bind(this, "mousemove")); event.addMultiMouseDownListener(mouseTarget, [300, 300, 250], this, "onMouseEvent"); event.addMouseWheelListener(editor.container, this.onMouseWheel.bind(this, "mousewheel")); var gutterEl = editor.renderer.$gutter; event.addListener(gutterEl, "mousedown", this.onMouseEvent.bind(this, "guttermousedown")); event.addListener(gutterEl, "click", this.onMouseEvent.bind(this, "gutterclick")); event.addListener(gutterEl, "dblclick", this.onMouseEvent.bind(this, "gutterdblclick")); event.addListener(gutterEl, "mousemove", this.onMouseMove.bind(this, "gutter")); }; (function() { this.$scrollSpeed = 1; this.setScrollSpeed = function(speed) { this.$scrollSpeed = speed; }; this.getScrollSpeed = function() { return this.$scrollSpeed; }; this.onMouseEvent = function(name, e) { this.editor._emit(name, new MouseEvent(e, this.editor)); }; this.$dragDelay = 250; this.setDragDelay = function(dragDelay) { this.$dragDelay = dragDelay; }; this.getDragDelay = function() { return this.$dragDelay; }; this.onMouseMove = function(name, e) { // optimization, because mousemove doesn't have a default handler. var listeners = this.editor._eventRegistry && this.editor._eventRegistry.mousemove; if (!listeners || !listeners.length) return; this.editor._emit(name, new MouseEvent(e, this.editor)); }; this.onMouseWheel = function(name, e) { var mouseEvent = new MouseEvent(e, this.editor); mouseEvent.speed = this.$scrollSpeed * 2; mouseEvent.wheelX = e.wheelX; mouseEvent.wheelY = e.wheelY; this.editor._emit(name, mouseEvent); }; this.setState = function(state) { this.state = state; }; this.captureMouse = function(ev, state) { if (state) this.setState(state); this.x = ev.x; this.y = ev.y; // do not move textarea during selection var renderer = this.editor.renderer; if (renderer.$keepTextAreaAtCursor) renderer.$keepTextAreaAtCursor = null; var self = this; var onMouseSelection = function(e) { self.x = e.clientX; self.y = e.clientY; }; var onMouseSelectionEnd = function(e) { clearInterval(timerId); self[self.state + "End"] && self[self.state + "End"](e); self.$clickSelection = null; if (renderer.$keepTextAreaAtCursor == null) { renderer.$keepTextAreaAtCursor = true; renderer.$moveTextAreaToCursor(); } }; var onSelectionInterval = function() { self[self.state] && self[self.state](); } event.capture(this.editor.container, onMouseSelection, onMouseSelectionEnd); var timerId = setInterval(onSelectionInterval, 20); }; }).call(MouseHandler.prototype); exports.MouseHandler = MouseHandler; }); define('ace/mouse/default_handlers', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/useragent'], function(require, exports, module) { var dom = require("../lib/dom"); var useragent = require("../lib/useragent"); var DRAG_OFFSET = 5; // pixels function DefaultHandlers(mouseHandler) { mouseHandler.$clickSelection = null; var editor = mouseHandler.editor; editor.setDefaultHandler("mousedown", this.onMouseDown.bind(mouseHandler)); editor.setDefaultHandler("dblclick", this.onDoubleClick.bind(mouseHandler)); editor.setDefaultHandler("tripleclick", this.onTripleClick.bind(mouseHandler)); editor.setDefaultHandler("quadclick", this.onQuadClick.bind(mouseHandler)); editor.setDefaultHandler("mousewheel", this.onScroll.bind(mouseHandler)); var exports = ["select", "startSelect", "drag", "dragEnd", "dragWait", "dragWaitEnd", "startDrag", "focusWait"]; exports.forEach(function(x) { mouseHandler[x] = this[x]; }, this); mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange"); mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange"); mouseHandler.$focusWaitTimout = 250; } (function() { this.onMouseDown = function(ev) { var inSelection = ev.inSelection(); var pos = ev.getDocumentPosition(); this.mousedownEvent = ev; var editor = this.editor; var _self = this; var button = ev.getButton(); if (button !== 0) { var selectionRange = editor.getSelectionRange(); var selectionEmpty = selectionRange.isEmpty(); if (selectionEmpty) { editor.moveCursorToPosition(pos); editor.selection.clearSelection(); } // 2: contextmenu, 1: linux paste editor.textInput.onContextMenu(ev.domEvent); return ev.stop(); } // if this click caused the editor to be focused should not clear the // selection if (inSelection && !editor.isFocused()) { editor.focus(); if (this.$focusWaitTimout && !this.$clickSelection) { this.setState("focusWait"); this.captureMouse(ev); return ev.preventDefault(); } } if (!inSelection || this.$clickSelection || ev.getShiftKey()) { // Directly pick STATE_SELECT, since the user is not clicking inside // a selection. this.startSelect(pos); } else if (inSelection) { var e = ev.domEvent; if ((e.ctrlKey || e.altKey)) { this.startDrag(); } else { this.mousedownEvent.time = (new Date()).getTime(); this.setState("dragWait"); } } this.captureMouse(ev); return ev.preventDefault(); }; this.startSelect = function(pos) { pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y); if (this.mousedownEvent.getShiftKey()) { this.editor.selection.selectToPosition(pos); } else if (!this.$clickSelection) { this.editor.moveCursorToPosition(pos); this.editor.selection.clearSelection(); } this.setState("select"); } this.select = function() { var anchor, editor = this.editor; var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); if (this.$clickSelection) { var cmp = this.$clickSelection.comparePoint(cursor); if (cmp == -1) { anchor = this.$clickSelection.end; } else if (cmp == 1) { anchor = this.$clickSelection.start; } else { cursor = this.$clickSelection.end; anchor = this.$clickSelection.start; } editor.selection.setSelectionAnchor(anchor.row, anchor.column); } editor.selection.selectToPosition(cursor); editor.renderer.scrollCursorIntoView(); }; this.extendSelectionBy = function(unitName) { var anchor, editor = this.editor; var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); var range = editor.selection[unitName](cursor.row, cursor.column); if (this.$clickSelection) { var cmpStart = this.$clickSelection.comparePoint(range.start); var cmpEnd = this.$clickSelection.comparePoint(range.end); if (cmpStart == -1 && cmpEnd <= 0) { anchor = this.$clickSelection.end; cursor = range.start; } else if (cmpEnd == 1 && cmpStart >= 0) { anchor = this.$clickSelection.start; cursor = range.end; } else if (cmpStart == -1 && cmpEnd == 1) { cursor = range.end; anchor = range.start; } else { cursor = this.$clickSelection.end; anchor = this.$clickSelection.start; } editor.selection.setSelectionAnchor(anchor.row, anchor.column); } editor.selection.selectToPosition(cursor); editor.renderer.scrollCursorIntoView(); }; this.startDrag = function() { var editor = this.editor; this.setState("drag"); this.dragRange = editor.getSelectionRange(); var style = editor.getSelectionStyle(); this.dragSelectionMarker = editor.session.addMarker(this.dragRange, "ace_selection", style); editor.clearSelection(); dom.addCssClass(editor.container, "ace_dragging"); if (!this.$dragKeybinding) { this.$dragKeybinding = { handleKeyboard: function(data, hashId, keyString, keyCode) { if (keyString == "esc") return {command: this.command}; }, command: { exec: function(editor) { var self = editor.$mouseHandler; self.dragCursor = null self.dragEnd(); self.startSelect(); } } } } editor.keyBinding.addKeyboardHandler(this.$dragKeybinding); }; this.focusWait = function() { var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); var time = (new Date()).getTime(); if (distance > DRAG_OFFSET ||time - this.mousedownEvent.time > this.$focusWaitTimout) this.startSelect(); }; this.dragWait = function() { var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); var time = (new Date()).getTime(); var editor = this.editor; if (distance > DRAG_OFFSET) { this.startSelect(); } else if (time - this.mousedownEvent.time > editor.getDragDelay()) { this.startDrag() } }; this.dragWaitEnd = function(e) { this.mousedownEvent.domEvent = e; this.startSelect(); }; this.drag = function() { var editor = this.editor; this.dragCursor = editor.renderer.screenToTextCoordinates(this.x, this.y); editor.moveCursorToPosition(this.dragCursor); editor.renderer.scrollCursorIntoView(); }; this.dragEnd = function(e) { var editor = this.editor; var dragCursor = this.dragCursor; var dragRange = this.dragRange; dom.removeCssClass(editor.container, "ace_dragging"); editor.session.removeMarker(this.dragSelectionMarker); editor.keyBinding.removeKeyboardHandler(this.$dragKeybinding); if (!dragCursor) return; editor.clearSelection(); if (e && (e.ctrlKey || e.altKey)) { var session = editor.session; var newRange = dragRange; newRange.end = session.insert(dragCursor, session.getTextRange(dragRange)); newRange.start = dragCursor; } else if (dragRange.contains(dragCursor.row, dragCursor.column)) { return; } else { var newRange = editor.moveText(dragRange, dragCursor); } if (!newRange) return; editor.selection.setSelectionRange(newRange); }; this.onDoubleClick = function(ev) { var pos = ev.getDocumentPosition(); var editor = this.editor; this.setState("selectByWords"); editor.moveCursorToPosition(pos); editor.selection.selectWord(); this.$clickSelection = editor.getSelectionRange(); }; this.onTripleClick = function(ev) { var pos = ev.getDocumentPosition(); var editor = this.editor; this.setState("selectByLines"); editor.moveCursorToPosition(pos); editor.selection.selectLine(); this.$clickSelection = editor.getSelectionRange(); }; this.onQuadClick = function(ev) { var editor = this.editor; editor.selectAll(); this.$clickSelection = editor.getSelectionRange(); this.setState("null"); }; this.onScroll = function(ev) { var editor = this.editor; var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); if (isScrolable) { this.$passScrollEvent = false; } else { if (this.$passScrollEvent) return; if (!this.$scrollStopTimeout) { var self = this; this.$scrollStopTimeout = setTimeout(function() { self.$passScrollEvent = true; self.$scrollStopTimeout = null; }, 200); } } editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); return ev.preventDefault(); }; }).call(DefaultHandlers.prototype); exports.DefaultHandlers = DefaultHandlers; function calcDistance(ax, ay, bx, by) { return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); } }); define('ace/mouse/default_gutter_handler', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { var dom = require("../lib/dom"); function GutterHandler(mouseHandler) { var editor = mouseHandler.editor; mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) { var target = e.domEvent.target; if (target.className.indexOf("ace_gutter-cell") == -1) return; if (!editor.isFocused()) return; var padding = parseInt(dom.computedStyle(target).paddingLeft); if (e.x < padding + target.getBoundingClientRect().left + 1) return; var row = e.getDocumentPosition().row; var selection = editor.session.selection; if (e.getShiftKey()) { selection.selectTo(row, 0); } else { selection.moveCursorTo(row, 0); selection.selectLine(); mouseHandler.$clickSelection = selection.getRange(); } mouseHandler.captureMouse(e, "selectByLines"); return e.preventDefault(); }); } exports.GutterHandler = GutterHandler; }); define('ace/mouse/mouse_event', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("../lib/event"); var MouseEvent = exports.MouseEvent = function(domEvent, editor) { this.domEvent = domEvent; this.editor = editor; this.x = this.clientX = domEvent.clientX; this.y = this.clientY = domEvent.clientY; this.$pos = null; this.$inSelection = null; this.propagationStopped = false; this.defaultPrevented = false; }; (function() { this.stopPropagation = function() { event.stopPropagation(this.domEvent); this.propagationStopped = true; }; this.preventDefault = function() { event.preventDefault(this.domEvent); this.defaultPrevented = true; }; this.stop = function() { this.stopPropagation(); this.preventDefault(); }; this.getDocumentPosition = function() { if (this.$pos) return this.$pos; this.$pos = this.editor.renderer.screenToTextCoordinates(this.clientX, this.clientY); return this.$pos; }; this.inSelection = function() { if (this.$inSelection !== null) return this.$inSelection; var editor = this.editor; if (editor.getReadOnly()) { this.$inSelection = false; } else { var selectionRange = editor.getSelectionRange(); if (selectionRange.isEmpty()) this.$inSelection = false; else { var pos = this.getDocumentPosition(); this.$inSelection = selectionRange.contains(pos.row, pos.column); } } return this.$inSelection; }; this.getButton = function() { return event.getButton(this.domEvent); }; this.getShiftKey = function() { return this.domEvent.shiftKey; }; this.getAccelKey = function() { return this.domEvent.ctrlKey || this.domEvent.metaKey ; }; }).call(MouseEvent.prototype); }); define('ace/mouse/dragdrop', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("../lib/event"); var DragdropHandler = function(mouseHandler) { var editor = mouseHandler.editor; var dragSelectionMarker, x, y; var timerId, range, isBackwards; var dragCursor, counter = 0; var mouseTarget = editor.container; event.addListener(mouseTarget, "dragenter", function(e) {console.log(e.type, counter,e.target); counter++; if (!dragSelectionMarker) { range = editor.getSelectionRange(); isBackwards = editor.selection.isBackwards(); var style = editor.getSelectionStyle(); dragSelectionMarker = editor.session.addMarker(range, "ace_selection", style); editor.clearSelection(); clearInterval(timerId); timerId = setInterval(onDragInterval, 20); } return event.preventDefault(e); }); event.addListener(mouseTarget, "dragover", function(e) { x = e.clientX; y = e.clientY; return event.preventDefault(e); }); var onDragInterval = function() { dragCursor = editor.renderer.screenToTextCoordinates(x, y); editor.moveCursorToPosition(dragCursor); editor.renderer.scrollCursorIntoView(); }; event.addListener(mouseTarget, "dragleave", function(e) {console.log(e.type, counter,e.target); counter--; if (counter > 0) return; console.log(e.type, counter,e.target); clearInterval(timerId); editor.session.removeMarker(dragSelectionMarker); dragSelectionMarker = null; editor.selection.setSelectionRange(range, isBackwards); return event.preventDefault(e); }); event.addListener(mouseTarget, "drop", function(e) { console.log(e.type, counter,e.target); counter = 0; clearInterval(timerId); editor.session.removeMarker(dragSelectionMarker); dragSelectionMarker = null; range.end = editor.session.insert(dragCursor, e.dataTransfer.getData('Text')); range.start = dragCursor; editor.focus(); editor.selection.setSelectionRange(range); return event.preventDefault(e); }); }; exports.DragdropHandler = DragdropHandler; }); define('ace/mouse/fold_handler', ['require', 'exports', 'module' ], function(require, exports, module) { function FoldHandler(editor) { editor.on("click", function(e) { var position = e.getDocumentPosition(); var session = editor.session; // If the user clicked on a fold, then expand it. var fold = session.getFoldAt(position.row, position.column, 1); if (fold) { if (e.getAccelKey()) session.removeFold(fold); else session.expandFold(fold); e.stop(); } }); editor.on("gutterclick", function(e) { if (e.domEvent.target.className.indexOf("ace_fold-widget") != -1) { var row = e.getDocumentPosition().row; editor.session.onFoldWidgetClick(row, e.domEvent); e.stop(); } }); } exports.FoldHandler = FoldHandler; }); define('ace/keyboard/keybinding', ['require', 'exports', 'module' , 'ace/lib/keys', 'ace/lib/event'], function(require, exports, module) { var keyUtil = require("../lib/keys"); var event = require("../lib/event"); var KeyBinding = function(editor) { this.$editor = editor; this.$data = { }; this.$handlers = []; this.setDefaultHandler(editor.commands); }; (function() { this.setDefaultHandler = function(kb) { this.removeKeyboardHandler(this.$defaultHandler); this.$defaultHandler = kb; this.addKeyboardHandler(kb, 0); this.$data = {editor: this.$editor}; }; this.setKeyboardHandler = function(kb) { if (this.$handlers[this.$handlers.length - 1] == kb) return; while (this.$handlers[1]) this.removeKeyboardHandler(this.$handlers[1]); this.addKeyboardHandler(kb, 1); }; this.addKeyboardHandler = function(kb, pos) { if (!kb) return; var i = this.$handlers.indexOf(kb); if (i != -1) this.$handlers.splice(i, 1); if (pos == undefined) this.$handlers.push(kb); else this.$handlers.splice(pos, 0, kb); if (i == -1 && kb.attach) kb.attach(this.$editor); }; this.removeKeyboardHandler = function(kb) { var i = this.$handlers.indexOf(kb); if (i == -1) return false; this.$handlers.splice(i, 1); kb.detach && kb.detach(this.$editor); return true; }; this.getKeyboardHandler = function() { return this.$handlers[this.$handlers.length - 1]; }; this.$callKeyboardHandlers = function (hashId, keyString, keyCode, e) { var toExecute; for (var i = this.$handlers.length; i--;) { toExecute = this.$handlers[i].handleKeyboard( this.$data, hashId, keyString, keyCode, e ); if (toExecute && toExecute.command) break; } if (!toExecute || !toExecute.command) return false; var success = false; var commands = this.$editor.commands; // allow keyboardHandler to consume keys if (toExecute.command != "null") success = commands.exec(toExecute.command, this.$editor, toExecute.args, e); else success = toExecute.passEvent != true; // do not stop input events to not break repeating if (success && e && hashId != -1) event.stopEvent(e); return success; }; this.onCommandKey = function(e, hashId, keyCode) { var keyString = keyUtil.keyCodeToString(keyCode); this.$callKeyboardHandlers(hashId, keyString, keyCode, e); }; this.onTextInput = function(text) { var success = this.$callKeyboardHandlers(-1, text); if (!success) this.$editor.commands.exec("insertstring", this.$editor, text); }; }).call(KeyBinding.prototype); exports.KeyBinding = KeyBinding; }); define('ace/edit_session', ['require', 'exports', 'module' , 'ace/config', 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/net', 'ace/lib/event_emitter', 'ace/selection', 'ace/mode/text', 'ace/range', 'ace/document', 'ace/background_tokenizer', 'ace/search_highlight', 'ace/edit_session/folding', 'ace/edit_session/bracket_match'], function(require, exports, module) { var config = require("./config"); var oop = require("./lib/oop"); var lang = require("./lib/lang"); var net = require("./lib/net"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Selection = require("./selection").Selection; var TextMode = require("./mode/text").Mode; var Range = require("./range").Range; var Document = require("./document").Document; var BackgroundTokenizer = require("./background_tokenizer").BackgroundTokenizer; var SearchHighlight = require("./search_highlight").SearchHighlight; /** * new EditSession(text, mode) * - text (Document | String): If `text` is a `Document`, it associates the `EditSession` with it. Otherwise, a new `Document` is created, with the initial text * - mode (TextMode): The inital language mode to use for the document * * Sets up a new `EditSession` and associates it with the given `Document` and `TextMode`. * **/ var EditSession = function(text, mode) { this.$modified = true; this.$breakpoints = []; this.$frontMarkers = {}; this.$backMarkers = {}; this.$markerId = 1; this.$resetRowCache(0); this.$wrapData = []; this.$foldData = []; this.$rowLengthCache = []; this.$undoSelect = true; this.$foldData.toString = function() { var str = ""; this.forEach(function(foldLine) { str += "\n" + foldLine.toString(); }); return str; } if (typeof text == "object" && text.getLine) { this.setDocument(text); } else { this.setDocument(new Document(text)); } this.selection = new Selection(this); this.setMode(mode); }; (function() { oop.implement(this, EventEmitter); this.setDocument = function(doc) { if (this.doc) throw new Error("Document is already set"); this.doc = doc; doc.on("change", this.onChange.bind(this)); this.on("changeFold", this.onChangeFold.bind(this)); if (this.bgTokenizer) { this.bgTokenizer.setDocument(this.getDocument()); this.bgTokenizer.start(0); } }; this.getDocument = function() { return this.doc; }; this.$resetRowCache = function(docRrow) { if (!docRrow) { this.$docRowCache = []; this.$screenRowCache = []; return; } var i = this.$getRowCacheIndex(this.$docRowCache, docRrow) + 1; var l = this.$docRowCache.length; this.$docRowCache.splice(i, l); this.$screenRowCache.splice(i, l); }; this.$getRowCacheIndex = function(cacheArray, val) { var low = 0; var hi = cacheArray.length - 1; while (low <= hi) { var mid = (low + hi) >> 1; var c = cacheArray[mid]; if (val > c) low = mid + 1; else if (val < c) hi = mid - 1; else return mid; } return low && low -1; }; this.onChangeFold = function(e) { var fold = e.data; this.$resetRowCache(fold.start.row); }; this.onChange = function(e) { var delta = e.data; this.$modified = true; this.$resetRowCache(delta.range.start.row); var removedFolds = this.$updateInternalDataOnChange(e); if (!this.$fromUndo && this.$undoManager && !delta.ignore) { this.$deltasDoc.push(delta); if (removedFolds && removedFolds.length != 0) { this.$deltasFold.push({ action: "removeFolds", folds: removedFolds }); } this.$informUndoManager.schedule(); } this.bgTokenizer.$updateOnChange(delta); this._emit("change", e); }; this.setValue = function(text) { this.doc.setValue(text); this.selection.moveCursorTo(0, 0); this.selection.clearSelection(); this.$resetRowCache(0); this.$deltas = []; this.$deltasDoc = []; this.$deltasFold = []; this.getUndoManager().reset(); }; /** alias of: EditSession.getValue * EditSession.toString() -> String * * Returns the current [[Document `Document`]] as a string. * **/ this.getValue = this.toString = function() { return this.doc.getValue(); }; this.getSelection = function() { return this.selection; }; this.getState = function(row) { return this.bgTokenizer.getState(row); }; this.getTokens = function(row) { return this.bgTokenizer.getTokens(row); }; this.getTokenAt = function(row, column) { var tokens = this.bgTokenizer.getTokens(row); var token, c = 0; if (column == null) { i = tokens.length - 1; c = this.getLine(row).length; } else { for (var i = 0; i < tokens.length; i++) { c += tokens[i].value.length; if (c >= column) break; } } token = tokens[i]; if (!token) return null; token.index = i; token.start = c - token.value.length; return token; }; this.highlight = function(re) { if (!this.$searchHighlight) { var highlight = new SearchHighlight(null, "ace_selected_word", "text"); this.$searchHighlight = this.addDynamicMarker(highlight); } this.$searchHighlight.setRegexp(re); } /** * EditSession.setUndoManager(undoManager) * - undoManager (UndoManager): The new undo manager * * Sets the undo manager. **/ this.setUndoManager = function(undoManager) { this.$undoManager = undoManager; this.$deltas = []; this.$deltasDoc = []; this.$deltasFold = []; if (this.$informUndoManager) this.$informUndoManager.cancel(); if (undoManager) { var self = this; this.$syncInformUndoManager = function() { self.$informUndoManager.cancel(); if (self.$deltasFold.length) { self.$deltas.push({ group: "fold", deltas: self.$deltasFold }); self.$deltasFold = []; } if (self.$deltasDoc.length) { self.$deltas.push({ group: "doc", deltas: self.$deltasDoc }); self.$deltasDoc = []; } if (self.$deltas.length > 0) { undoManager.execute({ action: "aceupdate", args: [self.$deltas, self] }); } self.$deltas = []; } this.$informUndoManager = lang.deferredCall(this.$syncInformUndoManager); } }; this.$defaultUndoManager = { undo: function() {}, redo: function() {}, reset: function() {} }; this.getUndoManager = function() { return this.$undoManager || this.$defaultUndoManager; }, /** * EditSession.getTabString() -> String * * Returns the current value for tabs. If the user is using soft tabs, this will be a series of spaces (defined by [[EditSession.getTabSize `getTabSize()`]]); otherwise it's simply `'\t'`. **/ this.getTabString = function() { if (this.getUseSoftTabs()) { return lang.stringRepeat(" ", this.getTabSize()); } else { return "\t"; } }; this.$useSoftTabs = true; this.setUseSoftTabs = function(useSoftTabs) { if (this.$useSoftTabs === useSoftTabs) return; this.$useSoftTabs = useSoftTabs; }; this.getUseSoftTabs = function() { return this.$useSoftTabs; }; this.$tabSize = 4; this.setTabSize = function(tabSize) { if (isNaN(tabSize) || this.$tabSize === tabSize) return; this.$modified = true; this.$rowLengthCache = []; this.$tabSize = tabSize; this._emit("changeTabSize"); }; this.getTabSize = function() { return this.$tabSize; }; this.isTabStop = function(position) { return this.$useSoftTabs && (position.column % this.$tabSize == 0); }; this.$overwrite = false; this.setOverwrite = function(overwrite) { if (this.$overwrite == overwrite) return; this.$overwrite = overwrite; this._emit("changeOverwrite"); }; this.getOverwrite = function() { return this.$overwrite; }; this.toggleOverwrite = function() { this.setOverwrite(!this.$overwrite); }; this.getBreakpoints = function() { return this.$breakpoints; }; this.setBreakpoints = function(rows) { this.$breakpoints = []; for (var i=0; i<rows.length; i++) { this.$breakpoints[rows[i]] = true; } this._emit("changeBreakpoint", {}); }; this.clearBreakpoints = function() { this.$breakpoints = []; this._emit("changeBreakpoint", {}); }; this.setBreakpoint = function(row) { this.$breakpoints[row] = true; this._emit("changeBreakpoint", {}); }; this.clearBreakpoint = function(row) { delete this.$breakpoints[row]; this._emit("changeBreakpoint", {}); }; this.addMarker = function(range, clazz, type, inFront) { var id = this.$markerId++; var marker = { range : range, type : type || "line", renderer: typeof type == "function" ? type : null, clazz : clazz, inFront: !!inFront, id: id } if (inFront) { this.$frontMarkers[id] = marker; this._emit("changeFrontMarker") } else { this.$backMarkers[id] = marker; this._emit("changeBackMarker") } return id; }; this.addDynamicMarker = function(marker, inFront) { if (!marker.update) return; var id = this.$markerId++; marker.id = id; marker.inFront = !!inFront; if (inFront) { this.$frontMarkers[id] = marker; this._emit("changeFrontMarker") } else { this.$backMarkers[id] = marker; this._emit("changeBackMarker") } return marker; }; this.removeMarker = function(markerId) { var marker = this.$frontMarkers[markerId] || this.$backMarkers[markerId]; if (!marker) return; var markers = marker.inFront ? this.$frontMarkers : this.$backMarkers; if (marker) { delete (markers[markerId]); this._emit(marker.inFront ? "changeFrontMarker" : "changeBackMarker"); } }; this.getMarkers = function(inFront) { return inFront ? this.$frontMarkers : this.$backMarkers; }; /** * EditSession.setAnnotations(annotations) * - annotations (Array): A list of annotations * * Sets annotations for the `EditSession`. This functions emits the `'changeAnnotation'` event. **/ 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._emit("changeAnnotation", {}); }; this.getAnnotations = function() { return this.$annotations || {}; }; this.clearAnnotations = function() { this.$annotations = {}; this._emit("changeAnnotation", {}); }; this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r?\n)/m); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getWordRange = function(row, column) { var line = this.getLine(row); var inToken = false; if (column > 0) inToken = !!line.charAt(column - 1).match(this.tokenRe); if (!inToken) inToken = !!line.charAt(column).match(this.tokenRe); if (inToken) var re = this.tokenRe; else if (/^\s+$/.test(line.slice(column-1, column+1))) var re = /\s/; else var re = this.nonTokenRe; var start = column; if (start > 0) { do { start--; } while (start >= 0 && line.charAt(start).match(re)); start++; } var end = column; while (end < line.length && line.charAt(end).match(re)) { end++; } return new Range(row, start, row, end); }; this.getAWordRange = function(row, column) { var wordRange = this.getWordRange(row, column); var line = this.getLine(wordRange.end.row); while (line.charAt(wordRange.end.column).match(/[ \t]/)) { wordRange.end.column += 1; } return wordRange; }; this.setNewLineMode = function(newLineMode) { this.doc.setNewLineMode(newLineMode); }; this.getNewLineMode = function() { return this.doc.getNewLineMode(); }; this.$useWorker = true; this.setUseWorker = function(useWorker) { if (this.$useWorker == useWorker) return; this.$useWorker = useWorker; this.$stopWorker(); if (useWorker) this.$startWorker(); }; this.getUseWorker = function() { return this.$useWorker; }; this.onReloadTokenizer = function(e) { var rows = e.data; this.bgTokenizer.start(rows.first); this._emit("tokenizerUpdate", e); }; this.$modes = {}; this._loadMode = function(mode, callback) { if (!this.$modes["null"]) this.$modes["null"] = this.$modes["ace/mode/text"] = new TextMode(); if (this.$modes[mode]) return callback(this.$modes[mode]); var _self = this; var module; try { module = require(mode); } catch (e) {}; if (module) return done(module); // set mode to text until loading is finished if (!this.$mode) this.$setModePlaceholder(); fetch(function() { require([mode], done); }); function done(module) { if (_self.$modes[mode]) return callback(_self.$modes[mode]); _self.$modes[mode] = new module.Mode(); _self.$modes[mode].$id = mode; _self._emit("loadmode", { name: mode, mode: _self.$modes[mode] }); callback(_self.$modes[mode]); } function fetch(callback) { if (!config.get("packaged")) return callback(); var base = mode.split("/").pop(); var filename = config.get("modePath") + "/mode-" + base + ".js"; net.loadScript(filename, callback); } }; this.$setModePlaceholder = function() { this.$mode = this.$modes["null"]; var tokenizer = this.$mode.getTokenizer(); if (!this.bgTokenizer) { this.bgTokenizer = new BackgroundTokenizer(tokenizer); var _self = this; this.bgTokenizer.addEventListener("update", function(e) { _self._emit("tokenizerUpdate", e); }); } else { this.bgTokenizer.setTokenizer(tokenizer); } this.bgTokenizer.setDocument(this.getDocument()); this.tokenRe = this.$mode.tokenRe; this.nonTokenRe = this.$mode.nonTokenRe; }; this.$mode = null; this.$modeId = null; this.setMode = function(mode) { mode = mode || "null"; // load on demand if (typeof mode === "string") { if (this.$modeId == mode) return; this.$modeId = mode; var _self = this; this._loadMode(mode, function(module) { if (_self.$modeId !== mode) return; _self.setMode(module); }); return; } if (this.$mode === mode) return; this.$mode = mode; this.$modeId = mode.$id; this.$stopWorker(); if (this.$useWorker) this.$startWorker(); var tokenizer = mode.getTokenizer(); if(tokenizer.addEventListener !== undefined) { var onReloadTokenizer = this.onReloadTokenizer.bind(this); tokenizer.addEventListener("update", onReloadTokenizer); } if (!this.bgTokenizer) { this.bgTokenizer = new BackgroundTokenizer(tokenizer); var _self = this; this.bgTokenizer.addEventListener("update", function(e) { _self._emit("tokenizerUpdate", e); }); } else { this.bgTokenizer.setTokenizer(tokenizer); } this.bgTokenizer.setDocument(this.getDocument()); this.bgTokenizer.start(0); this.tokenRe = mode.tokenRe; this.nonTokenRe = mode.nonTokenRe; this.$setFolding(mode.foldingRules); this._emit("changeMode"); }; this.$stopWorker = function() { if (this.$worker) this.$worker.terminate(); this.$worker = null; }; this.$startWorker = function() { if (typeof Worker !== "undefined" && !require.noWorker) { try { this.$worker = this.$mode.createWorker(this); } catch (e) { console.log("Could not load worker"); console.log(e); this.$worker = null; } } else this.$worker = null; }; this.getMode = function() { return this.$mode; }; this.$scrollTop = 0; this.setScrollTop = function(scrollTop) { scrollTop = Math.round(Math.max(0, scrollTop)); if (this.$scrollTop === scrollTop) return; this.$scrollTop = scrollTop; this._emit("changeScrollTop", scrollTop); }; this.getScrollTop = function() { return this.$scrollTop; }; this.$scrollLeft = 0; this.setScrollLeft = function(scrollLeft) { scrollLeft = Math.round(Math.max(0, scrollLeft)); if (this.$scrollLeft === scrollLeft) return; this.$scrollLeft = scrollLeft; this._emit("changeScrollLeft", scrollLeft); }; this.getScrollLeft = function() { return this.$scrollLeft; }; this.getScreenWidth = function() { this.$computeWidth(); return this.screenWidth; }; this.$computeWidth = function(force) { if (this.$modified || force) { this.$modified = false; if (this.$useWrapMode) return this.screenWidth = this.$wrapLimit; var lines = this.doc.getAllLines(); var cache = this.$rowLengthCache; var longestScreenLine = 0; var foldIndex = 0; var foldLine = this.$foldData[foldIndex]; var foldStart = foldLine ? foldLine.start.row : Infinity; var len = lines.length; for (var i = 0; i < len; i++) { if (i > foldStart) { i = foldLine.end.row + 1; if (i >= len) break foldLine = this.$foldData[foldIndex++]; foldStart = foldLine ? foldLine.start.row : Infinity; } if (cache[i] == null) cache[i] = this.$getStringScreenWidth(lines[i])[0]; if (cache[i] > longestScreenLine) longestScreenLine = cache[i]; } this.screenWidth = longestScreenLine; } }; this.getLine = function(row) { return this.doc.getLine(row); }; this.getLines = function(firstRow, lastRow) { return this.doc.getLines(firstRow, lastRow); }; this.getLength = function() { return this.doc.getLength(); }; this.getTextRange = function(range) { return this.doc.getTextRange(range || this.selection.getRange()); }; this.insert = function(position, text) { return this.doc.insert(position, text); }; this.remove = function(range) { return this.doc.remove(range); }; this.undoChanges = function(deltas, dontSelect) { if (!deltas.length) return; this.$fromUndo = true; var lastUndoRange = null; for (var i = deltas.length - 1; i != -1; i--) { var delta = deltas[i]; if (delta.group == "doc") { this.doc.revertDeltas(delta.deltas); lastUndoRange = this.$getUndoSelection(delta.deltas, true, lastUndoRange); } else { delta.deltas.forEach(function(foldDelta) { this.addFolds(foldDelta.folds); }, this); } } this.$fromUndo = false; lastUndoRange && this.$undoSelect && !dontSelect && this.selection.setSelectionRange(lastUndoRange); return lastUndoRange; }; this.redoChanges = function(deltas, dontSelect) { if (!deltas.length) return; this.$fromUndo = true; var lastUndoRange = null; for (var i = 0; i < deltas.length; i++) { var delta = deltas[i]; if (delta.group == "doc") { this.doc.applyDeltas(delta.deltas); lastUndoRange = this.$getUndoSelection(delta.deltas, false, lastUndoRange); } } this.$fromUndo = false; lastUndoRange && this.$undoSelect && !dontSelect && this.selection.setSelectionRange(lastUndoRange); return lastUndoRange; }; this.setUndoSelect = function(enable) { this.$undoSelect = enable; }; this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) { function isInsert(delta) { var insert = delta.action == "insertText" || delta.action == "insertLines"; return isUndo ? !insert : insert; } var delta = deltas[0]; var range, point; var lastDeltaIsInsert = false; if (isInsert(delta)) { range = delta.range.clone(); lastDeltaIsInsert = true; } else { range = Range.fromPoints(delta.range.start, delta.range.start); lastDeltaIsInsert = false; } for (var i = 1; i < deltas.length; i++) { delta = deltas[i]; if (isInsert(delta)) { point = delta.range.start; if (range.compare(point.row, point.column) == -1) { range.setStart(delta.range.start); } point = delta.range.end; if (range.compare(point.row, point.column) == 1) { range.setEnd(delta.range.end); } lastDeltaIsInsert = true; } else { point = delta.range.start; if (range.compare(point.row, point.column) == -1) { range = Range.fromPoints(delta.range.start, delta.range.start); } lastDeltaIsInsert = false; } } // Check if this range and the last undo range has something in common. // If true, merge the ranges. if (lastUndoRange != null) { var cmp = lastUndoRange.compareRange(range); if (cmp == 1) { range.setStart(lastUndoRange.start); } else if (cmp == -1) { range.setEnd(lastUndoRange.end); } } return range; }, /** related to: Document.replace * EditSession.replace(range, text) -> Object * - range (Range): A specified Range to replace * - text (String): The new text to use as a replacement * + (Object): Returns an object containing the final row and column, like this:<br/> * ```{row: endRow, column: 0}```<br/> * If the text and range are empty, this function returns an object containing the current `range.start` value.<br/> * If the text is the exact same as what currently exists, this function returns an object containing the current `range.end` value. * * Replaces a range in the document with the new `text`. * * * **/ this.replace = function(range, text) { return this.doc.replace(range, text); }; this.moveText = function(fromRange, toPosition) { var text = this.getTextRange(fromRange); this.remove(fromRange); var toRow = toPosition.row; var toColumn = toPosition.column; // Make sure to update the insert location, when text is removed in // front of the chosen point of insertion. if (!fromRange.isMultiLine() && fromRange.start.row == toRow && fromRange.end.column < toColumn) toColumn -= text.length; if (fromRange.isMultiLine() && fromRange.end.row < toRow) { var lines = this.doc.$split(text); toRow -= lines.length - 1; } var endRow = toRow + fromRange.end.row - fromRange.start.row; var endColumn = fromRange.isMultiLine() ? fromRange.end.column : toColumn + fromRange.end.column - fromRange.start.column; var toRange = new Range(toRow, toColumn, endRow, endColumn); this.insert(toRange.start, text); return toRange; }; this.indentRows = function(startRow, endRow, indentString) { indentString = indentString.replace(/\t/g, this.getTabString()); for (var row=startRow; row<=endRow; row++) this.insert({row: row, column:0}, indentString); }; this.outdentRows = function (range) { var rowRange = range.collapseRows(); var deleteRange = new Range(0, 0, 0, 0); var size = this.getTabSize(); for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) { var line = this.getLine(i); deleteRange.start.row = i; deleteRange.end.row = i; for (var j = 0; j < size; ++j) if (line.charAt(j) != ' ') break; if (j < size && line.charAt(j) == '\t') { deleteRange.start.column = j; deleteRange.end.column = j + 1; } else { deleteRange.start.column = 0; deleteRange.end.column = j; } this.remove(deleteRange); } }; this.moveLinesUp = function(firstRow, lastRow) { if (firstRow <= 0) return 0; var removed = this.doc.removeLines(firstRow, lastRow); this.doc.insertLines(firstRow - 1, removed); return -1; }; this.moveLinesDown = function(firstRow, lastRow) { if (lastRow >= this.doc.getLength()-1) return 0; var removed = this.doc.removeLines(firstRow, lastRow); this.doc.insertLines(firstRow+1, removed); return 1; }; this.duplicateLines = function(firstRow, lastRow) { var firstRow = this.$clipRowToDocument(firstRow); var lastRow = this.$clipRowToDocument(lastRow); var lines = this.getLines(firstRow, lastRow); this.doc.insertLines(firstRow, lines); var addedRows = lastRow - firstRow + 1; return addedRows; }; this.$clipRowToDocument = function(row) { return Math.max(0, Math.min(row, this.doc.getLength()-1)); }; this.$clipColumnToRow = function(row, column) { if (column < 0) return 0; return Math.min(this.doc.getLine(row).length, column); }; this.$clipPositionToDocument = function(row, column) { column = Math.max(0, column); if (row < 0) { row = 0; column = 0; } else { var len = this.doc.getLength(); if (row >= len) { row = len - 1; column = this.doc.getLine(len-1).length; } else { column = Math.min(this.doc.getLine(row).length, column); } } return { row: row, column: column }; }; this.$clipRangeToDocument = function(range) { if (range.start.row < 0) { range.start.row = 0; range.start.column = 0 } else { range.start.column = this.$clipColumnToRow( range.start.row, range.start.column ); } var len = this.doc.getLength() - 1; if (range.end.row > len) { range.end.row = len; range.end.column = this.doc.getLine(len).length; } else { range.end.column = this.$clipColumnToRow( range.end.row, range.end.column ); } return range; }; // WRAPMODE this.$wrapLimit = 80; this.$useWrapMode = false; this.$wrapLimitRange = { min : null, max : null }; this.setUseWrapMode = function(useWrapMode) { if (useWrapMode != this.$useWrapMode) { this.$useWrapMode = useWrapMode; this.$modified = true; this.$resetRowCache(0); // If wrapMode is activaed, the wrapData array has to be initialized. if (useWrapMode) { var len = this.getLength(); this.$wrapData = []; for (var i = 0; i < len; i++) { this.$wrapData.push([]); } this.$updateWrapData(0, len - 1); } this._emit("changeWrapMode"); } }; this.getUseWrapMode = function() { return this.$useWrapMode; }; // Allow the wrap limit to move freely between min and max. Either // parameter can be null to allow the wrap limit to be unconstrained // in that direction. Or set both parameters to the same number to pin // the limit to that value. /** * EditSession.setWrapLimitRange(min, max) * - min (Number): The minimum wrap value (the left side wrap) * - max (Number): The maximum wrap value (the right side wrap) * * Sets the boundaries of wrap. Either value can be `null` to have an unconstrained wrap, or, they can be the same number to pin the limit. If the wrap limits for `min` or `max` are different, this method also emits the `'changeWrapMode'` event. **/ this.setWrapLimitRange = function(min, max) { if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) { this.$wrapLimitRange.min = min; this.$wrapLimitRange.max = max; this.$modified = true; // This will force a recalculation of the wrap limit this._emit("changeWrapMode"); } }; this.adjustWrapLimit = function(desiredLimit) { var wrapLimit = this.$constrainWrapLimit(desiredLimit); if (wrapLimit != this.$wrapLimit && wrapLimit > 0) { this.$wrapLimit = wrapLimit; this.$modified = true; if (this.$useWrapMode) { this.$updateWrapData(0, this.getLength() - 1); this.$resetRowCache(0) this._emit("changeWrapLimit"); } return true; } return false; }; this.$constrainWrapLimit = function(wrapLimit) { var min = this.$wrapLimitRange.min; if (min) wrapLimit = Math.max(min, wrapLimit); var max = this.$wrapLimitRange.max; if (max) wrapLimit = Math.min(max, wrapLimit); // What would a limit of 0 even mean? return Math.max(1, wrapLimit); }; this.getWrapLimit = function() { return this.$wrapLimit; }; this.getWrapLimitRange = function() { // Avoid unexpected mutation by returning a copy return { min : this.$wrapLimitRange.min, max : this.$wrapLimitRange.max }; }; this.$updateInternalDataOnChange = function(e) { var useWrapMode = this.$useWrapMode; var len; var action = e.data.action; var firstRow = e.data.range.start.row; var lastRow = e.data.range.end.row; var start = e.data.range.start; var end = e.data.range.end; var removedFolds = null; if (action.indexOf("Lines") != -1) { if (action == "insertLines") { lastRow = firstRow + (e.data.lines.length); } else { lastRow = firstRow; } len = e.data.lines ? e.data.lines.length : lastRow - firstRow; } else { len = lastRow - firstRow; } if (len != 0) { if (action.indexOf("remove") != -1) { this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len); var foldLines = this.$foldData; removedFolds = this.getFoldsInRange(e.data.range); this.removeFolds(removedFolds); var foldLine = this.getFoldLine(end.row); var idx = 0; if (foldLine) { foldLine.addRemoveChars(end.row, end.column, start.column - end.column); foldLine.shiftRow(-len); var foldLineBefore = this.getFoldLine(firstRow); if (foldLineBefore && foldLineBefore !== foldLine) { foldLineBefore.merge(foldLine); foldLine = foldLineBefore; } idx = foldLines.indexOf(foldLine) + 1; } for (idx; idx < foldLines.length; idx++) { var foldLine = foldLines[idx]; if (foldLine.start.row >= end.row) { foldLine.shiftRow(-len); } } lastRow = firstRow; } else { var args; if (useWrapMode) { args = [firstRow, 0]; for (var i = 0; i < len; i++) args.push([]); this.$wrapData.splice.apply(this.$wrapData, args); } else { args = Array(len); args.unshift(firstRow, 0); this.$rowLengthCache.splice.apply(this.$rowLengthCache, args); } // If some new line is added inside of a foldLine, then split // the fold line up. var foldLines = this.$foldData; var foldLine = this.getFoldLine(firstRow); var idx = 0; if (foldLine) { var cmp = foldLine.range.compareInside(start.row, start.column) // Inside of the foldLine range. Need to split stuff up. if (cmp == 0) { foldLine = foldLine.split(start.row, start.column); foldLine.shiftRow(len); foldLine.addRemoveChars( lastRow, 0, end.column - start.column); } else // Infront of the foldLine but same row. Need to shift column. if (cmp == -1) { foldLine.addRemoveChars(firstRow, 0, end.column - start.column); foldLine.shiftRow(len); } // Nothing to do if the insert is after the foldLine. idx = foldLines.indexOf(foldLine) + 1; } for (idx; idx < foldLines.length; idx++) { var foldLine = foldLines[idx]; if (foldLine.start.row >= firstRow) { foldLine.shiftRow(len); } } } } else { // Realign folds. E.g. if you add some new chars before a fold, the // fold should "move" to the right. len = Math.abs(e.data.range.start.column - e.data.range.end.column); if (action.indexOf("remove") != -1) { // Get all the folds in the change range and remove them. removedFolds = this.getFoldsInRange(e.data.range); this.removeFolds(removedFolds); len = -len; } var foldLine = this.getFoldLine(firstRow); if (foldLine) { foldLine.addRemoveChars(firstRow, start.column, len); } } if (useWrapMode && this.$wrapData.length != this.doc.getLength()) { console.error("doc.getLength() and $wrapData.length have to be the same!"); } if (useWrapMode) this.$updateWrapData(firstRow, lastRow); else this.$updateRowLengthCache(firstRow, lastRow); return removedFolds; }; this.$updateRowLengthCache = function(firstRow, lastRow, b) { //console.log(firstRow, lastRow, b) this.$rowLengthCache[firstRow] = null; this.$rowLengthCache[lastRow] = null; //console.log(this.$rowLengthCache) }; this.$updateWrapData = function(firstRow, lastRow) { var lines = this.doc.getAllLines(); var tabSize = this.getTabSize(); var wrapData = this.$wrapData; var wrapLimit = this.$wrapLimit; var tokens; var foldLine; var row = firstRow; lastRow = Math.min(lastRow, lines.length - 1); while (row <= lastRow) { foldLine = this.getFoldLine(row, foldLine); if (!foldLine) { tokens = this.$getDisplayTokens(lang.stringTrimRight(lines[row])); wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); row ++; } else { tokens = []; foldLine.walk( function(placeholder, row, column, lastColumn) { var walkTokens; if (placeholder) { walkTokens = this.$getDisplayTokens( placeholder, tokens.length); walkTokens[0] = PLACEHOLDER_START; for (var i = 1; i < walkTokens.length; i++) { walkTokens[i] = PLACEHOLDER_BODY; } } else { walkTokens = this.$getDisplayTokens( lines[row].substring(lastColumn, column), tokens.length); } tokens = tokens.concat(walkTokens); }.bind(this), foldLine.end.row, lines[foldLine.end.row].length + 1 ); // Remove spaces/tabs from the back of the token array. while (tokens.length != 0 && tokens[tokens.length - 1] >= SPACE) tokens.pop(); wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); row = foldLine.end.row + 1; } } }; // "Tokens" var CHAR = 1, CHAR_EXT = 2, PLACEHOLDER_START = 3, PLACEHOLDER_BODY = 4, PUNCTUATION = 9, SPACE = 10, TAB = 11, TAB_SPACE = 12; this.$computeWrapSplits = function(tokens, wrapLimit) { if (tokens.length == 0) { return []; } var splits = []; var displayLength = tokens.length; var lastSplit = 0, lastDocSplit = 0; function addSplit(screenPos) { var displayed = tokens.slice(lastSplit, screenPos); // The document size is the current size - the extra width for tabs // and multipleWidth characters. var len = displayed.length; displayed.join(""). // Get all the TAB_SPACEs. replace(/12/g, function() { len -= 1; }). // Get all the CHAR_EXT/multipleWidth characters. replace(/2/g, function() { len -= 1; }); lastDocSplit += len; splits.push(lastDocSplit); lastSplit = screenPos; } while (displayLength - lastSplit > wrapLimit) { // This is, where the split should be. var split = lastSplit + wrapLimit; // If there is a space or tab at this split position, then making // a split is simple. if (tokens[split] >= SPACE) { // Include all following spaces + tabs in this split as well. while (tokens[split] >= SPACE) { split ++; } addSplit(split); continue; } // === ELSE === // Check if split is inside of a placeholder. Placeholder are // not splitable. Therefore, seek the beginning of the placeholder // and try to place the split beofre the placeholder's start. if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) { // Seek the start of the placeholder and do the split // before the placeholder. By definition there always // a PLACEHOLDER_START between split and lastSplit. for (split; split != lastSplit - 1; split--) { if (tokens[split] == PLACEHOLDER_START) { // split++; << No incremental here as we want to // have the position before the Placeholder. break; } } // If the PLACEHOLDER_START is not the index of the // last split, then we can do the split if (split > lastSplit) { addSplit(split); continue; } // If the PLACEHOLDER_START IS the index of the last // split, then we have to place the split after the // placeholder. So, let's seek for the end of the placeholder. split = lastSplit + wrapLimit; for (split; split < tokens.length; split++) { if (tokens[split] != PLACEHOLDER_BODY) { break; } } // If spilt == tokens.length, then the placeholder is the last // thing in the line and adding a new split doesn't make sense. if (split == tokens.length) { break; // Breaks the while-loop. } // Finally, add the split... addSplit(split); continue; } // === ELSE === // Search for the first non space/tab/placeholder/punctuation token backwards. var minSplit = Math.max(split - 10, lastSplit - 1); while (split > minSplit && tokens[split] < PLACEHOLDER_START) { split --; } while (split > minSplit && tokens[split] == PUNCTUATION) { split --; } // If we found one, then add the split. if (split > minSplit) { addSplit(++split); continue; } // === ELSE === split = lastSplit + wrapLimit; // The split is inside of a CHAR or CHAR_EXT token and no space // around -> force a split. addSplit(split); } return splits; } /** internal, hide * EditSession.$getDisplayTokens(str, offset) -> Array * - str (String): The string to check * - offset (Number): The value to start at * * Given a string, returns an array of the display characters, including tabs and spaces. **/ this.$getDisplayTokens = function(str, offset) { var arr = []; var tabSize; offset = offset || 0; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); // Tab if (c == 9) { tabSize = this.getScreenTabSize(arr.length + offset); arr.push(TAB); for (var n = 1; n < tabSize; n++) { arr.push(TAB_SPACE); } } // Space else if (c == 32) { arr.push(SPACE); } else if((c > 39 && c < 48) || (c > 57 && c < 64)) { arr.push(PUNCTUATION); } // full width characters else if (c >= 0x1100 && isFullWidth(c)) { arr.push(CHAR, CHAR_EXT); } else { arr.push(CHAR); } } return arr; } /** internal, hide * EditSession.$getStringScreenWidth(str, maxScreenColumn, screenColumn) -> [Number] * - str (String): The string to calculate the screen width of * - maxScreenColumn (Number): * - screenColumn (Number): * + ([Number]): Returns an `int[]` array with two elements:<br/> * The first position indicates the number of columns for `str` on screen.<br/> * The second value contains the position of the document column that this function read until. * * Calculates the width of the string `str` on the screen while assuming that the string starts at the first column on the screen. * * **/ this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { if (maxScreenColumn == 0) return [0, 0]; if (maxScreenColumn == null) maxScreenColumn = Infinity; screenColumn = screenColumn || 0; var c, column; for (column = 0; column < str.length; column++) { c = str.charCodeAt(column); // tab if (c == 9) { screenColumn += this.getScreenTabSize(screenColumn); } // full width characters else if (c >= 0x1100 && isFullWidth(c)) { screenColumn += 2; } else { screenColumn += 1; } if (screenColumn > maxScreenColumn) { break } } return [screenColumn, column]; } /** * EditSession.getRowLength(row) -> Number * - row (Number): The row number to check * * * Returns the length of the indicated row. **/ this.getRowLength = function(row) { if (!this.$useWrapMode || !this.$wrapData[row]) { return 1; } else { return this.$wrapData[row].length + 1; } } /** * EditSession.getRowHeight(config, row) -> Number * - config (Object): An object containing a parameter indicating the `lineHeight`. * - row (Number): The row number to check * * Returns the height of the indicated row. This is mostly relevant for situations where wrapping occurs, and a single line spans across multiple rows. * **/ this.getRowHeight = function(config, row) { return this.getRowLength(row) * config.lineHeight; } /** internal, hide, related to: EditSession.documentToScreenColumn * EditSession.getScreenLastRowColumn(screenRow) -> Number * - screenRow (Number): The screen row to check * * Returns the column position (on screen) for the last character in the provided row. **/ this.getScreenLastRowColumn = function(screenRow) { var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE) return this.documentToScreenColumn(pos.row, pos.column); }; this.getDocumentLastRowColumn = function(docRow, docColumn) { var screenRow = this.documentToScreenRow(docRow, docColumn); return this.getScreenLastRowColumn(screenRow); }; this.getDocumentLastRowColumnPosition = function(docRow, docColumn) { var screenRow = this.documentToScreenRow(docRow, docColumn); return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10); }; this.getRowSplitData = function(row) { if (!this.$useWrapMode) { return undefined; } else { return this.$wrapData[row]; } }; this.getScreenTabSize = function(screenColumn) { return this.$tabSize - screenColumn % this.$tabSize; }; this.screenToDocumentRow = function(screenRow, screenColumn) { return this.screenToDocumentPosition(screenRow, screenColumn).row; }; this.screenToDocumentColumn = function(screenRow, screenColumn) { return this.screenToDocumentPosition(screenRow, screenColumn).column; }; this.screenToDocumentPosition = function(screenRow, screenColumn) { if (screenRow < 0) return {row: 0, column: 0}; var line; var docRow = 0; var docColumn = 0; var column; var row = 0; var rowLength = 0; var rowCache = this.$screenRowCache; var i = this.$getRowCacheIndex(rowCache, screenRow); var row1 = rowCache[i]; var docRow1 = this.$docRowCache[i]; if (0 < i && i < rowCache.length) { var row = rowCache[i]; var docRow = this.$docRowCache[i]; var doCache = screenRow > row || (screenRow == row && i == rowCache.length - 1); } else { var doCache = true; } var maxRow = this.getLength() - 1; var foldLine = this.getNextFoldLine(docRow); var foldStart = foldLine ? foldLine.start.row : Infinity; while (row <= screenRow) { rowLength = this.getRowLength(docRow); if (row + rowLength - 1 >= screenRow || docRow >= maxRow) { break; } else { row += rowLength; docRow++; if (docRow > foldStart) { docRow = foldLine.end.row+1; foldLine = this.getNextFoldLine(docRow, foldLine); foldStart = foldLine ? foldLine.start.row : Infinity; } } if (doCache) { this.$docRowCache.push(docRow); this.$screenRowCache.push(row); } } if (foldLine && foldLine.start.row <= docRow) { line = this.getFoldDisplayLine(foldLine); docRow = foldLine.start.row; } else if (row + rowLength <= screenRow || docRow > maxRow) { // clip at the end of the document return { row: maxRow, column: this.getLine(maxRow).length } } else { line = this.getLine(docRow); foldLine = null; } if (this.$useWrapMode) { var splits = this.$wrapData[docRow]; if (splits) { column = splits[screenRow - row]; if(screenRow > row && splits.length) { docColumn = splits[screenRow - row - 1] || splits[splits.length - 1]; line = line.substring(docColumn); } } } docColumn += this.$getStringScreenWidth(line, screenColumn)[1]; // We remove one character at the end so that the docColumn // position returned is not associated to the next row on the screen. if (this.$useWrapMode && docColumn >= column) docColumn = column - 1; if (foldLine) return foldLine.idxToPosition(docColumn); return {row: docRow, column: docColumn}; }; this.documentToScreenPosition = function(docRow, docColumn) { // Normalize the passed in arguments. if (typeof docColumn === "undefined") var pos = this.$clipPositionToDocument(docRow.row, docRow.column); else pos = this.$clipPositionToDocument(docRow, docColumn); docRow = pos.row; docColumn = pos.column; var screenRow = 0; var foldStartRow = null; var fold = null; // Clamp the docRow position in case it's inside of a folded block. fold = this.getFoldAt(docRow, docColumn, 1); if (fold) { docRow = fold.start.row; docColumn = fold.start.column; } var rowEnd, row = 0; var rowCache = this.$docRowCache; var i = this.$getRowCacheIndex(rowCache, docRow); if (0 < i && i < rowCache.length) { var row = rowCache[i]; var screenRow = this.$screenRowCache[i]; var doCache = docRow > row || (docRow == row && i == rowCache.length - 1); } else { var doCache = true; } var foldLine = this.getNextFoldLine(row); var foldStart = foldLine ?foldLine.start.row :Infinity; while (row < docRow) { if (row >= foldStart) { rowEnd = foldLine.end.row + 1; if (rowEnd > docRow) break; foldLine = this.getNextFoldLine(rowEnd, foldLine); foldStart = foldLine ?foldLine.start.row :Infinity; } else { rowEnd = row + 1; } screenRow += this.getRowLength(row); row = rowEnd; if (doCache) { this.$docRowCache.push(row); this.$screenRowCache.push(screenRow); } } // Calculate the text line that is displayed in docRow on the screen. var textLine = ""; // Check if the final row we want to reach is inside of a fold. if (foldLine && row >= foldStart) { textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn); foldStartRow = foldLine.start.row; } else { textLine = this.getLine(docRow).substring(0, docColumn); foldStartRow = docRow; } // Clamp textLine if in wrapMode. if (this.$useWrapMode) { var wrapRow = this.$wrapData[foldStartRow]; var screenRowOffset = 0; while (textLine.length >= wrapRow[screenRowOffset]) { screenRow ++; screenRowOffset++; } textLine = textLine.substring( wrapRow[screenRowOffset - 1] || 0, textLine.length ); } return { row: screenRow, column: this.$getStringScreenWidth(textLine)[0] }; }; this.documentToScreenColumn = function(row, docColumn) { return this.documentToScreenPosition(row, docColumn).column; }; this.documentToScreenRow = function(docRow, docColumn) { return this.documentToScreenPosition(docRow, docColumn).row; }; this.getScreenLength = function() { var screenRows = 0; var fold = null; if (!this.$useWrapMode) { screenRows = this.getLength(); // Remove the folded lines again. var foldData = this.$foldData; for (var i = 0; i < foldData.length; i++) { fold = foldData[i]; screenRows -= fold.end.row - fold.start.row; } } else { var lastRow = this.$wrapData.length; var row = 0, i = 0; var fold = this.$foldData[i++]; var foldStart = fold ? fold.start.row :Infinity; while (row < lastRow) { screenRows += this.$wrapData[row].length + 1; row ++; if (row > foldStart) { row = fold.end.row+1; fold = this.$foldData[i++]; foldStart = fold ?fold.start.row :Infinity; } } } return screenRows; } // For every keystroke this gets called once per char in the whole doc!! // Wouldn't hurt to make it a bit faster for c >= 0x1100 function isFullWidth(c) { if (c < 0x1100) return false; return c >= 0x1100 && c <= 0x115F || c >= 0x11A3 && c <= 0x11A7 || c >= 0x11FA && c <= 0x11FF || c >= 0x2329 && c <= 0x232A || c >= 0x2E80 && c <= 0x2E99 || c >= 0x2E9B && c <= 0x2EF3 || c >= 0x2F00 && c <= 0x2FD5 || c >= 0x2FF0 && c <= 0x2FFB || c >= 0x3000 && c <= 0x303E || c >= 0x3041 && c <= 0x3096 || c >= 0x3099 && c <= 0x30FF || c >= 0x3105 && c <= 0x312D || c >= 0x3131 && c <= 0x318E || c >= 0x3190 && c <= 0x31BA || c >= 0x31C0 && c <= 0x31E3 || c >= 0x31F0 && c <= 0x321E || c >= 0x3220 && c <= 0x3247 || c >= 0x3250 && c <= 0x32FE || c >= 0x3300 && c <= 0x4DBF || c >= 0x4E00 && c <= 0xA48C || c >= 0xA490 && c <= 0xA4C6 || c >= 0xA960 && c <= 0xA97C || c >= 0xAC00 && c <= 0xD7A3 || c >= 0xD7B0 && c <= 0xD7C6 || c >= 0xD7CB && c <= 0xD7FB || c >= 0xF900 && c <= 0xFAFF || c >= 0xFE10 && c <= 0xFE19 || c >= 0xFE30 && c <= 0xFE52 || c >= 0xFE54 && c <= 0xFE66 || c >= 0xFE68 && c <= 0xFE6B || c >= 0xFF01 && c <= 0xFF60 || c >= 0xFFE0 && c <= 0xFFE6; }; }).call(EditSession.prototype); require("./edit_session/folding").Folding.call(EditSession.prototype); require("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype); exports.EditSession = EditSession; }); define('ace/config', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { "no use strict"; var lang = require("./lib/lang"); var global = (function() { return this; })(); var options = { packaged: false, workerPath: "", modePath: "", themePath: "", suffix: ".js" }; exports.get = function(key) { if (!options.hasOwnProperty(key)) throw new Error("Unknown config key: " + key); return options[key]; }; exports.set = function(key, value) { if (!options.hasOwnProperty(key)) throw new Error("Unknown config key: " + key); options[key] = value; }; exports.all = function() { return lang.copyObject(options); }; exports.init = function() { options.packaged = require.packaged || module.packaged || (global.define && define.packaged); if (!global.document) return ""; var scriptOptions = {}; var scriptUrl = ""; var scripts = document.getElementsByTagName("script"); for (var i=0; i<scripts.length; i++) { var script = scripts[i]; var src = script.src || script.getAttribute("src"); if (!src) { continue; } var attributes = script.attributes; for (var j=0, l=attributes.length; j < l; j++) { var attr = attributes[j]; if (attr.name.indexOf("data-ace-") === 0) { scriptOptions[deHyphenate(attr.name.replace(/^data-ace-/, ""))] = attr.value; } } var m = src.match(/^(?:(.*\/)ace\.js)(?:\?|$)/); if (m) { scriptUrl = m[1] || m[2]; } } if (scriptUrl) { scriptOptions.base = scriptOptions.base || scriptUrl; scriptOptions.packaged = true; } scriptOptions.workerPath = scriptOptions.workerPath || scriptOptions.base; scriptOptions.modePath = scriptOptions.modePath || scriptOptions.base; scriptOptions.themePath = scriptOptions.themePath || scriptOptions.base; delete scriptOptions.base; for (var key in scriptOptions) if (typeof scriptOptions[key] !== "undefined") exports.set(key, scriptOptions[key]); }; function deHyphenate(str) { return str.replace(/-(.)/g, function(m, m1) { return m1.toUpperCase(); }); } }); define('ace/lib/net', ['require', 'exports', 'module' ], function(require, exports, module) { exports.get = function (url, callback) { var xhr = exports.createXhr(); xhr.open('GET', url, true); xhr.onreadystatechange = function (evt) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { callback(xhr.responseText); } }; xhr.send(null); }; var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0']; exports.createXhr = function() { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else { for (i = 0; i < 3; i++) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } if (!xhr) { throw new Error("createXhr(): XMLHttpRequest not available"); } return xhr; }; exports.loadScript = function(path, callback) { var head = document.getElementsByTagName('head')[0]; var s = document.createElement('script'); s.src = path; head.appendChild(s); s.onload = callback; }; }); define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { var EventEmitter = {}; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry = this._eventRegistry || {}; this._defaultHandlers = this._defaultHandlers || {}; var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; e = e || {}; e.type = eventName; if (!e.stopPropagation) { e.stopPropagation = function() { this.propagationStopped = true; }; } if (!e.preventDefault) { e.preventDefault = function() { this.defaultPrevented = true; }; } for (var i=0; i<listeners.length; i++) { listeners[i](e); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e); }; EventEmitter.setDefaultHandler = function(eventName, callback) { this._defaultHandlers = this._defaultHandlers || {}; if (this._defaultHandlers[eventName]) throw new Error("The default handler for '" + eventName + "' is already set"); this._defaultHandlers[eventName] = callback; }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) var listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners.push(callback); }; EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); define('ace/selection', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/event_emitter', 'ace/range'], function(require, exports, module) { var oop = require("./lib/oop"); var lang = require("./lib/lang"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; /** * new Selection(session) * - session (EditSession): The session to use * * Creates a new `Selection` object. * **/ var Selection = function(session) { this.session = session; this.doc = session.getDocument(); this.clearSelection(); this.lead = this.selectionLead = this.doc.createAnchor(0, 0); this.anchor = this.selectionAnchor = this.doc.createAnchor(0, 0); var self = this; this.lead.on("change", function(e) { self._emit("changeCursor"); if (!self.$isEmpty) self._emit("changeSelection"); if (!self.$keepDesiredColumnOnChange && e.old.column != e.value.column) self.$desiredColumn = null; }); this.selectionAnchor.on("change", function() { if (!self.$isEmpty) self._emit("changeSelection"); }); }; (function() { oop.implement(this, EventEmitter); this.isEmpty = function() { return (this.$isEmpty || ( this.anchor.row == this.lead.row && this.anchor.column == this.lead.column )); }; this.isMultiLine = function() { if (this.isEmpty()) { return false; } return this.getRange().isMultiLine(); }; this.getCursor = function() { return this.lead.getPosition(); }; this.setSelectionAnchor = function(row, column) { this.anchor.setPosition(row, column); if (this.$isEmpty) { this.$isEmpty = false; this._emit("changeSelection"); } }; this.getSelectionAnchor = function() { if (this.$isEmpty) return this.getSelectionLead() else return this.anchor.getPosition(); }; this.getSelectionLead = function() { return this.lead.getPosition(); }; this.shiftSelection = function(columns) { if (this.$isEmpty) { this.moveCursorTo(this.lead.row, this.lead.column + columns); return; }; var anchor = this.getSelectionAnchor(); var lead = this.getSelectionLead(); var isBackwards = this.isBackwards(); if (!isBackwards || anchor.column !== 0) this.setSelectionAnchor(anchor.row, anchor.column + columns); if (isBackwards || lead.column !== 0) { this.$moveSelection(function() { this.moveCursorTo(lead.row, lead.column + columns); }); } }; this.isBackwards = function() { var anchor = this.anchor; var lead = this.lead; return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column)); }; this.getRange = function() { var anchor = this.anchor; var lead = this.lead; if (this.isEmpty()) return Range.fromPoints(lead, lead); if (this.isBackwards()) { return Range.fromPoints(lead, anchor); } else { return Range.fromPoints(anchor, lead); } }; this.clearSelection = function() { if (!this.$isEmpty) { this.$isEmpty = true; this._emit("changeSelection"); } }; this.selectAll = function() { var lastRow = this.doc.getLength() - 1; this.setSelectionAnchor(0, 0); this.moveCursorTo(lastRow, this.doc.getLine(lastRow).length); }; this.setRange = this.setSelectionRange = function(range, reverse) { if (reverse) { this.setSelectionAnchor(range.end.row, range.end.column); this.selectTo(range.start.row, range.start.column); } else { this.setSelectionAnchor(range.start.row, range.start.column); this.selectTo(range.end.row, range.end.column); } this.$desiredColumn = null; }; this.$moveSelection = function(mover) { var lead = this.lead; if (this.$isEmpty) this.setSelectionAnchor(lead.row, lead.column); mover.call(this); }; this.selectTo = function(row, column) { this.$moveSelection(function() { this.moveCursorTo(row, column); }); }; this.selectToPosition = function(pos) { this.$moveSelection(function() { this.moveCursorToPosition(pos); }); }; this.selectUp = function() { this.$moveSelection(this.moveCursorUp); }; this.selectDown = function() { this.$moveSelection(this.moveCursorDown); }; this.selectRight = function() { this.$moveSelection(this.moveCursorRight); }; this.selectLeft = function() { this.$moveSelection(this.moveCursorLeft); }; this.selectLineStart = function() { this.$moveSelection(this.moveCursorLineStart); }; this.selectLineEnd = function() { this.$moveSelection(this.moveCursorLineEnd); }; this.selectFileEnd = function() { this.$moveSelection(this.moveCursorFileEnd); }; this.selectFileStart = function() { this.$moveSelection(this.moveCursorFileStart); }; this.selectWordRight = function() { this.$moveSelection(this.moveCursorWordRight); }; this.selectWordLeft = function() { this.$moveSelection(this.moveCursorWordLeft); }; this.getWordRange = function(row, column) { if (typeof column == "undefined") { var cursor = row || this.lead; row = cursor.row; column = cursor.column; } return this.session.getWordRange(row, column); }; this.selectWord = function() { this.setSelectionRange(this.getWordRange()); }; this.selectAWord = function() { var cursor = this.getCursor(); var range = this.session.getAWordRange(cursor.row, cursor.column); this.setSelectionRange(range); }; this.getLineRange = function(row, excludeLastChar) { var rowStart = typeof row == "number" ? row : this.lead.row; var rowEnd; var foldLine = this.session.getFoldLine(rowStart); if (foldLine) { rowStart = foldLine.start.row; rowEnd = foldLine.end.row; } else { rowEnd = rowStart; } if (excludeLastChar) return new Range(rowStart, 0, rowEnd, this.session.getLine(rowEnd).length); else return new Range(rowStart, 0, rowEnd + 1, 0); }; this.selectLine = function() { this.setSelectionRange(this.getLineRange()); }; this.moveCursorUp = function() { this.moveCursorBy(-1, 0); }; this.moveCursorDown = function() { this.moveCursorBy(1, 0); }; this.moveCursorLeft = function() { var cursor = this.lead.getPosition(), fold; if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) { this.moveCursorTo(fold.start.row, fold.start.column); } else if (cursor.column == 0) { // cursor is a line (start if (cursor.row > 0) { this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length); } } else { var tabSize = this.session.getTabSize(); if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize) this.moveCursorBy(0, -tabSize); else this.moveCursorBy(0, -1); } }; this.moveCursorRight = function() { var cursor = this.lead.getPosition(), fold; if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) { this.moveCursorTo(fold.end.row, fold.end.column); } else if (this.lead.column == this.doc.getLine(this.lead.row).length) { if (this.lead.row < this.doc.getLength() - 1) { this.moveCursorTo(this.lead.row + 1, 0); } } else { var tabSize = this.session.getTabSize(); var cursor = this.lead; if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize) this.moveCursorBy(0, tabSize); else this.moveCursorBy(0, 1); } }; this.moveCursorLineStart = function() { var row = this.lead.row; var column = this.lead.column; var screenRow = this.session.documentToScreenRow(row, column); // Determ the doc-position of the first character at the screen line. var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0); // Determ the line var beforeCursor = this.session.getDisplayLine( row, null, firstColumnPosition.row, firstColumnPosition.column ); var leadingSpace = beforeCursor.match(/^\s*/); if (leadingSpace[0].length == column) { this.moveCursorTo( firstColumnPosition.row, firstColumnPosition.column ); } else { this.moveCursorTo( firstColumnPosition.row, firstColumnPosition.column + leadingSpace[0].length ); } }; this.moveCursorLineEnd = function() { var lead = this.lead; var lastRowColumnPosition = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column); this.moveCursorTo( lastRowColumnPosition.row, lastRowColumnPosition.column ); }; this.moveCursorFileEnd = function() { var row = this.doc.getLength() - 1; var column = this.doc.getLine(row).length; this.moveCursorTo(row, column); }; this.moveCursorFileStart = function() { this.moveCursorTo(0, 0); }; this.moveCursorLongWordRight = function() { var row = this.lead.row; var column = this.lead.column; var line = this.doc.getLine(row); var rightOfCursor = line.substring(column); var match; this.session.nonTokenRe.lastIndex = 0; this.session.tokenRe.lastIndex = 0; // skip folds var fold = this.session.getFoldAt(row, column, 1); if (fold) { this.moveCursorTo(fold.end.row, fold.end.column); return; } // first skip space if (match = this.session.nonTokenRe.exec(rightOfCursor)) { column += this.session.nonTokenRe.lastIndex; this.session.nonTokenRe.lastIndex = 0; rightOfCursor = line.substring(column); } // if at line end proceed with next line if (column >= line.length) { this.moveCursorTo(row, line.length); this.moveCursorRight(); if (row < this.doc.getLength() - 1) this.moveCursorWordRight(); return; } // advance to the end of the next token if (match = this.session.tokenRe.exec(rightOfCursor)) { column += this.session.tokenRe.lastIndex; this.session.tokenRe.lastIndex = 0; } this.moveCursorTo(row, column); }; this.moveCursorLongWordLeft = function() { var row = this.lead.row; var column = this.lead.column; // skip folds var fold; if (fold = this.session.getFoldAt(row, column, -1)) { this.moveCursorTo(fold.start.row, fold.start.column); return; } var str = this.session.getFoldStringAt(row, column, -1); if (str == null) { str = this.doc.getLine(row).substring(0, column) } var leftOfCursor = lang.stringReverse(str); var match; this.session.nonTokenRe.lastIndex = 0; this.session.tokenRe.lastIndex = 0; // skip whitespace if (match = this.session.nonTokenRe.exec(leftOfCursor)) { column -= this.session.nonTokenRe.lastIndex; leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex); this.session.nonTokenRe.lastIndex = 0; } // if at begin of the line proceed in line above if (column <= 0) { this.moveCursorTo(row, 0); this.moveCursorLeft(); if (row > 0) this.moveCursorWordLeft(); return; } // move to the begin of the word if (match = this.session.tokenRe.exec(leftOfCursor)) { column -= this.session.tokenRe.lastIndex; this.session.tokenRe.lastIndex = 0; } this.moveCursorTo(row, column); }; this.$shortWordEndIndex = function(rightOfCursor) { var match, index = 0, ch; var whitespaceRe = /\s/; var tokenRe = this.session.tokenRe; tokenRe.lastIndex = 0; if (match = this.session.tokenRe.exec(rightOfCursor)) { index = this.session.tokenRe.lastIndex; } else { while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) index ++; if (index <= 1) { tokenRe.lastIndex = 0; while ((ch = rightOfCursor[index]) && !tokenRe.test(ch)) { tokenRe.lastIndex = 0; index ++; if (whitespaceRe.test(ch)) { if (index > 2) { index-- break; } else { while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch)) index ++; if (index > 2) break } } } } } tokenRe.lastIndex = 0; return index; }; this.moveCursorShortWordRight = function() { var row = this.lead.row; var column = this.lead.column; var line = this.doc.getLine(row); var rightOfCursor = line.substring(column); var fold = this.session.getFoldAt(row, column, 1); if (fold) return this.moveCursorTo(fold.end.row, fold.end.column); if (column == line.length) { var l = this.doc.getLength(); do { row++; rightOfCursor = this.doc.getLine(row) } while (row < l && /^\s*$/.test(rightOfCursor)) if (!/^\s+/.test(rightOfCursor)) rightOfCursor = "" column = 0; } var index = this.$shortWordEndIndex(rightOfCursor); this.moveCursorTo(row, column + index); }; this.moveCursorShortWordLeft = function() { var row = this.lead.row; var column = this.lead.column; var fold; if (fold = this.session.getFoldAt(row, column, -1)) return this.moveCursorTo(fold.start.row, fold.start.column); var line = this.session.getLine(row).substring(0, column); if (column == 0) { do { row--; line = this.doc.getLine(row); } while (row > 0 && /^\s*$/.test(line)) column = line.length; if (!/\s+$/.test(line)) line = "" } var leftOfCursor = lang.stringReverse(line); var index = this.$shortWordEndIndex(leftOfCursor); return this.moveCursorTo(row, column - index); }; this.moveCursorWordRight = function() { if (this.session.$selectLongWords) this.moveCursorLongWordRight(); else this.moveCursorShortWordRight(); }; this.moveCursorWordLeft = function() { if (this.session.$selectLongWords) this.moveCursorLongWordLeft(); else this.moveCursorShortWordLeft(); }; this.moveCursorBy = function(rows, chars) { var screenPos = this.session.documentToScreenPosition( this.lead.row, this.lead.column ); if (chars === 0) { if (this.$desiredColumn) screenPos.column = this.$desiredColumn; else this.$desiredColumn = screenPos.column; } var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column); // move the cursor and update the desired column this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0); }; this.moveCursorToPosition = function(position) { this.moveCursorTo(position.row, position.column); }; this.moveCursorTo = function(row, column, keepDesiredColumn) { // Ensure the row/column is not inside of a fold. var fold = this.session.getFoldAt(row, column, 1); if (fold) { row = fold.start.row; column = fold.start.column; } this.$keepDesiredColumnOnChange = true; this.lead.setPosition(row, column); this.$keepDesiredColumnOnChange = false; if (!keepDesiredColumn) this.$desiredColumn = null; }; this.moveCursorToScreen = function(row, column, keepDesiredColumn) { var pos = this.session.screenToDocumentPosition(row, column); this.moveCursorTo(pos.row, pos.column, keepDesiredColumn); }; // remove listeners from document this.detach = function() { this.lead.detach(); this.anchor.detach(); this.session = this.doc = null; } this.fromOrientedRange = function(range) { this.setSelectionRange(range, range.cursor == range.start); this.$desiredColumn = range.desiredColumn || this.$desiredColumn; } this.toOrientedRange = function(range) { var r = this.getRange(); if (range) { range.start.column = r.start.column; range.start.row = r.start.row; range.end.column = r.end.column; range.end.row = r.end.row; } else { range = r; } range.cursor = this.isBackwards() ? range.start : range.end; range.desiredColumn = this.$desiredColumn; return range; } }).call(Selection.prototype); exports.Selection = Selection; }); define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Range * * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. * **/ /** * new Range(startRow, startColumn, endRow, endColumn) * - startRow (Number): The starting row * - startColumn (Number): The starting column * - endRow (Number): The ending row * - endColumn (Number): The ending column * * Creates a new `Range` object with the given starting and ending row and column points. * **/ var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { /** * Range.isEqual(range) -> Boolean * - range (Range): A range to check against * * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. * **/ this.isEqual = function(range) { return this.start.row == range.start.row && this.end.row == range.end.row && this.start.column == range.start.column && this.end.column == range.end.column }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } } /** related to: Range.compare * Range.comparePoint(p) -> Number * - p (Range): A point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1<br/> * * Checks the row and column points of `p` with the row and column points of the calling range. * * * **/ this.comparePoint = function(p) { return this.compare(p.row, p.column); } /** related to: Range.comparePoint * Range.containsRange(range) -> Boolean * - range (Range): A range to compare with * * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * **/ this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; } /** * Range.intersects(range) -> Boolean * - range (Range): A range to compare with * * Returns `true` if passed in `range` intersects with the one calling this method. * **/ this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); } /** * Range.isEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * **/ this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; } /** * Range.isStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * **/ this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; } /** * Range.setStart(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } } /** * Range.setEnd(row, column) * - row (Number): A row point to set * - column (Number): A column point to set * * Sets the starting row and column for the range. * **/ this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } } /** related to: Range.compare * Range.inside(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range. * **/ this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideStart(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's starting points. * **/ this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; } /** related to: Range.compare * Range.insideEnd(row, column) -> Boolean * - row (Number): A row point to compare with * - column (Number): A column point to compare with * * Returns `true` if the `row` and `column` are within the given range's ending points. * **/ this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; } /** * Range.compare(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal <br/> * * `-1` if `p.row` is less then the calling range <br/> * * `1` if `p.row` is greater than the calling range <br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> * <br/> * If the ending row of the calling range is equal to `p.row`, and: <br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); }; } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } } /** * Range.compareEnd(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `0` if the two points are exactly equal<br/> * * `-1` if `p.row` is less then the calling range<br/> * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/> * <br/> * If the starting row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/> * * Otherwise, it returns -1<br/> *<br/> * If the ending row of the calling range is equal to `p.row`, and:<br/> * * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/> * * Otherwise, it returns 1 * * Checks the row and column points with the row and column points of the calling range. * * **/ this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } } /** * Range.compareInside(row, column) -> Number * - row (Number): A row point to compare with * - column (Number): A column point to compare with * + (Number): This method returns one of the following numbers:<br/> * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/> * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/> * <br/> * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. * * Checks the row and column points with the row and column points of the calling range. * * * **/ this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } } /** * Range.clipRows(firstRow, lastRow) -> Range * - firstRow (Number): The starting row * - lastRow (Number): The ending row * * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * **/ this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) { var end = { row: lastRow+1, column: 0 }; } if (this.start.row > lastRow) { var start = { row: lastRow+1, column: 0 }; } if (this.start.row < firstRow) { var start = { row: firstRow, column: 0 }; } if (this.end.row < firstRow) { var end = { row: firstRow, column: 0 }; } return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || 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 Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; exports.Range = Range; }); define('ace/mode/text', ['require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/text_highlight_rules', 'ace/mode/behaviour', 'ace/unicode'], function(require, exports, module) { var Tokenizer = require("../tokenizer").Tokenizer; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var Behaviour = require("./behaviour").Behaviour; var unicode = require("../unicode"); var Mode = function() { this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules()); this.$behaviour = new Behaviour(); }; (function() { 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.getTokenizer = function() { return this.$tokenizer; }; this.toggleCommentLines = function(state, doc, startRow, endRow) { }; this.getNextLineIndent = function(state, line, tab) { return ""; }; this.checkOutdent = function(state, line, input) { return false; }; this.autoOutdent = function(state, doc, row) { }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; this.createWorker = function(session) { return null; }; this.createModeDelegates = function (mapping) { if (!this.$embeds) { return; } this.$modes = {}; for (var i = 0; i < this.$embeds.length; i++) { if (mapping[this.$embeds[i]]) { this.$modes[this.$embeds[i]] = new mapping[this.$embeds[i]](); } } var delegations = ['toggleCommentLines', 'getNextLineIndent', 'checkOutdent', 'autoOutdent', 'transformAction']; for (var i = 0; i < delegations.length; i++) { (function(scope) { var functionName = delegations[i]; var defaultHandler = scope[functionName]; scope[delegations[i]] = function() { return this.$delegator(functionName, arguments, defaultHandler); } } (this)); } } this.$delegator = function(method, args, defaultHandler) { var state = args[0]; for (var i = 0; i < this.$embeds.length; i++) { if (!this.$modes[this.$embeds[i]]) continue; var split = state.split(this.$embeds[i]); if (!split[0] && split[1]) { args[0] = split[1]; var mode = this.$modes[this.$embeds[i]]; return mode[method].apply(mode, args); } } var ret = defaultHandler.apply(this, args); return defaultHandler ? ret : undefined; }; this.transformAction = function(state, action, editor, session, param) { if (this.$behaviour) { var behaviours = this.$behaviour.getBehaviours(); for (var key in behaviours) { if (behaviours[key][action]) { var ret = behaviours[key][action].apply(this, arguments); if (ret) { return ret; } } } } } }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/tokenizer', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class Tokenizer * * This class takes a set of highlighting rules, and creates a tokenizer out of them. For more information, see [the wiki on extending highlighters](https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode#wiki-extendingTheHighlighter). * **/ /** * new Tokenizer(rules, flag) * - rules (Object): The highlighting rules * - flag (String): Any additional regular expression flags to pass (like "i" for case insensitive) * * Constructs a new tokenizer based on the given rules and flags. * **/ var Tokenizer = function(rules, flag) { flag = flag ? "g" + flag : "g"; this.rules = rules; this.regExps = {}; this.matchMappings = {}; for ( var key in this.rules) { var rule = this.rules[key]; var state = rule; var ruleRegExps = []; var matchTotal = 0; var mapping = this.matchMappings[key] = {}; for ( var i = 0; i < state.length; i++) { if (state[i].regex instanceof RegExp) state[i].regex = state[i].regex.toString().slice(1, -1); // Count number of matching groups. 2 extra groups from the full match // And the catch-all on the end (used to force a match); var matchcount = new RegExp("(?:(" + state[i].regex + ")|(.))").exec("a").length - 2; // Replace any backreferences and offset appropriately. var adjustedregex = state[i].regex.replace(/\\([0-9]+)/g, function (match, digit) { return "\\" + (parseInt(digit, 10) + matchTotal + 1); }); if (matchcount > 1 && state[i].token.length !== matchcount-1) throw new Error("Matching groups and length of the token array don't match in rule #" + i + " of state " + key); mapping[matchTotal] = { rule: i, len: matchcount }; matchTotal += matchcount; ruleRegExps.push(adjustedregex); } this.regExps[key] = new RegExp("(?:(" + ruleRegExps.join(")|(") + ")|(.))", flag); } }; (function() { /** * Tokenizer.getLineTokens() -> Object * * Returns an object containing two properties: `tokens`, which contains all the tokens; and `state`, the current state. **/ this.getLineTokens = function(line, startState) { var currentState = startState || "start"; var state = this.rules[currentState]; var mapping = this.matchMappings[currentState]; var re = this.regExps[currentState]; re.lastIndex = 0; var match, tokens = []; var lastIndex = 0; var token = { type: null, value: "" }; while (match = re.exec(line)) { var type = "text"; var rule = null; var value = [match[0]]; for (var i = 0; i < match.length-2; i++) { if (match[i + 1] === undefined) continue; rule = state[mapping[i].rule]; if (mapping[i].len > 1) value = match.slice(i+2, i+1+mapping[i].len); // compute token type if (typeof rule.token == "function") type = rule.token.apply(this, value); else type = rule.token; if (rule.next) { currentState = rule.next; state = this.rules[currentState]; mapping = this.matchMappings[currentState]; lastIndex = re.lastIndex; re = this.regExps[currentState]; re.lastIndex = lastIndex; } break; } if (value[0]) { if (typeof type == "string") { value = [value.join("")]; type = [type]; } for (var i = 0; i < value.length; i++) { if (!value[i]) continue; if ((!rule || rule.merge || type[i] === "text") && token.type === type[i]) { token.value += value[i]; } else { if (token.type) tokens.push(token); token = { type: type[i], value: value[i] }; } } } if (lastIndex == line.length) break; lastIndex = re.lastIndex; } if (token.type) tokens.push(token); return { tokens : tokens, state : currentState }; }; }).call(Tokenizer.prototype); exports.Tokenizer = Tokenizer; }); define('ace/mode/text_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); var TextHighlightRules = function() { // regexp must not have capturing parentheses // regexps are ordered -> the first match is used this.$rules = { "start" : [{ token : "empty_line", regex : '^$' }, { token : "text", regex : ".+" }] }; }; (function() { this.addRules = function(rules, prefix) { for (var key in rules) { var state = rules[key]; for (var i=0; i<state.length; i++) { var rule = state[i]; if (rule.next) { rule.next = prefix + rule.next; } } this.$rules[prefix + key] = state; } }; this.getRules = function() { return this.$rules; }; this.embedRules = function (HighlightRules, prefix, escapeRules, states) { var embedRules = new HighlightRules().getRules(); if (states) { for (var i = 0; i < states.length; i++) { states[i] = prefix + states[i]; } } else { states = []; for (var key in embedRules) { states.push(prefix + key); } } this.addRules(embedRules, prefix); for (var i = 0; i < states.length; i++) { Array.prototype.unshift.apply(this.$rules[states[i]], lang.deepCopy(escapeRules)); } if (!this.$embeds) { this.$embeds = []; } this.$embeds.push(prefix); } this.getEmbeds = function() { return this.$embeds; } }).call(TextHighlightRules.prototype); exports.TextHighlightRules = TextHighlightRules; }); define('ace/mode/behaviour', ['require', 'exports', 'module' ], function(require, exports, module) { var Behaviour = function() { this.$behaviours = {}; }; (function () { this.add = function (name, action, callback) { switch (undefined) { case this.$behaviours: this.$behaviours = {}; case this.$behaviours[name]: this.$behaviours[name] = {}; } this.$behaviours[name][action] = callback; } this.addBehaviours = function (behaviours) { for (var key in behaviours) { for (var action in behaviours[key]) { this.add(key, action, behaviours[key][action]); } } } this.remove = function (name) { if (this.$behaviours && this.$behaviours[name]) { delete this.$behaviours[name]; } } this.inherit = function (mode, filter) { if (typeof mode === "function") { var behaviours = new mode().getBehaviours(filter); } else { var behaviours = mode.getBehaviours(filter); } this.addBehaviours(behaviours); } this.getBehaviours = function (filter) { if (!filter) { return this.$behaviours; } else { var ret = {} for (var i = 0; i < filter.length; i++) { if (this.$behaviours[filter[i]]) { ret[filter[i]] = this.$behaviours[filter[i]]; } } return ret; } } }).call(Behaviour.prototype); exports.Behaviour = Behaviour; }); define('ace/unicode', ['require', 'exports', 'module' ], function(require, exports, module) { /* XRegExp Unicode plugin pack: Categories 1.0 (c) 2010 Steven Levithan MIT License <http://xregexp.com> Uses the Unicode 5.2 character database This package for the XRegExp Unicode plugin enables the following Unicode categories (aka properties): L - Letter (the top-level Letter category is included in the Unicode plugin base script) Ll - Lowercase letter Lu - Uppercase letter Lt - Titlecase letter Lm - Modifier letter Lo - Letter without case M - Mark Mn - Non-spacing mark Mc - Spacing combining mark Me - Enclosing mark N - Number Nd - Decimal digit Nl - Letter number No - Other number P - Punctuation Pd - Dash punctuation Ps - Open punctuation Pe - Close punctuation Pi - Initial punctuation Pf - Final punctuation Pc - Connector punctuation Po - Other punctuation S - Symbol Sm - Math symbol Sc - Currency symbol Sk - Modifier symbol So - Other symbol Z - Separator Zs - Space separator Zl - Line separator Zp - Paragraph separator C - Other Cc - Control Cf - Format Co - Private use Cs - Surrogate Cn - Unassigned Example usage: \p{N} \p{Cn} */ // will be populated by addUnicodePackage exports.packages = {}; addUnicodePackage({ L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A", Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A", Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC", Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F", Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26", Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26", Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC", Me: "0488048906DE20DD-20E020E2-20E4A670-A672", N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19", Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19", Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF", No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835", P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65", Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D", Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62", Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63", Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20", Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21", Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F", Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65", S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD", Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC", Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6", Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3", So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD", Z: "002000A01680180E2000-200A20282029202F205F3000", Zs: "002000A01680180E2000-200A202F205F3000", Zl: "2028", Zp: "2029", C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF", Cc: "0000-001F007F-009F", Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB", Co: "E000-F8FF", Cs: "D800-DFFF", Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF" }); function addUnicodePackage (pack) { var codePoint = /\w{4}/g; for (var name in pack) exports.packages[name] = pack[name].replace(codePoint, "\\u$&"); }; }); define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; /** * new Document([text]) * - text (String | Array): The starting text * * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * **/ var Document = function(text) { this.$lines = []; // There has to be one line at least in the document. If you pass an empty // string to the insert function, nothing will happen. Workaround. if (text.length == 0) { this.$lines = [""]; } else if (Array.isArray(text)) { this.insertLines(0, text); } else { this.insert({row: 0, column:0}, text); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength(); this.remove(new Range(0, 0, len, this.getLine(len-1).length)); this.insert({row: 0, column:0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; // check for IE split bug if ("aaa".split(/a/).length == 0) this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); } else this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); if (match) { this.$autoNewLine = match[1]; } else { this.$autoNewLine = "\n"; } }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; case "auto": return this.$autoNewLine; } }; this.$autoNewLine = "\n"; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { if (range.start.row == range.end.row) { return this.$lines[range.start.row].substring(range.start.column, range.end.column); } else { var lines = this.getLines(range.start.row+1, range.end.row-1); lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column)); lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column)); return lines.join(this.getNewLineCharacter()); } }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length-1).length; } return position; }; this.insert = function(position, text) { if (!text || text.length === 0) return position; position = this.$clipPosition(position); // only detect new lines if the document has no line break yet if (this.getLength() <= 1) this.$detectNewLine(text); var lines = this.$split(text); var firstLine = lines.splice(0, 1)[0]; var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; position = this.insertInLine(position, firstLine); if (lastLine !== null) { position = this.insertNewLine(position); // terminate first line position = this.insertLines(position.row, lines); position = this.insertInLine(position, lastLine || ""); } return position; }; this.insertLines = function(row, lines) { if (lines.length == 0) return {row: row, column: 0}; // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) // to circumvent that we have to break huge inserts into smaller chunks here if (lines.length > 0xFFFF) { var end = this.insertLines(row, lines.slice(0xFFFF)); lines = lines.slice(0, 0xFFFF); } var args = [row, 0]; args.push.apply(args, lines); this.$lines.splice.apply(this.$lines, args); var range = new Range(row, 0, row + lines.length, 0); var delta = { action: "insertLines", range: range, lines: lines }; this._emit("change", { data: delta }); return end || range.end; }; this.insertNewLine = function(position) { position = this.$clipPosition(position); var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column); this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); var end = { row : position.row + 1, column : 0 }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); return end; }; this.insertInLine = function(position, text) { if (text.length == 0) return position; var line = this.$lines[position.row] || ""; this.$lines[position.row] = line.substring(0, position.column) + text + line.substring(position.column); var end = { row : position.row, column : position.column + text.length }; var delta = { action: "insertText", range: Range.fromPoints(position, end), text: text }; this._emit("change", { data: delta }); return end; }; this.remove = function(range) { // clip to document range.start = this.$clipPosition(range.start); range.end = this.$clipPosition(range.end); if (range.isEmpty()) return range.start; var firstRow = range.start.row; var lastRow = range.end.row; if (range.isMultiLine()) { var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; var lastFullRow = lastRow - 1; if (range.end.column > 0) this.removeInLine(lastRow, 0, range.end.column); if (lastFullRow >= firstFullRow) this.removeLines(firstFullRow, lastFullRow); if (firstFullRow != firstRow) { this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); this.removeNewLine(range.start.row); } } else { this.removeInLine(firstRow, range.start.column, range.end.column); } return range.start; }; this.removeInLine = function(row, startColumn, endColumn) { if (startColumn == endColumn) return; var range = new Range(row, startColumn, row, endColumn); var line = this.getLine(row); var removed = line.substring(startColumn, endColumn); var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); this.$lines.splice(row, 1, newLine); var delta = { action: "removeText", range: range, text: removed }; this._emit("change", { data: delta }); return range.start; }; this.removeLines = function(firstRow, lastRow) { var range = new Range(firstRow, 0, lastRow + 1, 0); var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); var delta = { action: "removeLines", range: range, nl: this.getNewLineCharacter(), lines: removed }; this._emit("change", { data: delta }); return removed; }; this.removeNewLine = function(row) { var firstLine = this.getLine(row); var secondLine = this.getLine(row+1); var range = new Range(row, firstLine.length, row+1, 0); var line = firstLine + secondLine; this.$lines.splice(row, 2, line); var delta = { action: "removeText", range: range, text: this.getNewLineCharacter() }; this._emit("change", { data: delta }); }; this.replace = function(range, text) { if (text.length == 0 && range.isEmpty()) return range.start; // Shortcut: If the text we want to insert is the same as it is already // in the document, we don't have to replace anything. if (text == this.getTextRange(range)) return range.end; this.remove(range); if (text) { var end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "insertText") this.insert(range.start, delta.text); else if (delta.action == "removeLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "removeText") this.remove(range); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { var delta = deltas[i]; var range = Range.fromPoints(delta.range.start, delta.range.end); if (delta.action == "insertLines") this.removeLines(range.start.row, range.end.row - 1); else if (delta.action == "insertText") this.remove(range); else if (delta.action == "removeLines") this.insertLines(range.start.row, delta.lines); else if (delta.action == "removeText") this.insert(range.start, delta.text); } }; }).call(Document.prototype); exports.Document = Document; }); define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new Anchor(doc, row, column) * - doc (Document): The document to associate with the anchor * - row (Number): The starting row position * - column (Number): The starting column position * * Creates a new `Anchor` and associates it with a document. * **/ var Anchor = exports.Anchor = function(doc, row, column) { this.document = doc; if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); this.$onChange = this.onChange.bind(this); doc.on("change", this.$onChange); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.onChange = function(e) { var delta = e.data; var range = delta.range; if (range.start.row == range.end.row && range.start.row != this.row) return; if (range.start.row > this.row) return; if (range.start.row == this.row && range.start.column > this.column) return; var row = this.row; var column = this.column; if (delta.action === "insertText") { if (range.start.row === row && range.start.column <= column) { if (range.start.row === range.end.row) { column += range.end.column - range.start.column; } else { column -= range.start.column; row += range.end.row - range.start.row; } } else if (range.start.row !== range.end.row && range.start.row < row) { row += range.end.row - range.start.row; } } else if (delta.action === "insertLines") { if (range.start.row <= row) { row += range.end.row - range.start.row; } } else if (delta.action == "removeText") { if (range.start.row == row && range.start.column < column) { if (range.end.column >= column) column = range.start.column; else column = Math.max(0, column - (range.end.column - range.start.column)); } else if (range.start.row !== range.end.row && range.start.row < row) { if (range.end.row == row) { column = Math.max(0, column - range.end.column) + range.start.column; } row -= (range.end.row - range.start.row); } else if (range.end.row == row) { row -= range.end.row - range.start.row; column = Math.max(0, column - range.end.column) + range.start.column; } } else if (delta.action == "removeLines") { if (range.start.row <= row) { if (range.end.row <= row) row -= range.end.row - range.start.row; else { row = range.start.row; column = 0; } } } this.setPosition(row, column, true); }; 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._emit("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("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); }); define('ace/background_tokenizer', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; // tokenizing lines longer than this makes editor very slow var MAX_LINE_LENGTH = 5000; /** * new BackgroundTokenizer(tokenizer, editor) * - tokenizer (Tokenizer): The tokenizer to use * - editor (Editor): The editor to associate with * * Creates a new `BackgroundTokenizer` object. * * **/ var BackgroundTokenizer = function(tokenizer, editor) { this.running = false; this.lines = []; this.states = []; this.currentLine = 0; this.tokenizer = tokenizer; var self = this; this.$worker = function() { if (!self.running) { return; } var workerStart = new Date(); var startLine = self.currentLine; var doc = self.doc; var processedLines = 0; var len = doc.getLength(); while (self.currentLine < len) { self.$tokenizeRow(self.currentLine); while (self.lines[self.currentLine]) self.currentLine++; // only check every 5 lines processedLines ++; if ((processedLines % 5 == 0) && (new Date() - workerStart) > 20) { self.fireUpdateEvent(startLine, self.currentLine-1); self.running = setTimeout(self.$worker, 20); return; } } self.running = false; self.fireUpdateEvent(startLine, len - 1); }; }; (function(){ oop.implement(this, EventEmitter); this.setTokenizer = function(tokenizer) { this.tokenizer = tokenizer; this.lines = []; this.states = []; this.start(0); }; this.setDocument = function(doc) { this.doc = doc; this.lines = []; this.states = []; this.stop(); }; this.fireUpdateEvent = function(firstRow, lastRow) { var data = { first: firstRow, last: lastRow }; this._emit("update", {data: data}); }; this.start = function(startRow) { this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength()); // remove all cached items below this line this.lines.splice(this.currentLine, this.lines.length); this.states.splice(this.currentLine, this.states.length); this.stop(); // pretty long delay to prevent the tokenizer from interfering with the user this.running = setTimeout(this.$worker, 700); }; this.$updateOnChange = function(delta) { var range = delta.range; var startRow = range.start.row; var len = range.end.row - startRow; if (len === 0) { this.lines[startRow] = null; } else if (delta.action == "removeText" || delta.action == "removeLines") { this.lines.splice(startRow, len + 1, null); this.states.splice(startRow, len + 1, null); } else { var args = Array(len + 1); args.unshift(startRow, 1); this.lines.splice.apply(this.lines, args); this.states.splice.apply(this.states, args); } this.currentLine = Math.min(startRow, this.currentLine, this.doc.getLength()); this.stop(); // pretty long delay to prevent the tokenizer from interfering with the user this.running = setTimeout(this.$worker, 700); }; this.stop = function() { if (this.running) clearTimeout(this.running); this.running = false; }; this.getTokens = function(row) { return this.lines[row] || this.$tokenizeRow(row); }; this.getState = function(row) { if (this.currentLine == row) this.$tokenizeRow(row); return this.states[row] || "start"; }; this.$tokenizeRow = function(row) { var line = this.doc.getLine(row); var state = this.states[row - 1]; if (line.length > MAX_LINE_LENGTH) { var overflow = {value: line.substr(MAX_LINE_LENGTH), type: "text"}; line = line.slice(0, MAX_LINE_LENGTH); } var data = this.tokenizer.getLineTokens(line, state); if (overflow) { data.tokens.push(overflow); data.state = "start"; } if (this.states[row] !== data.state) { this.states[row] = data.state; this.lines[row + 1] = null; if (this.currentLine > row + 1) this.currentLine = row + 1; } else if (this.currentLine == row) { this.currentLine = row + 1; } return this.lines[row] = data.tokens; }; }).call(BackgroundTokenizer.prototype); exports.BackgroundTokenizer = BackgroundTokenizer; }); define('ace/search_highlight', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/lib/oop', 'ace/range'], function(require, exports, module) { var lang = require("./lib/lang"); var oop = require("./lib/oop"); var Range = require("./range").Range; var SearchHighlight = function(regExp, clazz, type) { this.setRegexp(regExp); this.clazz = clazz; this.type = type || "text"; }; (function() { this.setRegexp = function(regExp) { if (this.regExp+"" == regExp+"") return; this.regExp = regExp; this.cache = []; }; this.update = function(html, markerLayer, session, config) { if (!this.regExp) return; var start = config.firstRow, end = config.lastRow; for (var i = start; i <= end; i++) { var ranges = this.cache[i]; if (ranges == null) { ranges = lang.getMatchOffsets(session.getLine(i), this.regExp); ranges = ranges.map(function(match) { return new Range(i, match.offset, i, match.offset + match.length); }); this.cache[i] = ranges.length ? ranges : ""; } for (var j = ranges.length; j --; ) { markerLayer.drawSingleLineMarker( html, ranges[j].toScreenRange(session), this.clazz, config, null, this.type ); } } }; }).call(SearchHighlight.prototype); exports.SearchHighlight = SearchHighlight; }); define('ace/edit_session/folding', ['require', 'exports', 'module' , 'ace/range', 'ace/edit_session/fold_line', 'ace/edit_session/fold', 'ace/token_iterator'], function(require, exports, module) { var Range = require("../range").Range; var FoldLine = require("./fold_line").FoldLine; var Fold = require("./fold").Fold; var TokenIterator = require("../token_iterator").TokenIterator; function Folding() { /* * Looks up a fold at a given row/column. Possible values for side: * -1: ignore a fold if fold.start = row/column * +1: ignore a fold if fold.end = row/column */ this.getFoldAt = function(row, column, side) { var foldLine = this.getFoldLine(row); if (!foldLine) return null; var folds = foldLine.folds; for (var i = 0; i < folds.length; i++) { var fold = folds[i]; if (fold.range.contains(row, column)) { if (side == 1 && fold.range.isEnd(row, column)) { continue; } else if (side == -1 && fold.range.isStart(row, column)) { continue; } return fold; } } }; this.getFoldsInRange = function(range) { range = range.clone(); var start = range.start; var end = range.end; var foldLines = this.$foldData; var foundFolds = []; start.column += 1; end.column -= 1; for (var i = 0; i < foldLines.length; i++) { var cmp = foldLines[i].range.compareRange(range); if (cmp == 2) { // Range is before foldLine. No intersection. This means, // there might be other foldLines that intersect. continue; } else if (cmp == -2) { // Range is after foldLine. There can't be any other foldLines then, // so let's give up. break; } var folds = foldLines[i].folds; for (var j = 0; j < folds.length; j++) { var fold = folds[j]; cmp = fold.range.compareRange(range); if (cmp == -2) { break; } else if (cmp == 2) { continue; } else // WTF-state: Can happen due to -1/+1 to start/end column. if (cmp == 42) { break; } foundFolds.push(fold); } } return foundFolds; }; this.getAllFolds = function() { var folds = []; var foldLines = this.$foldData; function addFold(fold) { folds.push(fold); if (!fold.subFolds) return; for (var i = 0; i < fold.subFolds.length; i++) addFold(fold.subFolds[i]); } for (var i = 0; i < foldLines.length; i++) for (var j = 0; j < foldLines[i].folds.length; j++) addFold(foldLines[i].folds[j]); return folds; }; this.getFoldStringAt = function(row, column, trim, foldLine) { foldLine = foldLine || this.getFoldLine(row); if (!foldLine) return null; var lastFold = { end: { column: 0 } }; // TODO: Refactor to use getNextFoldTo function. var str, fold; for (var i = 0; i < foldLine.folds.length; i++) { fold = foldLine.folds[i]; var cmp = fold.range.compareEnd(row, column); if (cmp == -1) { str = this .getLine(fold.start.row) .substring(lastFold.end.column, fold.start.column); break; } else if (cmp === 0) { return null; } lastFold = fold; } if (!str) str = this.getLine(fold.start.row).substring(lastFold.end.column); if (trim == -1) return str.substring(0, column - lastFold.end.column); else if (trim == 1) return str.substring(column - lastFold.end.column); else return str; }; this.getFoldLine = function(docRow, startFoldLine) { var foldData = this.$foldData; var i = 0; if (startFoldLine) i = foldData.indexOf(startFoldLine); if (i == -1) i = 0; for (i; i < foldData.length; i++) { var foldLine = foldData[i]; if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) { return foldLine; } else if (foldLine.end.row > docRow) { return null; } } return null; }; // returns the fold which starts after or contains docRow this.getNextFoldLine = function(docRow, startFoldLine) { var foldData = this.$foldData; var i = 0; if (startFoldLine) i = foldData.indexOf(startFoldLine); if (i == -1) i = 0; for (i; i < foldData.length; i++) { var foldLine = foldData[i]; if (foldLine.end.row >= docRow) { return foldLine; } } return null; }; this.getFoldedRowCount = function(first, last) { var foldData = this.$foldData, rowCount = last-first+1; for (var i = 0; i < foldData.length; i++) { var foldLine = foldData[i], end = foldLine.end.row, start = foldLine.start.row; if (end >= last) { if(start < last) { if(start >= first) rowCount -= last-start; else rowCount = 0;//in one fold } break; } else if(end >= first){ if (start >= first) //fold inside range rowCount -= end-start; else rowCount -= end-first+1; } } return rowCount; }; this.$addFoldLine = function(foldLine) { this.$foldData.push(foldLine); this.$foldData.sort(function(a, b) { return a.start.row - b.start.row; }); return foldLine; }; this.addFold = function(placeholder, range) { var foldData = this.$foldData; var added = false; var fold; if (placeholder instanceof Fold) fold = placeholder; else fold = new Fold(range, placeholder); this.$clipRangeToDocument(fold.range); var startRow = fold.start.row; var startColumn = fold.start.column; var endRow = fold.end.row; var endColumn = fold.end.column; // --- Some checking --- if (fold.placeholder.length < 2) throw "Placeholder has to be at least 2 characters"; if (startRow == endRow && endColumn - startColumn < 2) throw "The range has to be at least 2 characters width"; var startFold = this.getFoldAt(startRow, startColumn, 1); var endFold = this.getFoldAt(endRow, endColumn, -1); if (startFold && endFold == startFold) return startFold.addSubFold(fold); if ( (startFold && !startFold.range.isStart(startRow, startColumn)) || (endFold && !endFold.range.isEnd(endRow, endColumn)) ) { throw "A fold can't intersect already existing fold" + fold.range + startFold.range; } // Check if there are folds in the range we create the new fold for. var folds = this.getFoldsInRange(fold.range); if (folds.length > 0) { // Remove the folds from fold data. this.removeFolds(folds); // Add the removed folds as subfolds on the new fold. fold.subFolds = folds; } for (var i = 0; i < foldData.length; i++) { var foldLine = foldData[i]; if (endRow == foldLine.start.row) { foldLine.addFold(fold); added = true; break; } else if (startRow == foldLine.end.row) { foldLine.addFold(fold); added = true; if (!fold.sameRow) { // Check if we might have to merge two FoldLines. var foldLineNext = foldData[i + 1]; if (foldLineNext && foldLineNext.start.row == endRow) { // We need to merge! foldLine.merge(foldLineNext); break; } } break; } else if (endRow <= foldLine.start.row) { break; } } if (!added) foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold)); if (this.$useWrapMode) this.$updateWrapData(foldLine.start.row, foldLine.start.row); else this.$updateRowLengthCache(foldLine.start.row, foldLine.start.row); // Notify that fold data has changed. this.$modified = true; this._emit("changeFold", { data: fold }); return fold; }; this.addFolds = function(folds) { folds.forEach(function(fold) { this.addFold(fold); }, this); }; this.removeFold = function(fold) { var foldLine = fold.foldLine; var startRow = foldLine.start.row; var endRow = foldLine.end.row; var foldLines = this.$foldData; var folds = foldLine.folds; // Simple case where there is only one fold in the FoldLine such that // the entire fold line can get removed directly. if (folds.length == 1) { foldLines.splice(foldLines.indexOf(foldLine), 1); } else // If the fold is the last fold of the foldLine, just remove it. if (foldLine.range.isEnd(fold.end.row, fold.end.column)) { folds.pop(); foldLine.end.row = folds[folds.length - 1].end.row; foldLine.end.column = folds[folds.length - 1].end.column; } else // If the fold is the first fold of the foldLine, just remove it. if (foldLine.range.isStart(fold.start.row, fold.start.column)) { folds.shift(); foldLine.start.row = folds[0].start.row; foldLine.start.column = folds[0].start.column; } else // We know there are more then 2 folds and the fold is not at the edge. // This means, the fold is somewhere in between. // // If the fold is in one row, we just can remove it. if (fold.sameRow) { folds.splice(folds.indexOf(fold), 1); } else // The fold goes over more then one row. This means remvoing this fold // will cause the fold line to get splitted up. newFoldLine is the second part { var newFoldLine = foldLine.split(fold.start.row, fold.start.column); folds = newFoldLine.folds; folds.shift(); newFoldLine.start.row = folds[0].start.row; newFoldLine.start.column = folds[0].start.column; } if (this.$useWrapMode) this.$updateWrapData(startRow, endRow); else this.$updateRowLengthCache(startRow, endRow); // Notify that fold data has changed. this.$modified = true; this._emit("changeFold", { data: fold }); }; this.removeFolds = function(folds) { // We need to clone the folds array passed in as it might be the folds // array of a fold line and as we call this.removeFold(fold), folds // are removed from folds and changes the current index. var cloneFolds = []; for (var i = 0; i < folds.length; i++) { cloneFolds.push(folds[i]); } cloneFolds.forEach(function(fold) { this.removeFold(fold); }, this); this.$modified = true; }; this.expandFold = function(fold) { this.removeFold(fold); fold.subFolds.forEach(function(fold) { this.addFold(fold); }, this); fold.subFolds = []; }; this.expandFolds = function(folds) { folds.forEach(function(fold) { this.expandFold(fold); }, this); }; this.unfold = function(location, expandInner) { var range, folds; if (location == null) range = new Range(0, 0, this.getLength(), 0); else if (typeof location == "number") range = new Range(location, 0, location, this.getLine(location).length); else if ("row" in location) range = Range.fromPoints(location, location); else range = location; folds = this.getFoldsInRange(range); if (expandInner) { this.removeFolds(folds); } else { // TODO: might need to remove and add folds in one go instead of using // expandFolds several times. while (folds.length) { this.expandFolds(folds); folds = this.getFoldsInRange(range); } } }; this.isRowFolded = function(docRow, startFoldRow) { return !!this.getFoldLine(docRow, startFoldRow); }; this.getRowFoldEnd = function(docRow, startFoldRow) { var foldLine = this.getFoldLine(docRow, startFoldRow); return (foldLine ? foldLine.end.row : docRow); }; this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) { if (startRow == null) { startRow = foldLine.start.row; startColumn = 0; } if (endRow == null) { endRow = foldLine.end.row; endColumn = this.getLine(endRow).length; } // Build the textline using the FoldLine walker. var doc = this.doc; var textLine = ""; foldLine.walk(function(placeholder, row, column, lastColumn) { if (row < startRow) { return; } else if (row == startRow) { if (column < startColumn) { return; } lastColumn = Math.max(startColumn, lastColumn); } if (placeholder) { textLine += placeholder; } else { textLine += doc.getLine(row).substring(lastColumn, column); } }.bind(this), endRow, endColumn); return textLine; }; this.getDisplayLine = function(row, endColumn, startRow, startColumn) { var foldLine = this.getFoldLine(row); if (!foldLine) { var line; line = this.doc.getLine(row); return line.substring(startColumn || 0, endColumn || line.length); } else { return this.getFoldDisplayLine( foldLine, row, endColumn, startRow, startColumn); } }; this.$cloneFoldData = function() { var fd = []; fd = this.$foldData.map(function(foldLine) { var folds = foldLine.folds.map(function(fold) { return fold.clone(); }); return new FoldLine(fd, folds); }); return fd; }; this.toggleFold = function(tryToUnfold) { var selection = this.selection; var range = selection.getRange(); var fold; var bracketPos; if (range.isEmpty()) { var cursor = range.start; fold = this.getFoldAt(cursor.row, cursor.column); if (fold) { this.expandFold(fold); return; } else if (bracketPos = this.findMatchingBracket(cursor)) { if (range.comparePoint(bracketPos) == 1) { range.end = bracketPos; } else { range.start = bracketPos; range.start.column++; range.end.column--; } } else if (bracketPos = this.findMatchingBracket({row: cursor.row, column: cursor.column + 1})) { if (range.comparePoint(bracketPos) == 1) range.end = bracketPos; else range.start = bracketPos; range.start.column++; } else { range = this.getCommentFoldRange(cursor.row, cursor.column) || range; } } else { var folds = this.getFoldsInRange(range); if (tryToUnfold && folds.length) { this.expandFolds(folds); return; } else if (folds.length == 1 ) { fold = folds[0]; } } if (!fold) fold = this.getFoldAt(range.start.row, range.start.column); if (fold && fold.range.toString() == range.toString()) { this.expandFold(fold); return; } var placeholder = "..."; if (!range.isMultiLine()) { placeholder = this.getTextRange(range); if(placeholder.length < 4) return; placeholder = placeholder.trim().substring(0, 2) + ".."; } this.addFold(placeholder, range); }; this.getCommentFoldRange = function(row, column) { var iterator = new TokenIterator(this, row, column); var token = iterator.getCurrentToken(); if (token && /^comment|string/.test(token.type)) { var range = new Range(); var re = new RegExp(token.type.replace(/\..*/, "\\.")); do { token = iterator.stepBackward(); } while(token && re.test(token.type)); iterator.stepForward(); range.start.row = iterator.getCurrentTokenRow(); range.start.column = iterator.getCurrentTokenColumn() + 2; iterator = new TokenIterator(this, row, column); do { token = iterator.stepForward(); } while(token && re.test(token.type)); token = iterator.stepBackward(); range.end.row = iterator.getCurrentTokenRow(); range.end.column = iterator.getCurrentTokenColumn() + token.value.length; return range; } }; this.foldAll = function(startRow, endRow) { var foldWidgets = this.foldWidgets; endRow = endRow || this.getLength(); for (var row = startRow || 0; row < endRow; row++) { if (foldWidgets[row] == null) foldWidgets[row] = this.getFoldWidget(row); if (foldWidgets[row] != "start") continue; var range = this.getFoldWidgetRange(row); // sometimes range can be incompatible with existing fold // wouldn't it be better for addFold to return null istead of throwing? if (range && range.end.row < endRow) try { this.addFold("...", range); } catch(e) {} } }; this.$foldStyles = { "manual": 1, "markbegin": 1, "markbeginend": 1 }; this.$foldStyle = "markbegin"; this.setFoldStyle = function(style) { if (!this.$foldStyles[style]) throw new Error("invalid fold style: " + style + "[" + Object.keys(this.$foldStyles).join(", ") + "]"); if (this.$foldStyle == style) return; this.$foldStyle = style; if (style == "manual") this.unfold(); // reset folding var mode = this.$foldMode; this.$setFolding(null); this.$setFolding(mode); }; // structured folding this.$setFolding = function(foldMode) { if (this.$foldMode == foldMode) return; this.$foldMode = foldMode; this.removeListener('change', this.$updateFoldWidgets); this._emit("changeAnnotation"); if (!foldMode || this.$foldStyle == "manual") { this.foldWidgets = null; return; } this.foldWidgets = []; this.getFoldWidget = foldMode.getFoldWidget.bind(foldMode, this, this.$foldStyle); this.getFoldWidgetRange = foldMode.getFoldWidgetRange.bind(foldMode, this, this.$foldStyle); this.$updateFoldWidgets = this.updateFoldWidgets.bind(this); this.on('change', this.$updateFoldWidgets); }; this.onFoldWidgetClick = function(row, e) { var type = this.getFoldWidget(row); var line = this.getLine(row); var onlySubfolds = e.shiftKey; var addSubfolds = onlySubfolds || e.ctrlKey || e.altKey || e.metaKey; var fold; if (type == "end") fold = this.getFoldAt(row, 0, -1); else fold = this.getFoldAt(row, line.length, 1); if (fold) { if (addSubfolds) this.removeFold(fold); else this.expandFold(fold); return; } var range = this.getFoldWidgetRange(row); if (range) { // sometimes singleline folds can be missed by the code above if (!range.isMultiLine()) { fold = this.getFoldAt(range.start.row, range.start.column, 1); if (fold && range.isEqual(fold.range)) { this.removeFold(fold); return; } } if (!onlySubfolds) this.addFold("...", range); if (addSubfolds) this.foldAll(range.start.row + 1, range.end.row); } else { if (addSubfolds) this.foldAll(row + 1, this.getLength()); e.target.className += " invalid" } }; this.updateFoldWidgets = function(e) { var delta = e.data; var range = delta.range; var firstRow = range.start.row; var len = range.end.row - firstRow; if (len === 0) { this.foldWidgets[firstRow] = null; } else if (delta.action == "removeText" || delta.action == "removeLines") { this.foldWidgets.splice(firstRow, len + 1, null); } else { var args = Array(len + 1); args.unshift(firstRow, 1); this.foldWidgets.splice.apply(this.foldWidgets, args); } }; } exports.Folding = Folding; }); define('ace/edit_session/fold_line', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; function FoldLine(foldData, folds) { this.foldData = foldData; if (Array.isArray(folds)) { this.folds = folds; } else { folds = this.folds = [ folds ]; } var last = folds[folds.length - 1] this.range = new Range(folds[0].start.row, folds[0].start.column, last.end.row, last.end.column); this.start = this.range.start; this.end = this.range.end; this.folds.forEach(function(fold) { fold.setFoldLine(this); }, this); } (function() { /* * Note: This doesn't update wrapData! */ this.shiftRow = function(shift) { this.start.row += shift; this.end.row += shift; this.folds.forEach(function(fold) { fold.start.row += shift; fold.end.row += shift; }); } this.addFold = function(fold) { if (fold.sameRow) { if (fold.start.row < this.startRow || fold.endRow > this.endRow) { throw "Can't add a fold to this FoldLine as it has no connection"; } this.folds.push(fold); this.folds.sort(function(a, b) { return -a.range.compareEnd(b.start.row, b.start.column); }); if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) { this.end.row = fold.end.row; this.end.column = fold.end.column; } else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) { this.start.row = fold.start.row; this.start.column = fold.start.column; } } else if (fold.start.row == this.end.row) { this.folds.push(fold); this.end.row = fold.end.row; this.end.column = fold.end.column; } else if (fold.end.row == this.start.row) { this.folds.unshift(fold); this.start.row = fold.start.row; this.start.column = fold.start.column; } else { throw "Trying to add fold to FoldRow that doesn't have a matching row"; } fold.foldLine = this; } this.containsRow = function(row) { return row >= this.start.row && row <= this.end.row; } this.walk = function(callback, endRow, endColumn) { var lastEnd = 0, folds = this.folds, fold, comp, stop, isNewRow = true; if (endRow == null) { endRow = this.end.row; endColumn = this.end.column; } for (var i = 0; i < folds.length; i++) { fold = folds[i]; comp = fold.range.compareStart(endRow, endColumn); // This fold is after the endRow/Column. if (comp == -1) { callback(null, endRow, endColumn, lastEnd, isNewRow); return; } stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow); stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd); // If the user requested to stop the walk or endRow/endColumn is // inside of this fold (comp == 0), then end here. if (stop || comp == 0) { return; } // Note the new lastEnd might not be on the same line. However, // it's the callback's job to recognize this. isNewRow = !fold.sameRow; lastEnd = fold.end.column; } callback(null, endRow, endColumn, lastEnd, isNewRow); } this.getNextFoldTo = function(row, column) { var fold, cmp; for (var i = 0; i < this.folds.length; i++) { fold = this.folds[i]; cmp = fold.range.compareEnd(row, column); if (cmp == -1) { return { fold: fold, kind: "after" }; } else if (cmp == 0) { return { fold: fold, kind: "inside" } } } return null; } this.addRemoveChars = function(row, column, len) { var ret = this.getNextFoldTo(row, column), fold, folds; if (ret) { fold = ret.fold; if (ret.kind == "inside" && fold.start.column != column && fold.start.row != row) { //throwing here breaks whole editor //@todo properly handle this window.console && window.console.log(row, column, fold); } else if (fold.start.row == row) { folds = this.folds; var i = folds.indexOf(fold); if (i == 0) { this.start.column += len; } for (i; i < folds.length; i++) { fold = folds[i]; fold.start.column += len; if (!fold.sameRow) { return; } fold.end.column += len; } this.end.column += len; } } } this.split = function(row, column) { var fold = this.getNextFoldTo(row, column).fold, folds = this.folds; var foldData = this.foldData; if (!fold) { return null; } var i = folds.indexOf(fold); var foldBefore = folds[i - 1]; this.end.row = foldBefore.end.row; this.end.column = foldBefore.end.column; // Remove the folds after row/column and create a new FoldLine // containing these removed folds. folds = folds.splice(i, folds.length - i); var newFoldLine = new FoldLine(foldData, folds); foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine); return newFoldLine; } this.merge = function(foldLineNext) { var folds = foldLineNext.folds; for (var i = 0; i < folds.length; i++) { this.addFold(folds[i]); } // Remove the foldLineNext - no longer needed, as // it's merged now with foldLineNext. var foldData = this.foldData; foldData.splice(foldData.indexOf(foldLineNext), 1); } this.toString = function() { var ret = [this.range.toString() + ": [" ]; this.folds.forEach(function(fold) { ret.push(" " + fold.toString()); }); ret.push("]") return ret.join("\n"); } this.idxToPosition = function(idx) { var lastFoldEndColumn = 0; var fold; for (var i = 0; i < this.folds.length; i++) { var fold = this.folds[i]; idx -= fold.start.column - lastFoldEndColumn; if (idx < 0) { return { row: fold.start.row, column: fold.start.column + idx }; } idx -= fold.placeholder.length; if (idx < 0) { return fold.start; } lastFoldEndColumn = fold.end.column; } return { row: this.end.row, column: this.end.column + idx }; } }).call(FoldLine.prototype); exports.FoldLine = FoldLine; }); define('ace/edit_session/fold', ['require', 'exports', 'module' ], function(require, exports, module) { /* * Simple fold-data struct. **/ var Fold = exports.Fold = function(range, placeholder) { this.foldLine = null; this.placeholder = placeholder; this.range = range; this.start = range.start; this.end = range.end; this.sameRow = range.start.row == range.end.row; this.subFolds = []; }; (function() { this.toString = function() { return '"' + this.placeholder + '" ' + this.range.toString(); }; this.setFoldLine = function(foldLine) { this.foldLine = foldLine; this.subFolds.forEach(function(fold) { fold.setFoldLine(foldLine); }); }; this.clone = function() { var range = this.range.clone(); var fold = new Fold(range, this.placeholder); this.subFolds.forEach(function(subFold) { fold.subFolds.push(subFold.clone()); }); return fold; }; this.addSubFold = function(fold) { if (this.range.isEqual(fold)) return this; if (!this.range.containsRange(fold)) throw "A fold can't intersect already existing fold" + fold.range + this.range; var row = fold.range.start.row, column = fold.range.start.column; for (var i = 0, cmp = -1; i < this.subFolds.length; i++) { cmp = this.subFolds[i].range.compare(row, column); if (cmp != 1) break; } var afterStart = this.subFolds[i]; if (cmp == 0) return afterStart.addSubFold(fold) // cmp == -1 var row = fold.range.end.row, column = fold.range.end.column; for (var j = i, cmp = -1; j < this.subFolds.length; j++) { cmp = this.subFolds[j].range.compare(row, column); if (cmp != 1) break; } var afterEnd = this.subFolds[j]; if (cmp == 0) throw "A fold can't intersect already existing fold" + fold.range + this.range; var consumedFolds = this.subFolds.splice(i, j - i, fold) fold.setFoldLine(this.foldLine); return fold; } }).call(Fold.prototype); }); define('ace/token_iterator', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class TokenIterator * * This class provides an essay way to treat the document as a stream of tokens, and provides methods to iterate over these tokens. * **/ /** * new TokenIterator(session, initialRow, initialColumn) * - session (EditSession): The session to associate with * - initialRow (Number): The row to start the tokenizing at * - initialColumn (Number): The column to start the tokenizing at * * Creates a new token iterator object. The inital token index is set to the provided row and column coordinates. * **/ var TokenIterator = function(session, initialRow, initialColumn) { this.$session = session; this.$row = initialRow; this.$rowTokens = session.getTokens(initialRow); var token = session.getTokenAt(initialRow, initialColumn); this.$tokenIndex = token ? token.index : -1; }; (function() { /** * TokenIterator.stepBackward() -> [String] * + (String): If the current point is not at the top of the file, this function returns `null`. Otherwise, it returns an array of the tokenized strings. * * Tokenizes all the items from the current point to the row prior in the document. **/ this.stepBackward = function() { this.$tokenIndex -= 1; while (this.$tokenIndex < 0) { this.$row -= 1; if (this.$row < 0) { this.$row = 0; return null; } this.$rowTokens = this.$session.getTokens(this.$row); this.$tokenIndex = this.$rowTokens.length - 1; } return this.$rowTokens[this.$tokenIndex]; }; this.stepForward = function() { var rowCount = this.$session.getLength(); this.$tokenIndex += 1; while (this.$tokenIndex >= this.$rowTokens.length) { this.$row += 1; if (this.$row >= rowCount) { this.$row = rowCount - 1; return null; } this.$rowTokens = this.$session.getTokens(this.$row); this.$tokenIndex = 0; } return this.$rowTokens[this.$tokenIndex]; }; this.getCurrentToken = function () { return this.$rowTokens[this.$tokenIndex]; }; this.getCurrentTokenRow = function () { return this.$row; }; this.getCurrentTokenColumn = function() { var rowTokens = this.$rowTokens; var tokenIndex = this.$tokenIndex; // If a column was cached by EditSession.getTokenAt, then use it var column = rowTokens[tokenIndex].start; if (column !== undefined) return column; column = 0; while (tokenIndex > 0) { tokenIndex -= 1; column += rowTokens[tokenIndex].value.length; } return column; }; }).call(TokenIterator.prototype); exports.TokenIterator = TokenIterator; }); define('ace/edit_session/bracket_match', ['require', 'exports', 'module' , 'ace/token_iterator'], function(require, exports, module) { var TokenIterator = require("../token_iterator").TokenIterator; /** * new BracketMatch(position) * - platform (String): Identifier for the platform; must be either `'mac'` or `'win'` * - commands (Array): A list of commands * * TODO * * **/ function BracketMatch() { /** * new findMatchingBracket(position) * - position (Number): Identifier for the platform; must be either `'mac'` or `'win'` * - commands (Array): A list of commands * * TODO * * **/ this.findMatchingBracket = function(position) { if (position.column == 0) return null; var charBeforeCursor = this.getLine(position.row).charAt(position.column-1); if (charBeforeCursor == "") return null; var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/); if (!match) { return null; } if (match[1]) { return this.$findClosingBracket(match[1], position); } else { return this.$findOpeningBracket(match[2], position); } }; this.$brackets = { ")": "(", "(": ")", "]": "[", "[": "]", "{": "}", "}": "{" }; this.$findOpeningBracket = function(bracket, position, typeRe) { var openBracket = this.$brackets[bracket]; var depth = 1; var iterator = new TokenIterator(this, position.row, position.column); var token = iterator.getCurrentToken(); if (!token) token = iterator.stepForward(); if (!token) return if (!typeRe){ typeRe = new RegExp( "(\\.?" + token.type.replace(".", "\\.").replace("rparen", ".paren") + ")+" ); } // Start searching in token, just before the character at position.column var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2; var value = token.value; while (true) { while (valueIndex >= 0) { var chr = value.charAt(valueIndex); if (chr == openBracket) { depth -= 1; if (depth == 0) { return {row: iterator.getCurrentTokenRow(), column: valueIndex + iterator.getCurrentTokenColumn()}; } } else if (chr == bracket) { depth += 1; } valueIndex -= 1; } // Scan backward through the document, looking for the next token // whose type matches typeRe do { token = iterator.stepBackward(); } while (token && !typeRe.test(token.type)); if (token == null) break; value = token.value; valueIndex = value.length - 1; } return null; }; this.$findClosingBracket = function(bracket, position, typeRe, allowBlankLine) { var closingBracket = this.$brackets[bracket]; var depth = 1; var iterator = new TokenIterator(this, position.row, position.column); var token = iterator.getCurrentToken(); if (!token) token = iterator.stepForward(); if (!token) return if (!typeRe){ typeRe = new RegExp( "(\\.?" + token.type.replace(".", "\\.").replace("lparen", ".paren") + ")+" ); } // Start searching in token, after the character at position.column var valueIndex = position.column - iterator.getCurrentTokenColumn(); while (true) { var value = token.value; var valueLength = value.length; while (valueIndex < valueLength) { var chr = value.charAt(valueIndex); if (chr == closingBracket) { depth -= 1; if (depth == 0) { return {row: iterator.getCurrentTokenRow(), column: valueIndex + iterator.getCurrentTokenColumn()}; } } else if (chr == bracket) { depth += 1; } valueIndex += 1; } // Scan forward through the document, looking for the next token // whose type matches typeRe do { token = iterator.stepForward(); if (allowBlankLine) { // if you've reached the doc end, or, you match a new content line if (token === null || token.type == "string") { return {row: iterator.getCurrentTokenRow() + (token === null ? 1 : -1), column: 0}; } } } while (token && !typeRe.test(token.type)); if (token == null) break; valueIndex = 0; } return null; }; } exports.BracketMatch = BracketMatch; }); define('ace/search', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/lib/oop', 'ace/range'], function(require, exports, module) { var lang = require("./lib/lang"); var oop = require("./lib/oop"); var Range = require("./range").Range; /** * new Search() * * Creates a new `Search` object. The following search options are avaliable: * * * needle: string or regular expression * * backwards: false * * wrap: false * * caseSensitive: false * * wholeWord: false * * range: Range or null for whole document * * regExp: false * * start: Range or position * * skipCurrent: false * **/ var Search = function() { this.$options = {}; }; (function() { /** * Search.set(options) -> Search * - options (Object): An object containing all the new search properties * * Sets the search options via the `options` parameter. * **/ this.set = function(options) { oop.mixin(this.$options, options); return this; }; this.getOptions = function() { return lang.copyObject(this.$options); }; this.setOptions = function(options) { this.$options = options; }; this.find = function(session) { var iterator = this.$matchIterator(session, this.$options); if (!iterator) return false; var firstRange = null; iterator.forEach(function(range, row, offset) { if (!range.start) { var column = range.offset + (offset || 0); firstRange = new Range(row, column, row, column+range.length); } else firstRange = range; return true; }); return firstRange; }; this.findAll = function(session) { var options = this.$options; if (!options.needle) return []; this.$assembleRegExp(options); if (options.range) { var range = options.range; var lines = session.getLines(range.start.row, range.end.row); } else var lines = session.doc.getAllLines(); var ranges = []; var re = options.re; if (options.$isMultiLine) { var len = re.length; var maxRow = lines.length - len; for (var row = re.offset || 0; row < maxRow; row++) { for (var j = 0; j < re.length; j++) if (lines[row + j].search(re[j]) == -1) break; var startIndex = lines[row + j].match(re[0])[0].length; var endIndex = line.match(re[len - 1])[0].length; ranges.push(new Range( row, startLine.length - startIndex, row + len - 1, endIndex )); } } else { for (var i = 0; i < lines.length; i++) { var matches = lang.getMatchOffsets(lines[i], re); for (var j = 0; j < matches.length; j++) { var match = matches[j]; ranges.push(new Range(i, match.offset, i, match.offset + match.length)); }; } } if (options.range) { var startColumn = range.start.column; var endColumn = range.start.column; var i = 0, j = ranges.length - 1; while (i < j && ranges[i].start.column < startColumn && ranges[i].start.row == range.start.row) i++; while (i < j && ranges[j].end.column > endColumn && ranges[j].end.row == range.end.row) j--; return ranges.slice(i, j + 1); } return ranges; }; this.replace = function(input, replacement) { var options = this.$options; var re = this.$assembleRegExp(options); if (options.$isMultiLine) return replacement; if (!re) return; var match = re.exec(input); if (!match || match[0].length != input.length) return null; replacement = input.replace(re, replacement) if (options.preserveCase) { replacement = replacement.split(""); for (var i = Math.min(input.length, input.length); i--; ) { var ch = input[i]; if (ch && ch.toLowerCase() != ch) replacement[i] = replacement[i].toUpperCase(); else replacement[i] = replacement[i].toLowerCase(); } replacement = replacement.join(""); } return replacement; }; this.$matchIterator = function(session, options) { var re = this.$assembleRegExp(options); if (!re) return false; var self = this, callback, backwards = options.backwards; if (options.$isMultiLine) { var len = re.length; var matchIterator = function(line, row, offset) { var startIndex = line.search(re[0]); if (startIndex == -1) return; for (var i = 1; i < len; i++) { line = session.getLine(row + i); if (line.search(re[i]) == -1) return; } var endIndex = line.match(re[len - 1])[0].length; var range = new Range(row, startIndex, row + len - 1, endIndex); if (re.offset == 1) { range.start.row--; range.start.column = Number.MAX_VALUE; } else if (offset) range.start.column += offset; if (callback(range)) return true; } } else if (backwards) { var matchIterator = function(line, row, startIndex) { var matches = lang.getMatchOffsets(line, re); for (var i = matches.length-1; i >= 0; i--) if (callback(matches[i], row, startIndex)) return true; } } else { var matchIterator = function(line, row, startIndex) { var matches = lang.getMatchOffsets(line, re); for (var i = 0; i < matches.length; i++) if (callback(matches[i], row, startIndex)) return true; } } return { forEach: function(_callback) { callback = _callback; self.$lineIterator(session, options).forEach(matchIterator); } }; }; this.$assembleRegExp = function(options) { if (options.needle instanceof RegExp) return options.re = options.needle; var needle = options.needle; if (!options.needle) return options.re = false; if (!options.regExp) needle = lang.escapeRegExp(needle); if (options.wholeWord) needle = "\\b" + needle + "\\b"; var modifier = options.caseSensitive ? "g" : "gi"; options.$isMultiLine = /[\n\r]/.test(needle); if (options.$isMultiLine) return options.re = this.$assembleMultilineRegExp(needle, modifier); try { var re = new RegExp(needle, modifier); } catch(e) { var re = false; } return options.re = re; }; this.$assembleMultilineRegExp = function(needle, modifier) { var parts = needle.replace(/\r\n|\r|\n/g, "$\n^").split("\n"); var re = []; for (var i = 0; i < parts.length; i++) try { re.push(new RegExp(parts[i], modifier)); } catch(e) { return false; } if (parts[0] == "") { re.shift(); re.offset = 1; } else { re.offset = 0; } return re; }; this.$lineIterator = function(session, options) { var range = options.range; var backwards = options.backwards == true; var skipCurrent = options.skipCurrent != false; var range = options.range; var start = options.start; if (!start) start = range ? range[backwards ? "end" : "start"] : session.selection.getRange(); if (start.start) start = start[skipCurrent != backwards ? "end" : "start"]; var firstRow = range ? range.start.row : 0; var firstColumn = range ? range.start.column : 0; var lastRow = range ? range.end.row : session.getLength() - 1; if (!backwards) { var forEach = function(callback) { var row = start.row; var line = session.getLine(row).substr(start.column); if (callback(line, row, start.column)) return; for (row = row+1; row <= lastRow; row++) if (callback(session.getLine(row), row)) return; if (options.wrap == false) return; for (row = firstRow, lastRow = start.row; row <= lastRow; row++) if (callback(session.getLine(row), row)) return; } } else { var forEach = function(callback) { var row = start.row; var line = session.getLine(row).substring(0, start.column); if (callback(line, row)) return; for (row--; row >= firstRow; row--) if (callback(session.getLine(row), row)) return; if (options.wrap == false) return; for (row = lastRow, firstRow = start.row; row >= firstRow; row--) if (callback(session.getLine(row), row)) return; } } return {forEach: forEach}; }; }).call(Search.prototype); exports.Search = Search; }); define('ace/commands/command_manager', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/keyboard/hash_handler', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("../lib/oop"); var HashHandler = require("../keyboard/hash_handler").HashHandler; var EventEmitter = require("../lib/event_emitter").EventEmitter; /** * new CommandManager(platform, commands) * - platform (String): Identifier for the platform; must be either `'mac'` or `'win'` * - commands (Array): A list of commands * * TODO * * **/ var CommandManager = function(platform, commands) { this.platform = platform; this.commands = {}; this.commmandKeyBinding = {}; this.addCommands(commands); this.setDefaultHandler("exec", function(e) { return e.command.exec(e.editor, e.args || {}); }); }; oop.inherits(CommandManager, HashHandler); (function() { oop.implement(this, EventEmitter); this.exec = function(command, editor, args) { if (typeof command === 'string') command = this.commands[command]; if (!command) return false; if (editor && editor.$readOnly && !command.readOnly) return false; var retvalue = this._emit("exec", { editor: editor, command: command, args: args }); return retvalue === false ? false : true; }; this.toggleRecording = function() { if (this.$inReplay) return; 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(); 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); exports.CommandManager = CommandManager; }); define('ace/keyboard/hash_handler', ['require', 'exports', 'module' , 'ace/lib/keys'], function(require, exports, module) { var keyUtil = require("../lib/keys"); function HashHandler(config, platform) { this.platform = platform; this.commands = {}; this.commmandKeyBinding = {}; this.addCommands(config); }; (function() { this.addCommand = function(command) { if (this.commands[command.name]) this.removeCommand(command); this.commands[command.name] = command; if (command.bindKey) this._buildKeyHash(command); }; this.removeCommand = function(command) { var name = (typeof command === 'string' ? command : command.name); command = this.commands[name]; delete this.commands[name]; // exhaustive search is brute force but since removeCommand is // not a performance critical operation this should be OK var ckb = this.commmandKeyBinding; for (var hashId in ckb) { for (var key in ckb[hashId]) { if (ckb[hashId][key] == command) delete ckb[hashId][key]; } } }; this.bindKey = function(key, command) { if(!key) return; if (typeof command == "function") { this.addCommand({exec: command, bindKey: key, name: key}); return; } var ckb = this.commmandKeyBinding; key.split("|").forEach(function(keyPart) { var binding = this.parseKeys(keyPart, command); var hashId = binding.hashId; (ckb[hashId] || (ckb[hashId] = {}))[binding.key] = command; }, this); }; this.addCommands = function(commands) { commands && Object.keys(commands).forEach(function(name) { var command = commands[name]; if (typeof command === "string") return this.bindKey(command, name); if (typeof command === "function") command = { exec: command }; if (!command.name) command.name = name; this.addCommand(command); }, this); }; this.removeCommands = function(commands) { Object.keys(commands).forEach(function(name) { this.removeCommand(commands[name]); }, this); }; this.bindKeys = function(keyList) { Object.keys(keyList).forEach(function(key) { this.bindKey(key, keyList[key]); }, this); }; this._buildKeyHash = function(command) { var binding = command.bindKey; if (!binding) return; var key = typeof binding == "string" ? binding: binding[this.platform]; this.bindKey(key, command); }; this.parseKeys = function(keys) { var key; var hashId = 0; var parts = keys.toLowerCase().trim().split(/\s*\-\s*/); for (var i = 0, l = parts.length; i < l; i++) { if (keyUtil.KEY_MODS[parts[i]]) hashId = hashId | keyUtil.KEY_MODS[parts[i]]; else key = parts[i] || "-"; //when empty, the splitSafe removed a '-' } if (parts[0] == "text" && parts.length == 2) { hashId = -1; key = parts[1]; } return { key: key, hashId: hashId }; }; this.findKeyCommand = function findKeyCommand(hashId, keyString) { var ckbr = this.commmandKeyBinding; return ckbr[hashId] && ckbr[hashId][keyString.toLowerCase()]; }; this.handleKeyboard = function(data, hashId, keyString, keyCode) { return { command: this.findKeyCommand(hashId, keyString) }; }; }).call(HashHandler.prototype) exports.HashHandler = HashHandler; }); define('ace/commands/default_commands', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) { var lang = require("../lib/lang"); function bindKey(win, mac) { return { win: win, mac: mac }; } exports.commands = [{ name: "selectall", bindKey: bindKey("Ctrl-A", "Command-A"), exec: function(editor) { editor.selectAll(); }, readOnly: true }, { name: "centerselection", bindKey: bindKey(null, "Ctrl-L"), exec: function(editor) { editor.centerSelection(); }, readOnly: true }, { name: "gotoline", bindKey: bindKey("Ctrl-L", "Command-L"), exec: function(editor) { var line = parseInt(prompt("Enter line number:"), 10); if (!isNaN(line)) { editor.gotoLine(line); } }, readOnly: true }, { name: "fold", bindKey: bindKey("Alt-L", "Alt-L"), exec: function(editor) { editor.session.toggleFold(false); }, readOnly: true }, { name: "unfold", bindKey: bindKey("Alt-Shift-L", "Alt-Shift-L"), exec: function(editor) { editor.session.toggleFold(true); }, readOnly: true }, { name: "foldall", bindKey: bindKey("Alt-0", "Alt-0"), exec: function(editor) { editor.session.foldAll(); }, readOnly: true }, { name: "unfoldall", bindKey: bindKey("Alt-Shift-0", "Alt-Shift-0"), exec: function(editor) { editor.session.unfold(); }, readOnly: true }, { name: "findnext", bindKey: bindKey("Ctrl-K", "Command-G"), exec: function(editor) { editor.findNext(); }, readOnly: true }, { name: "findprevious", bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"), exec: function(editor) { editor.findPrevious(); }, readOnly: true }, { name: "find", bindKey: bindKey("Ctrl-F", "Command-F"), exec: function(editor) { var needle = prompt("Find:", editor.getCopyText()); editor.find(needle); }, readOnly: true }, { name: "overwrite", bindKey: bindKey("Insert", "Insert"), exec: function(editor) { editor.toggleOverwrite(); }, readOnly: true }, { name: "selecttostart", bindKey: bindKey("Ctrl-Shift-Home|Alt-Shift-Up", "Command-Shift-Up"), exec: function(editor) { editor.getSelection().selectFileStart(); }, readOnly: true }, { name: "gotostart", bindKey: bindKey("Ctrl-Home|Ctrl-Up", "Command-Home|Command-Up"), exec: function(editor) { editor.navigateFileStart(); }, readOnly: true }, { name: "selectup", bindKey: bindKey("Shift-Up", "Shift-Up"), exec: function(editor) { editor.getSelection().selectUp(); }, multiSelectAction: "forEach", readOnly: true }, { name: "golineup", bindKey: bindKey("Up", "Up|Ctrl-P"), exec: function(editor, args) { editor.navigateUp(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selecttoend", bindKey: bindKey("Ctrl-Shift-End|Alt-Shift-Down", "Command-Shift-Down"), exec: function(editor) { editor.getSelection().selectFileEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotoend", bindKey: bindKey("Ctrl-End|Ctrl-Down", "Command-End|Command-Down"), exec: function(editor) { editor.navigateFileEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectdown", bindKey: bindKey("Shift-Down", "Shift-Down"), exec: function(editor) { editor.getSelection().selectDown(); }, multiSelectAction: "forEach", readOnly: true }, { name: "golinedown", bindKey: bindKey("Down", "Down|Ctrl-N"), exec: function(editor, args) { editor.navigateDown(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectwordleft", bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), exec: function(editor) { editor.getSelection().selectWordLeft(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotowordleft", bindKey: bindKey("Ctrl-Left", "Option-Left"), exec: function(editor) { editor.navigateWordLeft(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selecttolinestart", bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left"), exec: function(editor) { editor.getSelection().selectLineStart(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotolinestart", bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), exec: function(editor) { editor.navigateLineStart(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectleft", bindKey: bindKey("Shift-Left", "Shift-Left"), exec: function(editor) { editor.getSelection().selectLeft(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotoleft", bindKey: bindKey("Left", "Left|Ctrl-B"), exec: function(editor, args) { editor.navigateLeft(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectwordright", bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), exec: function(editor) { editor.getSelection().selectWordRight(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotowordright", bindKey: bindKey("Ctrl-Right", "Option-Right"), exec: function(editor) { editor.navigateWordRight(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selecttolineend", bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right"), exec: function(editor) { editor.getSelection().selectLineEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotolineend", bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), exec: function(editor) { editor.navigateLineEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectright", bindKey: bindKey("Shift-Right", "Shift-Right"), exec: function(editor) { editor.getSelection().selectRight(); }, multiSelectAction: "forEach", readOnly: true }, { name: "gotoright", bindKey: bindKey("Right", "Right|Ctrl-F"), exec: function(editor, args) { editor.navigateRight(args.times); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectpagedown", bindKey: bindKey("Shift-PageDown", "Shift-PageDown"), exec: function(editor) { editor.selectPageDown(); }, readOnly: true }, { name: "pagedown", bindKey: bindKey(null, "PageDown"), exec: function(editor) { editor.scrollPageDown(); }, readOnly: true }, { name: "gotopagedown", bindKey: bindKey("PageDown", "Option-PageDown|Ctrl-V"), exec: function(editor) { editor.gotoPageDown(); }, readOnly: true }, { name: "selectpageup", bindKey: bindKey("Shift-PageUp", "Shift-PageUp"), exec: function(editor) { editor.selectPageUp(); }, readOnly: true }, { name: "pageup", bindKey: bindKey(null, "PageUp"), exec: function(editor) { editor.scrollPageUp(); }, readOnly: true }, { name: "gotopageup", bindKey: bindKey("PageUp", "Option-PageUp"), exec: function(editor) { editor.gotoPageUp(); }, readOnly: true }, { name: "selectlinestart", bindKey: bindKey("Shift-Home", "Shift-Home"), exec: function(editor) { editor.getSelection().selectLineStart(); }, multiSelectAction: "forEach", readOnly: true }, { name: "selectlineend", bindKey: bindKey("Shift-End", "Shift-End"), exec: function(editor) { editor.getSelection().selectLineEnd(); }, multiSelectAction: "forEach", readOnly: true }, { name: "togglerecording", bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"), exec: function(editor) { editor.commands.toggleRecording(); }, readOnly: true }, { name: "replaymacro", bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"), exec: function(editor) { editor.commands.replay(editor); }, readOnly: true }, { name: "jumptomatching", bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"), exec: function(editor) { editor.jumpToMatching(); }, multiSelectAction: "forEach", readOnly: true }, // commands disabled in readOnly mode { name: "cut", exec: function(editor) { var range = editor.getSelectionRange(); editor._emit("cut", range); if (!editor.selection.isEmpty()) { editor.session.remove(range); editor.clearSelection(); } }, multiSelectAction: "forEach" }, { name: "removeline", bindKey: bindKey("Ctrl-D", "Command-D"), exec: function(editor) { editor.removeLines(); }, multiSelectAction: "forEach" }, { name: "togglecomment", bindKey: bindKey("Ctrl-/", "Command-/"), exec: function(editor) { editor.toggleCommentLines(); }, multiSelectAction: "forEach" }, { name: "replace", bindKey: bindKey("Ctrl-R", "Command-Option-F"), exec: function(editor) { var needle = prompt("Find:", editor.getCopyText()); if (!needle) return; var replacement = prompt("Replacement:"); if (!replacement) return; editor.replace(replacement, {needle: needle}); } }, { name: "replaceall", bindKey: bindKey("Ctrl-Shift-R", "Command-Shift-Option-F"), exec: function(editor) { var needle = prompt("Find:"); if (!needle) return; var replacement = prompt("Replacement:"); if (!replacement) return; editor.replaceAll(replacement, {needle: needle}); } }, { name: "undo", bindKey: bindKey("Ctrl-Z", "Command-Z"), exec: function(editor) { editor.undo(); } }, { name: "redo", bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"), exec: function(editor) { editor.redo(); } }, { name: "copylinesup", bindKey: bindKey("Ctrl-Alt-Up", "Command-Option-Up"), exec: function(editor) { editor.copyLinesUp(); } }, { name: "movelinesup", bindKey: bindKey("Alt-Up", "Option-Up"), exec: function(editor) { editor.moveLinesUp(); } }, { name: "copylinesdown", bindKey: bindKey("Ctrl-Alt-Down", "Command-Option-Down"), exec: function(editor) { editor.copyLinesDown(); } }, { name: "movelinesdown", bindKey: bindKey("Alt-Down", "Option-Down"), exec: function(editor) { editor.moveLinesDown(); } }, { name: "del", bindKey: bindKey("Delete", "Delete|Ctrl-D"), exec: function(editor) { editor.remove("right"); }, multiSelectAction: "forEach" }, { name: "backspace", bindKey: bindKey( "Command-Backspace|Option-Backspace|Shift-Backspace|Backspace", "Ctrl-Backspace|Command-Backspace|Shift-Backspace|Backspace|Ctrl-H" ), exec: function(editor) { editor.remove("left"); }, multiSelectAction: "forEach" }, { name: "removetolinestart", bindKey: bindKey("Alt-Backspace", "Command-Backspace"), exec: function(editor) { editor.removeToLineStart(); }, multiSelectAction: "forEach" }, { name: "removetolineend", bindKey: bindKey("Alt-Delete", "Ctrl-K"), exec: function(editor) { editor.removeToLineEnd(); }, multiSelectAction: "forEach" }, { name: "removewordleft", bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), exec: function(editor) { editor.removeWordLeft(); }, multiSelectAction: "forEach" }, { name: "removewordright", bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), exec: function(editor) { editor.removeWordRight(); }, multiSelectAction: "forEach" }, { name: "outdent", bindKey: bindKey("Shift-Tab", "Shift-Tab"), exec: function(editor) { editor.blockOutdent(); }, multiSelectAction: "forEach" }, { name: "indent", bindKey: bindKey("Tab", "Tab"), exec: function(editor) { editor.indent(); }, multiSelectAction: "forEach" }, { name: "insertstring", exec: function(editor, str) { editor.insert(str); }, multiSelectAction: "forEach" }, { name: "inserttext", exec: function(editor, args) { editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); }, multiSelectAction: "forEach" }, { name: "splitline", bindKey: bindKey(null, "Ctrl-O"), exec: function(editor) { editor.splitLine(); }, multiSelectAction: "forEach" }, { name: "transposeletters", bindKey: bindKey("Ctrl-T", "Ctrl-T"), exec: function(editor) { editor.transposeLetters(); }, multiSelectAction: function(editor) {editor.transposeSelections(1); } }, { name: "touppercase", bindKey: bindKey("Ctrl-U", "Ctrl-U"), exec: function(editor) { editor.toUpperCase(); }, multiSelectAction: "forEach" }, { name: "tolowercase", bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), exec: function(editor) { editor.toLowerCase(); }, multiSelectAction: "forEach" }]; }); define('ace/undomanager', ['require', 'exports', 'module' ], function(require, exports, module) { /** * class UndoManager * * This object maintains the undo stack for an [[EditSession `EditSession`]]. * **/ /** * new UndoManager() * * Resets the current undo state and creates a new `UndoManager`. **/ var UndoManager = function() { this.reset(); }; (function() { /** * UndoManager.execute(options) -> Void * - options (Object): Contains additional properties * * Provides a means for implementing your own undo manager. `options` has one property, `args`, an [[Array `Array`]], with two elements: * * `args[0]` is an array of deltas * * `args[1]` is the document to associate with * **/ this.execute = function(options) { var deltas = options.args[0]; this.$doc = options.args[1]; this.$undoStack.push(deltas); this.$redoStack = []; }; this.undo = function(dontSelect) { var deltas = this.$undoStack.pop(); var undoSelectionRange = null; if (deltas) { undoSelectionRange = this.$doc.undoChanges(deltas, dontSelect); this.$redoStack.push(deltas); } return undoSelectionRange; }; this.redo = function(dontSelect) { var deltas = this.$redoStack.pop(); var redoSelectionRange = null; if (deltas) { redoSelectionRange = this.$doc.redoChanges(deltas, dontSelect); this.$undoStack.push(deltas); } return redoSelectionRange; }; this.reset = function() { this.$undoStack = []; this.$redoStack = []; }; this.hasUndo = function() { return this.$undoStack.length > 0; }; this.hasRedo = function() { return this.$redoStack.length > 0; }; }).call(UndoManager.prototype); exports.UndoManager = UndoManager; }); define('ace/virtual_renderer', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/event', 'ace/lib/useragent', 'ace/config', 'ace/lib/net', 'ace/layer/gutter', 'ace/layer/marker', 'ace/layer/text', 'ace/layer/cursor', 'ace/scrollbar', 'ace/renderloop', 'ace/lib/event_emitter', 'text!ace/css/editor.css'], function(require, exports, module) { var oop = require("./lib/oop"); var dom = require("./lib/dom"); var event = require("./lib/event"); var useragent = require("./lib/useragent"); var config = require("./config"); var net = require("./lib/net"); var GutterLayer = require("./layer/gutter").Gutter; var MarkerLayer = require("./layer/marker").Marker; var TextLayer = require("./layer/text").Text; var CursorLayer = require("./layer/cursor").Cursor; var ScrollBar = require("./scrollbar").ScrollBar; var RenderLoop = require("./renderloop").RenderLoop; var EventEmitter = require("./lib/event_emitter").EventEmitter; var editorCss = require("text!./css/editor.css"); dom.importCssString(editorCss, "ace_editor"); /** * new VirtualRenderer(container, theme) * - container (DOMElement): The root element of the editor * - theme (String): The starting theme * * Constructs a new `VirtualRenderer` within the `container` specified, applying the given `theme`. * **/ var VirtualRenderer = function(container, theme) { var _self = this; this.container = container; // TODO: this breaks rendering in Cloud9 with multiple ace instances // // Imports CSS once per DOM document ('ace_editor' serves as an identifier). // dom.importCssString(editorCss, "ace_editor", container.ownerDocument); // in IE <= 9 the native cursor always shines through this.$keepTextAreaAtCursor = !useragent.isIE; dom.addCssClass(container, "ace_editor"); this.setTheme(theme); this.$gutter = dom.createElement("div"); this.$gutter.className = "ace_gutter"; this.container.appendChild(this.$gutter); this.scroller = dom.createElement("div"); this.scroller.className = "ace_scroller"; this.container.appendChild(this.scroller); this.content = dom.createElement("div"); this.content.className = "ace_content"; this.scroller.appendChild(this.content); this.$gutterLayer = new GutterLayer(this.$gutter); this.$gutterLayer.on("changeGutterWidth", this.onResize.bind(this, true)); this.setFadeFoldWidgets(true); this.$markerBack = new MarkerLayer(this.content); var textLayer = this.$textLayer = new TextLayer(this.content); this.canvas = textLayer.element; this.$markerFront = new MarkerLayer(this.content); this.characterWidth = textLayer.getCharacterWidth(); this.lineHeight = textLayer.getLineHeight(); this.$cursorLayer = new CursorLayer(this.content); this.$cursorPadding = 8; // Indicates whether the horizontal scrollbar is visible this.$horizScroll = false; this.$horizScrollAlwaysVisible = false; this.$animatedScroll = false; this.scrollBar = new ScrollBar(container); this.scrollBar.addEventListener("scroll", function(e) { if (!_self.$inScrollAnimation) _self.session.setScrollTop(e.data); }); this.scrollTop = 0; this.scrollLeft = 0; event.addListener(this.scroller, "scroll", function() { var scrollLeft = _self.scroller.scrollLeft; _self.scrollLeft = scrollLeft; _self.session.setScrollLeft(scrollLeft); }); this.cursorPos = { row : 0, column : 0 }; this.$textLayer.addEventListener("changeCharacterSize", function() { _self.characterWidth = textLayer.getCharacterWidth(); _self.lineHeight = textLayer.getLineHeight(); _self.$updatePrintMargin(); _self.onResize(true); _self.$loop.schedule(_self.CHANGE_FULL); }); this.$size = { width: 0, height: 0, scrollerHeight: 0, scrollerWidth: 0 }; this.layerConfig = { width : 1, padding : 0, firstRow : 0, firstRowScreen: 0, lastRow : 0, lineHeight : 1, characterWidth : 1, minHeight : 1, maxHeight : 1, offset : 0, height : 1 }; this.$loop = new RenderLoop( this.$renderChanges.bind(this), this.container.ownerDocument.defaultView ); this.$loop.schedule(this.CHANGE_FULL); this.setPadding(4); this.$updatePrintMargin(); }; (function() { this.showGutter = true; this.CHANGE_CURSOR = 1; this.CHANGE_MARKER = 2; this.CHANGE_GUTTER = 4; this.CHANGE_SCROLL = 8; this.CHANGE_LINES = 16; this.CHANGE_TEXT = 32; this.CHANGE_SIZE = 64; this.CHANGE_MARKER_BACK = 128; this.CHANGE_MARKER_FRONT = 256; this.CHANGE_FULL = 512; this.CHANGE_H_SCROLL = 1024; oop.implement(this, EventEmitter); this.setSession = function(session) { this.session = session; this.scroller.className = "ace_scroller"; this.$cursorLayer.setSession(session); this.$markerBack.setSession(session); this.$markerFront.setSession(session); this.$gutterLayer.setSession(session); this.$textLayer.setSession(session); this.$loop.schedule(this.CHANGE_FULL); }; this.updateLines = function(firstRow, lastRow) { if (lastRow === undefined) lastRow = Infinity; if (!this.$changedLines) { this.$changedLines = { firstRow: firstRow, lastRow: lastRow }; } else { if (this.$changedLines.firstRow > firstRow) this.$changedLines.firstRow = firstRow; if (this.$changedLines.lastRow < lastRow) this.$changedLines.lastRow = lastRow; } this.$loop.schedule(this.CHANGE_LINES); }; this.updateText = function() { this.$loop.schedule(this.CHANGE_TEXT); }; this.updateFull = function() { this.$loop.schedule(this.CHANGE_FULL); }; this.updateFontSize = function() { this.$textLayer.checkForSizeChanges(); }; this.onResize = function(force) { var changes = this.CHANGE_SIZE; var size = this.$size; var height = dom.getInnerHeight(this.container); if (force || size.height != height) { size.height = height; this.scroller.style.height = height + "px"; size.scrollerHeight = this.scroller.clientHeight; this.scrollBar.setHeight(size.scrollerHeight); if (this.session) { this.session.setScrollTop(this.getScrollTop()); changes = changes | this.CHANGE_FULL; } } var width = dom.getInnerWidth(this.container); if (force || size.width != width) { size.width = width; var gutterWidth = this.showGutter ? this.$gutter.offsetWidth : 0; this.scroller.style.left = gutterWidth + "px"; size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBar.getWidth()); this.scroller.style.width = size.scrollerWidth + "px"; if (this.session.getUseWrapMode() && this.adjustWrapLimit() || force) changes = changes | this.CHANGE_FULL; } this.$loop.schedule(changes); }; this.adjustWrapLimit = function() { var availableWidth = this.$size.scrollerWidth - this.$padding * 2; var limit = Math.floor(availableWidth / this.characterWidth); return this.session.adjustWrapLimit(limit); }; this.setAnimatedScroll = function(shouldAnimate){ this.$animatedScroll = shouldAnimate; }; this.getAnimatedScroll = function() { return this.$animatedScroll; }; this.setShowInvisibles = function(showInvisibles) { if (this.$textLayer.setShowInvisibles(showInvisibles)) this.$loop.schedule(this.CHANGE_TEXT); }; this.getShowInvisibles = function() { return this.$textLayer.showInvisibles; }; this.$showPrintMargin = true; this.setShowPrintMargin = function(showPrintMargin) { this.$showPrintMargin = showPrintMargin; this.$updatePrintMargin(); }; this.getShowPrintMargin = function() { return this.$showPrintMargin; }; this.$printMarginColumn = 80; this.setPrintMarginColumn = function(showPrintMargin) { this.$printMarginColumn = showPrintMargin; this.$updatePrintMargin(); }; this.getPrintMarginColumn = function() { return this.$printMarginColumn; }; this.getShowGutter = function(){ return this.showGutter; }; this.setShowGutter = function(show){ if(this.showGutter === show) return; this.$gutter.style.display = show ? "block" : "none"; this.showGutter = show; this.onResize(true); }; this.getFadeFoldWidgets = function(){ return dom.hasCssClass(this.$gutter, "ace_fade-fold-widgets"); }; this.setFadeFoldWidgets = function(show) { if (show) dom.addCssClass(this.$gutter, "ace_fade-fold-widgets"); else dom.removeCssClass(this.$gutter, "ace_fade-fold-widgets"); }; this.$highlightGutterLine = true; this.setHighlightGutterLine = function(shouldHighlight) { if (this.$highlightGutterLine == shouldHighlight) return; this.$highlightGutterLine = shouldHighlight; this.$loop.schedule(this.CHANGE_GUTTER); }; this.getHighlightGutterLine = function() { return this.$highlightGutterLine; }; this.$updateGutterLineHighlight = function(gutterReady) { var i = this.session.selection.lead.row; if (i == this.$gutterLineHighlight) return; if (!gutterReady) { var ch = this.$gutterLayer.element.children var oldEl = ch[this.$gutterLineHighlight - this.layerConfig.firstRow]; if (oldEl) dom.removeCssClass(oldEl, "ace_gutter_active_line"); var newEl = ch[i - this.layerConfig.firstRow]; if (newEl) dom.addCssClass(newEl, "ace_gutter_active_line"); } this.$gutterLayer.removeGutterDecoration(this.$gutterLineHighlight, "ace_gutter_active_line"); this.$gutterLayer.addGutterDecoration(i, "ace_gutter_active_line"); this.$gutterLineHighlight = i; }; this.$updatePrintMargin = function() { var containerEl; if (!this.$showPrintMargin && !this.$printMarginEl) return; if (!this.$printMarginEl) { containerEl = dom.createElement("div"); containerEl.className = "ace_print_margin_layer"; this.$printMarginEl = dom.createElement("div"); this.$printMarginEl.className = "ace_print_margin"; containerEl.appendChild(this.$printMarginEl); this.content.insertBefore(containerEl, this.$textLayer.element); } var style = this.$printMarginEl.style; style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px"; style.visibility = this.$showPrintMargin ? "visible" : "hidden"; }; this.getContainerElement = function() { return this.container; }; this.getMouseEventTarget = function() { return this.content; }; this.getTextAreaContainer = function() { return this.container; }; // move text input over the cursor // this is required for iOS and IME this.$moveTextAreaToCursor = function() { if (!this.$keepTextAreaAtCursor) return; var posTop = this.$cursorLayer.$pixelPos.top; var posLeft = this.$cursorLayer.$pixelPos.left; posTop -= this.layerConfig.offset; if (posTop < 0 || posTop > this.layerConfig.height - this.lineHeight) return; var w = this.characterWidth; if (this.$composition) w += this.textarea.scrollWidth; posLeft -= this.scrollLeft; if (posLeft > this.$size.scrollerWidth - w) posLeft = this.$size.scrollerWidth - w; if (this.showGutter) posLeft += this.$gutterLayer.gutterWidth; this.textarea.style.height = this.lineHeight + "px"; this.textarea.style.width = w + "px"; this.textarea.style.left = posLeft + "px"; this.textarea.style.top = posTop - 1 + "px"; }; this.getFirstVisibleRow = function() { return this.layerConfig.firstRow; }; this.getFirstFullyVisibleRow = function() { return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1); }; this.getLastFullyVisibleRow = function() { var flint = Math.floor((this.layerConfig.height + this.layerConfig.offset) / this.layerConfig.lineHeight); return this.layerConfig.firstRow - 1 + flint; }; this.getLastVisibleRow = function() { return this.layerConfig.lastRow; }; this.$padding = null; this.setPadding = function(padding) { this.$padding = padding; this.$textLayer.setPadding(padding); this.$cursorLayer.setPadding(padding); this.$markerFront.setPadding(padding); this.$markerBack.setPadding(padding); this.$loop.schedule(this.CHANGE_FULL); this.$updatePrintMargin(); }; this.getHScrollBarAlwaysVisible = function() { return this.$horizScrollAlwaysVisible; }; this.setHScrollBarAlwaysVisible = function(alwaysVisible) { if (this.$horizScrollAlwaysVisible != alwaysVisible) { this.$horizScrollAlwaysVisible = alwaysVisible; if (!this.$horizScrollAlwaysVisible || !this.$horizScroll) this.$loop.schedule(this.CHANGE_SCROLL); } }; this.$updateScrollBar = function() { this.scrollBar.setInnerHeight(this.layerConfig.maxHeight); this.scrollBar.setScrollTop(this.scrollTop); }; this.$renderChanges = function(changes) { if (!changes || !this.session || !this.container.offsetWidth) return; // text, scrolling and resize changes can cause the view port size to change if (changes & this.CHANGE_FULL || changes & this.CHANGE_SIZE || changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES || changes & this.CHANGE_SCROLL ) this.$computeLayerConfig(); // horizontal scrolling if (changes & this.CHANGE_H_SCROLL) { this.scroller.scrollLeft = this.scrollLeft; // read the value after writing it since the value might get clipped var scrollLeft = this.scroller.scrollLeft; this.scrollLeft = scrollLeft; this.session.setScrollLeft(scrollLeft); this.scroller.className = this.scrollLeft == 0 ? "ace_scroller" : "ace_scroller horscroll"; } // full if (changes & this.CHANGE_FULL) { this.$textLayer.checkForSizeChanges(); // update scrollbar first to not lose scroll position when gutter calls resize this.$updateScrollBar(); this.$textLayer.update(this.layerConfig); if (this.showGutter) { if (this.$highlightGutterLine) this.$updateGutterLineHighlight(true); this.$gutterLayer.update(this.layerConfig); } this.$markerBack.update(this.layerConfig); this.$markerFront.update(this.layerConfig); this.$cursorLayer.update(this.layerConfig); this.$moveTextAreaToCursor(); return; } // scrolling if (changes & this.CHANGE_SCROLL) { this.$updateScrollBar(); if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) this.$textLayer.update(this.layerConfig); else this.$textLayer.scrollLines(this.layerConfig); if (this.showGutter) { if (this.$highlightGutterLine) this.$updateGutterLineHighlight(true); this.$gutterLayer.update(this.layerConfig); } this.$markerBack.update(this.layerConfig); this.$markerFront.update(this.layerConfig); this.$cursorLayer.update(this.layerConfig); this.$moveTextAreaToCursor(); return; } if (changes & this.CHANGE_TEXT) { this.$textLayer.update(this.layerConfig); if (this.showGutter) this.$gutterLayer.update(this.layerConfig); } else if (changes & this.CHANGE_LINES) { if (this.$updateLines()) { this.$updateScrollBar(); if (this.showGutter) this.$gutterLayer.update(this.layerConfig); } } else if (changes & this.CHANGE_GUTTER) { if (this.showGutter) this.$gutterLayer.update(this.layerConfig); } if (changes & this.CHANGE_CURSOR) { this.$cursorLayer.update(this.layerConfig); this.$moveTextAreaToCursor(); this.$highlightGutterLine && this.$updateGutterLineHighlight(false); } if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) { this.$markerFront.update(this.layerConfig); } if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) { this.$markerBack.update(this.layerConfig); } if (changes & this.CHANGE_SIZE) this.$updateScrollBar(); }; this.$computeLayerConfig = function() { var session = this.session; var offset = this.scrollTop % this.lineHeight; var minHeight = this.$size.scrollerHeight + this.lineHeight; var longestLine = this.$getLongestLine(); var horizScroll = this.$horizScrollAlwaysVisible || this.$size.scrollerWidth - longestLine < 0; var horizScrollChanged = this.$horizScroll !== horizScroll; this.$horizScroll = horizScroll; if (horizScrollChanged) { this.scroller.style.overflowX = horizScroll ? "scroll" : "hidden"; // when we hide scrollbar scroll event isn't emited // leaving session with wrong scrollLeft value if (!horizScroll) this.session.setScrollLeft(0); } var maxHeight = this.session.getScreenLength() * this.lineHeight; this.session.setScrollTop(Math.max(0, Math.min(this.scrollTop, maxHeight - this.$size.scrollerHeight))); var lineCount = Math.ceil(minHeight / this.lineHeight) - 1; var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight)); var lastRow = firstRow + lineCount; // Map lines on the screen to lines in the document. var firstRowScreen, firstRowHeight; var lineHeight = { lineHeight: this.lineHeight }; firstRow = session.screenToDocumentRow(firstRow, 0); // Check if firstRow is inside of a foldLine. If true, then use the first // row of the foldLine. var foldLine = session.getFoldLine(firstRow); if (foldLine) { firstRow = foldLine.start.row; } firstRowScreen = session.documentToScreenRow(firstRow, 0); firstRowHeight = session.getRowHeight(lineHeight, firstRow); lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1); minHeight = this.$size.scrollerHeight + session.getRowHeight(lineHeight, lastRow)+ firstRowHeight; offset = this.scrollTop - firstRowScreen * this.lineHeight; this.layerConfig = { width : longestLine, padding : this.$padding, firstRow : firstRow, firstRowScreen: firstRowScreen, lastRow : lastRow, lineHeight : this.lineHeight, characterWidth : this.characterWidth, minHeight : minHeight, maxHeight : maxHeight, offset : offset, height : this.$size.scrollerHeight }; // For debugging. // console.log(JSON.stringify(this.layerConfig)); this.$gutterLayer.element.style.marginTop = (-offset) + "px"; this.content.style.marginTop = (-offset) + "px"; this.content.style.width = longestLine + 2 * this.$padding + "px"; this.content.style.height = minHeight + "px"; // Horizontal scrollbar visibility may have changed, which changes // the client height of the scroller if (horizScrollChanged) this.onResize(true); }; this.$updateLines = function() { var firstRow = this.$changedLines.firstRow; var lastRow = this.$changedLines.lastRow; this.$changedLines = null; var layerConfig = this.layerConfig; if (firstRow > layerConfig.lastRow + 1) { return; } if (lastRow < layerConfig.firstRow) { return; } // if the last row is unknown -> redraw everything if (lastRow === Infinity) { if (this.showGutter) this.$gutterLayer.update(layerConfig); this.$textLayer.update(layerConfig); return; } // else update only the changed rows this.$textLayer.updateLines(layerConfig, firstRow, lastRow); return true; }; this.$getLongestLine = function() { var charCount = this.session.getScreenWidth(); if (this.$textLayer.showInvisibles) charCount += 1; return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth)); }; this.updateFrontMarkers = function() { this.$markerFront.setMarkers(this.session.getMarkers(true)); this.$loop.schedule(this.CHANGE_MARKER_FRONT); }; this.updateBackMarkers = function() { this.$markerBack.setMarkers(this.session.getMarkers()); this.$loop.schedule(this.CHANGE_MARKER_BACK); }; this.addGutterDecoration = function(row, className){ this.$gutterLayer.addGutterDecoration(row, className); this.$loop.schedule(this.CHANGE_GUTTER); }; this.removeGutterDecoration = function(row, className){ this.$gutterLayer.removeGutterDecoration(row, className); this.$loop.schedule(this.CHANGE_GUTTER); }; this.updateBreakpoints = function(rows) { this.$loop.schedule(this.CHANGE_GUTTER); }; this.setAnnotations = function(annotations) { this.$gutterLayer.setAnnotations(annotations); this.$loop.schedule(this.CHANGE_GUTTER); }; this.updateCursor = function() { this.$loop.schedule(this.CHANGE_CURSOR); }; this.hideCursor = function() { this.$cursorLayer.hideCursor(); }; this.showCursor = function() { this.$cursorLayer.showCursor(); }; this.scrollSelectionIntoView = function(anchor, lead, offset) { // first scroll anchor into view then scroll lead into view this.scrollCursorIntoView(anchor, offset); this.scrollCursorIntoView(lead, offset); }; this.scrollCursorIntoView = function(cursor, offset) { // the editor is not visible if (this.$size.scrollerHeight === 0) return; var pos = this.$cursorLayer.getPixelPosition(cursor); var left = pos.left; var top = pos.top; if (this.scrollTop > top) { if (offset) top -= offset * this.$size.scrollerHeight; this.session.setScrollTop(top); } else if (this.scrollTop + this.$size.scrollerHeight < top + this.lineHeight) { if (offset) top += offset * this.$size.scrollerHeight; this.session.setScrollTop(top + this.lineHeight - this.$size.scrollerHeight); } var scrollLeft = this.scrollLeft; if (scrollLeft > left) { if (left < this.$padding + 2 * this.layerConfig.characterWidth) left = 0; this.session.setScrollLeft(left); } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); } }; this.getScrollTop = function() { return this.session.getScrollTop(); }; this.getScrollLeft = function() { return this.session.getScrollLeft(); }; this.getScrollTopRow = function() { return this.scrollTop / this.lineHeight; }; this.getScrollBottomRow = function() { return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1); }; this.scrollToRow = function(row) { this.session.setScrollTop(row * this.lineHeight); }; this.alignCursor = function(cursor, alignment) { if (typeof cursor == "number") cursor = {row: cursor, column: 0}; var pos = this.$cursorLayer.getPixelPosition(cursor); var offset = pos.top - this.$size.scrollerHeight * (alignment || 0); this.session.setScrollTop(offset); }; this.STEPS = 8; this.$calcSteps = function(fromValue, toValue){ var i = 0; var l = this.STEPS; var steps = []; var func = function(t, x_min, dx) { return dx * (Math.pow(t - 1, 3) + 1) + x_min; }; for (i = 0; i < l; ++i) steps.push(func(i / this.STEPS, fromValue, toValue - fromValue)); return steps; }; this.scrollToLine = function(line, center, animate, callback) { var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0}); var offset = pos.top; if (center) offset -= this.$size.scrollerHeight / 2; var initialScroll = this.scrollTop; this.session.setScrollTop(offset); if (animate !== false) this.animateScrolling(initialScroll, callback); }; this.animateScrolling = function(fromValue, callback) { var toValue = this.scrollTop; if (this.$animatedScroll && Math.abs(fromValue - toValue) < 100000) { var _self = this; var steps = _self.$calcSteps(fromValue, toValue); this.$inScrollAnimation = true; clearInterval(this.$timer); _self.session.setScrollTop(steps.shift()); this.$timer = setInterval(function() { if (steps.length) { _self.session.setScrollTop(steps.shift()); // trick session to think it's already scrolled to not loose toValue _self.session.$scrollTop = toValue; } else if (toValue != null) { _self.session.$scrollTop = -1; _self.session.setScrollTop(toValue); toValue = null; } else { // do this on separate step to not get spurious scroll event from scrollbar _self.$timer = clearInterval(_self.$timer); _self.$inScrollAnimation = false; callback && callback(); } }, 10); } }; this.scrollToY = function(scrollTop) { // after calling scrollBar.setScrollTop // scrollbar sends us event with same scrollTop. ignore it if (this.scrollTop !== scrollTop) { this.$loop.schedule(this.CHANGE_SCROLL); this.scrollTop = scrollTop; } }; this.scrollToX = function(scrollLeft) { if (scrollLeft < 0) scrollLeft = 0; if (this.scrollLeft !== scrollLeft) this.scrollLeft = scrollLeft; this.$loop.schedule(this.CHANGE_H_SCROLL); }; this.scrollBy = function(deltaX, deltaY) { deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY); deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX); }; this.isScrollableBy = function(deltaX, deltaY) { if (deltaY < 0 && this.session.getScrollTop() > 0) return true; if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight < this.layerConfig.maxHeight) return true; // todo: handle horizontal scrolling }; this.pixelToScreenCoordinates = function(x, y) { var canvasPos = this.scroller.getBoundingClientRect(); var offset = (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth; var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight); var col = Math.round(offset); return {row: row, column: col, side: offset - col > 0 ? 1 : -1}; }; this.screenToTextCoordinates = function(x, y) { var canvasPos = this.scroller.getBoundingClientRect(); var col = Math.round( (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth ); var row = Math.floor( (y + this.scrollTop - canvasPos.top) / this.lineHeight ); return this.session.screenToDocumentPosition(row, Math.max(col, 0)); }; this.textToScreenCoordinates = function(row, column) { var canvasPos = this.scroller.getBoundingClientRect(); var pos = this.session.documentToScreenPosition(row, column); var x = this.$padding + Math.round(pos.column * this.characterWidth); var y = pos.row * this.lineHeight; return { pageX: canvasPos.left + x - this.scrollLeft, pageY: canvasPos.top + y - this.scrollTop }; }; this.visualizeFocus = function() { dom.addCssClass(this.container, "ace_focus"); }; this.visualizeBlur = function() { dom.removeCssClass(this.container, "ace_focus"); }; this.showComposition = function(position) { if (!this.$composition) this.$composition = { keepTextAreaAtCursor: this.$keepTextAreaAtCursor, cssText: this.textarea.style.cssText }; this.$keepTextAreaAtCursor = true; dom.addCssClass(this.textarea, "ace_composition"); this.textarea.style.cssText = ""; this.$moveTextAreaToCursor(); }; this.setCompositionText = function(text) { this.$moveTextAreaToCursor(); }; this.hideComposition = function() { if (!this.$composition) return; dom.removeCssClass(this.textarea, "ace_composition"); this.$keepTextAreaAtCursor = this.$composition.keepTextAreaAtCursor; this.textarea.style.cssText = this.$composition.cssText; this.$composition = null; }; this._loadTheme = function(name, callback) { if (!config.get("packaged")) return callback(); var base = name.split("/").pop(); var filename = config.get("themePath") + "/theme-" + base + config.get("suffix"); net.loadScript(filename, callback); }; this.setTheme = function(theme) { var _self = this; this.$themeValue = theme; if (!theme || typeof theme == "string") { var moduleName = theme || "ace/theme/textmate"; var module; try { module = require(moduleName); } catch (e) {}; if (module) return afterLoad(module); _self._loadTheme(moduleName, function() { require([moduleName], function(module) { if (_self.$themeValue !== theme) return; afterLoad(module); }); }); } else { afterLoad(theme); } function afterLoad(theme) { dom.importCssString( theme.cssText, theme.cssClass, _self.container.ownerDocument ); if (_self.$theme) dom.removeCssClass(_self.container, _self.$theme); _self.$theme = theme ? theme.cssClass : null; if (_self.$theme) dom.addCssClass(_self.container, _self.$theme); if (theme && theme.isDark) dom.addCssClass(_self.container, "ace_dark"); else dom.removeCssClass(_self.container, "ace_dark"); // force re-measure of the gutter width if (_self.$size) { _self.$size.width = 0; _self.onResize(); } } }; this.getTheme = function() { return this.$themeValue; }; // Methods allows to add / remove CSS classnames to the editor element. // This feature can be used by plug-ins to provide a visual indication of // a certain mode that editor is in. /** * VirtualRenderer.setStyle(style) -> Void * - style (String): A class name * * [Adds a new class, `style`, to the editor.]{: #VirtualRenderer.setStyle} **/ this.setStyle = function setStyle(style) { dom.addCssClass(this.container, style); }; this.unsetStyle = function unsetStyle(style) { dom.removeCssClass(this.container, style); }; this.destroy = function() { this.$textLayer.destroy(); this.$cursorLayer.destroy(); }; }).call(VirtualRenderer.prototype); exports.VirtualRenderer = VirtualRenderer; }); define('ace/layer/gutter', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { var dom = require("../lib/dom"); var oop = require("../lib/oop"); var EventEmitter = require("../lib/event_emitter").EventEmitter; var Gutter = function(parentEl) { this.element = dom.createElement("div"); this.element.className = "ace_layer ace_gutter-layer"; parentEl.appendChild(this.element); this.setShowFoldWidgets(this.$showFoldWidgets); this.gutterWidth = 0; this.$breakpoints = []; this.$annotations = []; this.$decorations = []; }; (function() { oop.implement(this, EventEmitter); this.setSession = function(session) { this.session = session; }; this.addGutterDecoration = function(row, className){ if (!this.$decorations[row]) this.$decorations[row] = ""; this.$decorations[row] += " " + className; }; this.removeGutterDecoration = function(row, className){ this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, ""); }; this.setAnnotations = function(annotations) { // iterate over sparse array this.$annotations = []; for (var row in annotations) if (annotations.hasOwnProperty(row)) { var rowAnnotations = annotations[row]; if (!rowAnnotations) continue; var rowInfo = this.$annotations[row] = { text: [] }; for (var i=0; i<rowAnnotations.length; i++) { var annotation = rowAnnotations[i]; var annoText = annotation.text.replace(/"/g, "&quot;").replace(/'/g, "&#8217;").replace(/</, "&lt;"); 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.update = function(config) { this.$config = config; var emptyAnno = {className: "", text: []}; var html = []; var i = config.firstRow; var lastRow = config.lastRow; var fold = this.session.getNextFoldLine(i); var foldStart = fold ? fold.start.row : Infinity; var foldWidgets = this.$showFoldWidgets && this.session.foldWidgets; var breakpoints = this.session.$breakpoints; while (true) { if(i > foldStart) { i = fold.end.row + 1; fold = this.session.getNextFoldLine(i, fold); foldStart = fold ?fold.start.row :Infinity; } if(i > lastRow) break; var annotation = this.$annotations[i] || emptyAnno; html.push("<div class='ace_gutter-cell", this.$decorations[i] || "", breakpoints[i] ? " ace_breakpoint " : " ", annotation.className, "' title='", annotation.text.join("\n"), "' style='height:", this.session.getRowLength(i) * config.lineHeight, "px;'>", (i+1)); if (foldWidgets) { var c = foldWidgets[i]; // check if cached value is invalidated and we need to recompute if (c == null) c = foldWidgets[i] = this.session.getFoldWidget(i); if (c) html.push( "<span class='ace_fold-widget ", c, c == "start" && i == foldStart && i < fold.end.row ? " closed" : " open", "'></span>" ); } html.push("</div>"); i++; } if (this.session.$useWrapMode) html.push( "<div class='ace_gutter-cell' style='pointer-events:none;opacity:0'>", this.session.getLength() - 1, "</div>" ); this.element = dom.setInnerHtml(this.element, html.join("")); this.element.style.height = config.minHeight + "px"; var gutterWidth = this.element.offsetWidth; if (gutterWidth !== this.gutterWidth) { this.gutterWidth = gutterWidth; this._emit("changeGutterWidth", gutterWidth); } }; 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.getShowFoldWidgets = function() { return this.$showFoldWidgets; }; }).call(Gutter.prototype); exports.Gutter = Gutter; }); define('ace/layer/marker', ['require', 'exports', 'module' , 'ace/range', 'ace/lib/dom'], function(require, exports, module) { var Range = require("../range").Range; var dom = require("../lib/dom"); var Marker = function(parentEl) { this.element = dom.createElement("div"); this.element.className = "ace_layer ace_marker-layer"; parentEl.appendChild(this.element); }; (function() { this.$padding = 0; this.setPadding = function(padding) { this.$padding = padding; }; this.setSession = function(session) { this.session = session; }; this.setMarkers = function(markers) { this.markers = markers; }; this.update = function(config) { var config = config || this.config; if (!config) return; this.config = config; var html = []; for ( var key in this.markers) { var marker = this.markers[key]; if (!marker.range) { marker.update(html, this, this.session, config); continue; } var range = marker.range.clipRows(config.firstRow, config.lastRow); if (range.isEmpty()) continue; range = range.toScreenRange(this.session); if (marker.renderer) { var top = this.$getTop(range.start.row, config); var left = Math.round( this.$padding + range.start.column * config.characterWidth ); marker.renderer(html, range, left, top, config); } else if (range.isMultiLine()) { if (marker.type == "text") { this.drawTextMarker(html, range, marker.clazz, config); } else { this.drawMultiLineMarker( html, range, marker.clazz, config, marker.type ); } } else { this.drawSingleLineMarker( html, range, marker.clazz + " start", config, null, marker.type ); } } this.element = dom.setInnerHtml(this.element, html.join("")); }; this.$getTop = function(row, layerConfig) { return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight; }; // Draws a marker, which spans a range of text on multiple lines this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig) { // selection start var row = range.start.row; var lineRange = new Range( row, range.start.column, row, this.session.getScreenLastRowColumn(row) ); this.drawSingleLineMarker(stringBuilder, lineRange, clazz + " start", layerConfig, 1, "text"); // selection end row = range.end.row; lineRange = new Range(row, 0, row, range.end.column); this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 0, "text"); for (row = range.start.row + 1; row < range.end.row; row++) { lineRange.start.row = row; lineRange.end.row = row; lineRange.end.column = this.session.getScreenLastRowColumn(row); this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 1, "text"); } }; // Draws a multi line marker, where lines span the full width this.drawMultiLineMarker = function(stringBuilder, range, clazz, layerConfig, type) { var padding = type === "background" ? 0 : this.$padding; var layerWidth = layerConfig.width + 2 * this.$padding - padding; // from selection start to the end of the line var height = layerConfig.lineHeight; var width = Math.round(layerWidth - (range.start.column * layerConfig.characterWidth)); var top = this.$getTop(range.start.row, layerConfig); var left = Math.round( padding + range.start.column * layerConfig.characterWidth ); stringBuilder.push( "<div class='", clazz, " start' style='", "height:", height, "px;", "width:", width, "px;", "top:", top, "px;", "left:", left, "px;'></div>" ); // from start of the last line to the selection end top = this.$getTop(range.end.row, layerConfig); width = Math.round(range.end.column * layerConfig.characterWidth); stringBuilder.push( "<div class='", clazz, "' style='", "height:", height, "px;", "width:", width, "px;", "top:", top, "px;", "left:", padding, "px;'></div>" ); // all the complete lines height = (range.end.row - range.start.row - 1) * layerConfig.lineHeight; if (height < 0) return; top = this.$getTop(range.start.row + 1, layerConfig); stringBuilder.push( "<div class='", clazz, "' style='", "height:", height, "px;", "width:", layerWidth, "px;", "top:", top, "px;", "left:", padding, "px;'></div>" ); }; // Draws a marker which covers part or whole width of a single screen line this.drawSingleLineMarker = function(stringBuilder, range, clazz, layerConfig, extraLength, type) { var padding = type === "background" ? 0 : this.$padding; var height = layerConfig.lineHeight; if (type === "background") var width = layerConfig.width; else width = Math.round((range.end.column + (extraLength || 0) - range.start.column) * layerConfig.characterWidth); var top = this.$getTop(range.start.row, layerConfig); var left = Math.round( padding + range.start.column * layerConfig.characterWidth ); stringBuilder.push( "<div class='", clazz, "' style='", "height:", height, "px;", "width:", width, "px;", "top:", top, "px;", "left:", left,"px;'></div>" ); }; }).call(Marker.prototype); exports.Marker = Marker; }); define('ace/layer/text', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/lang', 'ace/lib/useragent', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("../lib/oop"); var dom = require("../lib/dom"); var lang = require("../lib/lang"); var useragent = require("../lib/useragent"); var EventEmitter = require("../lib/event_emitter").EventEmitter; var Text = function(parentEl) { this.element = dom.createElement("div"); this.element.className = "ace_layer ace_text-layer"; parentEl.appendChild(this.element); this.$characterSize = this.$measureSizes() || {width: 0, height: 0}; this.$pollSizeChanges(); }; (function() { oop.implement(this, EventEmitter); this.EOF_CHAR = "\xB6"; //"&para;"; this.EOL_CHAR = "\xAC"; //"&not;"; this.TAB_CHAR = "\u2192"; //"&rarr;" "\u21E5"; this.SPACE_CHAR = "\xB7"; //"&middot;"; this.$padding = 0; this.setPadding = function(padding) { this.$padding = padding; this.element.style.padding = "0 " + padding + "px"; }; this.getLineHeight = function() { return this.$characterSize.height || 1; }; this.getCharacterWidth = function() { return this.$characterSize.width || 1; }; this.checkForSizeChanges = function() { var size = this.$measureSizes(); if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { this.$characterSize = size; this._emit("changeCharacterSize", {data: size}); } }; this.$pollSizeChanges = function() { var self = this; this.$pollSizeChangesTimer = setInterval(function() { self.checkForSizeChanges(); }, 500); }; this.$fontStyles = { fontFamily : 1, fontSize : 1, fontWeight : 1, fontStyle : 1, lineHeight : 1 }; this.$measureSizes = useragent.isIE || useragent.isOldGecko ? function() { var n = 1000; if (!this.$measureNode) { var measureNode = this.$measureNode = dom.createElement("div"); var style = measureNode.style; style.width = style.height = "auto"; style.left = style.top = (-n * 40) + "px"; style.visibility = "hidden"; style.position = "fixed"; style.overflow = "visible"; style.whiteSpace = "nowrap"; // in FF 3.6 monospace fonts can have a fixed sub pixel width. // that's why we have to measure many characters // Note: characterWidth can be a float! measureNode.innerHTML = lang.stringRepeat("Xy", n); if (this.element.ownerDocument.body) { this.element.ownerDocument.body.appendChild(measureNode); } else { var container = this.element.parentNode; while (!dom.hasCssClass(container, "ace_editor")) container = container.parentNode; container.appendChild(measureNode); } } // Size and width can be null if the editor is not visible or // detached from the document if (!this.element.offsetWidth) return null; var style = this.$measureNode.style; var computedStyle = dom.computedStyle(this.element); for (var prop in this.$fontStyles) style[prop] = computedStyle[prop]; var size = { height: this.$measureNode.offsetHeight, width: this.$measureNode.offsetWidth / (n * 2) }; // Size and width can be null if the editor is not visible or // detached from the document if (size.width == 0 || size.height == 0) return null; return size; } : function() { if (!this.$measureNode) { var measureNode = this.$measureNode = dom.createElement("div"); var style = measureNode.style; style.width = style.height = "auto"; style.left = style.top = -100 + "px"; style.visibility = "hidden"; style.position = "fixed"; style.overflow = "visible"; style.whiteSpace = "nowrap"; measureNode.innerHTML = "X"; var container = this.element.parentNode; while (container && !dom.hasCssClass(container, "ace_editor")) container = container.parentNode; if (!container) return this.$measureNode = null; container.appendChild(measureNode); } var rect = this.$measureNode.getBoundingClientRect(); var size = { height: rect.height, width: rect.width }; // Size and width can be null if the editor is not visible or // detached from the document if (size.width == 0 || size.height == 0) return null; return size; }; this.setSession = function(session) { this.session = session; }; this.showInvisibles = false; this.setShowInvisibles = function(showInvisibles) { if (this.showInvisibles == showInvisibles) return false; this.showInvisibles = showInvisibles; return true; }; this.$tabStrings = []; this.$computeTabString = function() { var tabSize = this.session.getTabSize(); var tabStr = this.$tabStrings = [0]; for (var i = 1; i < tabSize + 1; i++) { if (this.showInvisibles) { tabStr.push("<span class='ace_invisible'>" + this.TAB_CHAR + new Array(i).join("&#160;") + "</span>"); } else { tabStr.push(new Array(i+1).join("&#160;")); } } }; this.updateLines = function(config, firstRow, lastRow) { this.$computeTabString(); // Due to wrap line changes there can be new lines if e.g. // the line to updated wrapped in the meantime. 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 ++; } for (var i=first; i<=last; i++) { var lineElement = lineElements[lineElementsIdx++]; if (!lineElement) continue; var html = []; var tokens = this.session.getTokens(i); this.$renderLine(html, i, tokens, !this.$useLineGroups()); lineElement = dom.setInnerHtml(lineElement, html.join("")); i = this.session.getRowFoldEnd(i); } }; this.scrollLines = function(config) { this.$computeTabString(); 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 = []; // Get the tokens per line as there might be some lines in between // beeing folded. var tokens = this.session.getTokens(row); this.$renderLine(html, row, tokens, false); // don't use setInnerHtml since we are working with an empty DIV container.innerHTML = html.join(""); if (this.$useLineGroups()) { container.className = 'ace_line_group'; fragment.appendChild(container); } else { var lines = container.childNodes while(lines.length) fragment.appendChild(lines[0]); } row++; } return fragment; }; this.update = function(config) { this.$computeTabString(); 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'>") // Get the tokens per line as there might be some lines in between // beeing folded. var tokens = this.session.getTokens(row); this.$renderLine(html, row, tokens, false); if (this.$useLineGroups()) html.push("</div>"); // end the line group row++; } this.element = dom.setInnerHtml(this.element, html.join("")); }; this.$textToken = { "text": true, "rparen": true, "lparen": true }; this.$renderToken = function(stringBuilder, screenColumn, token, value) { var self = this; var replaceReg = /\t|&|<|( +)|([\u0000-\u0019\u00a0\u1680\u180E\u2000-\u200b\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 new Array(c.length+1).join("&#160;"); } else if (c == "&") { return "&#38;"; } else if (c == "<") { return "&#60;"; } else if (c == "\t") { var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx); screenColumn += tabSize - 1; return self.$tabStrings[tabSize]; } else if (c == "\u3000") { // U+3000 is both invisible AND full-width, so must be handled uniquely var classToUse = self.showInvisibles ? "ace_cjk ace_invisible" : "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_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.$renderLineCore = function(stringBuilder, lastRow, tokens, splits, onlyContents) { var chars = 0; var split = 0; var splitChars; var screenColumn = 0; var self = this; if (!splits || splits.length == 0) splitChars = Number.MAX_VALUE; else splitChars = splits[0]; if (!onlyContents) { stringBuilder.push("<div class='ace_line' style='height:", this.config.lineHeight, "px", "'>" ); } for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; var value = token.value; if (chars + value.length < splitChars) { screenColumn = self.$renderToken( stringBuilder, screenColumn, token, value ); chars += value.length; } else { while (chars + value.length >= splitChars) { screenColumn = self.$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", "'>" ); } split ++; screenColumn = 0; splitChars = splits[split] || Number.MAX_VALUE; } if (value.length != 0) { chars += value.length; screenColumn = self.$renderToken( stringBuilder, screenColumn, token, value ); } } } if (this.showInvisibles) { if (lastRow !== this.session.getLength() - 1) stringBuilder.push("<span class='ace_invisible'>" + this.EOL_CHAR + "</span>"); else stringBuilder.push("<span class='ace_invisible'>" + this.EOF_CHAR + "</span>"); } if (!onlyContents) stringBuilder.push("</div>"); }; this.$renderLine = function(stringBuilder, row, tokens, onlyContents) { // Check if the line to render is folded or not. If not, things are // simple, otherwise, we need to fake some things... if (!this.session.isRowFolded(row)) { var splits = this.session.getRowSplitData(row); this.$renderLineCore(stringBuilder, row, tokens, splits, onlyContents); } else { this.$renderFoldLine(stringBuilder, row, tokens, onlyContents); } }; this.$renderFoldLine = function(stringBuilder, row, tokens, onlyContents) { var session = this.session, foldLine = session.getFoldLine(row), 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); // Check if the token value is longer then the from...to spacing. 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) { var value = tokens[idx].value; if (value.length + col > to) { value = value.substring(0, to - col); } renderTokens.push({ type: tokens[idx].type, value: value }); col += value.length; idx += 1; } } foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) { if (placeholder) { renderTokens.push({ type: "fold", value: placeholder }); } else { if (isNewRow) tokens = this.session.getTokens(row); if (tokens.length) addTokens(tokens, lastColumn, column); } }.bind(this), foldLine.end.row, this.session.getLine(foldLine.end.row).length); // TODO: Build a fake splits array! var splits = this.session.$useWrapMode?this.session.$wrapData[row]:null; this.$renderLineCore(stringBuilder, row, renderTokens, splits, onlyContents); }; this.$useLineGroups = function() { // For the updateLines function to work correctly, it's important that the // child nodes of this.element correspond on a 1-to-1 basis to rows in the // document (as distinct from lines on the screen). For sessions that are // wrapped, this means we need to add a layer to the node hierarchy (tagged // with the class name ace_line_group). 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); exports.Text = Text; }); define('ace/layer/cursor', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) { var dom = require("../lib/dom"); var Cursor = function(parentEl) { this.element = dom.createElement("div"); this.element.className = "ace_layer ace_cursor-layer"; parentEl.appendChild(this.element); this.isVisible = false; this.cursors = []; this.cursor = this.addCursor(); }; (function() { this.$padding = 0; this.setPadding = function(padding) { this.$padding = padding; }; this.setSession = function(session) { this.session = session; }; this.addCursor = function() { var el = dom.createElement("div"); var className = "ace_cursor"; if (!this.isVisible) className += " ace_hidden"; if (this.overwrite) className += " ace_overwrite"; el.className = className; this.element.appendChild(el); this.cursors.push(el); return el; }; this.removeCursor = function() { if (this.cursors.length > 1) { var el = this.cursors.pop(); el.parentNode.removeChild(el); return el; } }; this.hideCursor = function() { this.isVisible = false; for (var i = this.cursors.length; i--; ) dom.addCssClass(this.cursors[i], "ace_hidden"); clearInterval(this.blinkId); }; this.showCursor = function() { this.isVisible = true; for (var i = this.cursors.length; i--; ) dom.removeCssClass(this.cursors[i], "ace_hidden"); this.element.style.visibility = ""; this.restartTimer(); }; this.restartTimer = function() { clearInterval(this.blinkId); if (!this.isVisible) return; var element = this.cursors.length == 1 ? this.cursor : this.element; this.blinkId = setInterval(function() { element.style.visibility = "hidden"; setTimeout(function() { element.style.visibility = ""; }, 400); }, 1000); }; this.getPixelPosition = function(position, onScreen) { if (!this.config || !this.session) { return { left : 0, top : 0 }; } if (!position) position = this.session.selection.getCursor(); var pos = this.session.documentToScreenPosition(position); var cursorLeft = Math.round(this.$padding + pos.column * this.config.characterWidth); var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) * this.config.lineHeight; return { left : cursorLeft, top : cursorTop }; }; this.update = function(config) { this.config = config; if (this.session.selectionMarkerCount > 0) { var selections = this.session.$selectionMarkers; var i = 0, sel, cursorIndex = 0; for (var i = selections.length; i--; ) { sel = selections[i]; var pixelPos = this.getPixelPosition(sel.cursor, true); var style = (this.cursors[cursorIndex++] || this.addCursor()).style; style.left = pixelPos.left + "px"; style.top = pixelPos.top + "px"; style.width = config.characterWidth + "px"; style.height = config.lineHeight + "px"; } if (cursorIndex > 1) while (this.cursors.length > cursorIndex) this.removeCursor(); } else { var pixelPos = this.getPixelPosition(null, true); var style = this.cursor.style; style.left = pixelPos.left + "px"; style.top = pixelPos.top + "px"; style.width = config.characterWidth + "px"; style.height = config.lineHeight + "px"; while (this.cursors.length > 1) this.removeCursor(); } var overwrite = this.session.getOverwrite(); if (overwrite != this.overwrite) this.$setOverite(overwrite); // cache for textarea and gutter highlight this.$pixelPos = pixelPos; this.restartTimer(); }; this.$setOverite = function(overwrite) { this.overwrite = overwrite; for (var i = this.cursors.length; i--; ) { if (overwrite) dom.addCssClass(this.cursors[i], "ace_overwrite"); else dom.removeCssClass(this.cursors[i], "ace_overwrite"); } }; this.destroy = function() { clearInterval(this.blinkId); } }).call(Cursor.prototype); exports.Cursor = Cursor; }); define('ace/scrollbar', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/dom', 'ace/lib/event', 'ace/lib/event_emitter'], function(require, exports, module) { var oop = require("./lib/oop"); var dom = require("./lib/dom"); var event = require("./lib/event"); var EventEmitter = require("./lib/event_emitter").EventEmitter; /** * new ScrollBar(parent) * - parent (DOMElement): A DOM element * * Creates a new `ScrollBar`. `parent` is the owner of the scroll bar. * **/ var ScrollBar = function(parent) { this.element = dom.createElement("div"); this.element.className = "ace_sb"; this.inner = dom.createElement("div"); this.element.appendChild(this.inner); parent.appendChild(this.element); // in OSX lion the scrollbars appear to have no width. In this case resize // the to show the scrollbar but still pretend that the scrollbar has a width // of 0px // in Firefox 6+ scrollbar is hidden if element has the same width as scrollbar // make element a little bit wider to retain scrollbar when page is zoomed this.width = dom.scrollbarWidth(parent.ownerDocument); this.element.style.width = (this.width || 15) + 5 + "px"; event.addListener(this.element, "scroll", this.onScroll.bind(this)); }; (function() { oop.implement(this, EventEmitter); this.onScroll = function() { this._emit("scroll", {data: this.element.scrollTop}); }; this.getWidth = function() { return this.width; }; this.setHeight = function(height) { this.element.style.height = height + "px"; }; this.setInnerHeight = function(height) { this.inner.style.height = height + "px"; }; // TODO: on chrome 17+ after for small zoom levels after this function // this.element.scrollTop != scrollTop which makes page to scroll up. this.setScrollTop = function(scrollTop) { this.element.scrollTop = scrollTop; }; }).call(ScrollBar.prototype); exports.ScrollBar = ScrollBar; }); define('ace/renderloop', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("./lib/event"); /** internal, hide * new RenderLoop(onRender, win) * * * **/ var RenderLoop = function(onRender, win) { this.onRender = onRender; this.pending = false; this.changes = 0; this.window = win || window; }; (function() { /** internal, hide * RenderLoop.schedule(change) * - change (Array): * * **/ this.schedule = function(change) { //this.onRender(change); //return; this.changes = this.changes | change; if (!this.pending) { this.pending = true; var _self = this; event.nextTick(function() { _self.pending = false; var changes; while (changes = _self.changes) { _self.changes = 0; _self.onRender(changes); } }, this.window); } }; }).call(RenderLoop.prototype); exports.RenderLoop = RenderLoop; }); define("text!ace/css/editor.css", [], ".ace_editor {\n" + " position: absolute;\n" + " overflow: hidden;\n" + " font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Droid Sans Mono', 'Consolas', monospace;\n" + " font-size: 12px;\n" + "}\n" + "\n" + ".ace_scroller {\n" + " position: absolute;\n" + " overflow: hidden;\n" + "}\n" + "\n" + ".ace_content {\n" + " position: absolute;\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + " cursor: text;\n" + "}\n" + "\n" + ".ace_gutter {\n" + " position: absolute;\n" + " overflow : hidden;\n" + " height: 100%;\n" + " width: auto;\n" + " cursor: default;\n" + " z-index: 4;\n" + "}\n" + "\n" + ".ace_scroller.horscroll {\n" + " box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\n" + "}\n" + "\n" + ".ace_gutter-cell {\n" + " padding-left: 19px;\n" + " padding-right: 6px;\n" + "}\n" + "\n" + ".ace_gutter-cell.ace_error {\n" + " background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUM2OEZDQTQ4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUM2OEZDQTU4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQzY4RkNBMjhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQzY4RkNBMzhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PkgXxbAAAAJbSURBVHjapFNNaBNBFH4zs5vdZLP5sQmNpT82QY209heh1ioWisaDRcSKF0WKJ0GQnrzrxasHsR6EnlrwD0TagxJabaVEpFYxLWlLSS822tr87m66ccfd2GKyVhA6MMybgfe97/vmPUQphd0sZjto9XIn9OOsvlu2nkqRzVU+6vvlzPf8W6bk8dxQ0NPbxAALgCgg2JkaQuhzQau/El0zbmUA7U0Es8v2CiYmKQJHGO1QICCLoqilMhkmurDAyapKgqItezi/USRdJqEYY4D5jCy03ht2yMkkvL91jTTX10qzyyu2hruPRN7jgbH+EOsXcMLgYiThEgAMhABW85oqy1DXdRIdvP1AHJ2acQXvDIrVHcdQNrEKNYSVMSZGMjEzIIAwDXIo+6G/FxcGnzkC3T2oMhLjre49sBB+RRcHLqdafK6sYdE/GGBwU1VpFNj0aN8pJbe+BkZyevUrvLl6Xmm0W9IuTc0DxrDNAJd5oEvI/KRsNC3bQyNjPO9yQ1YHcfj2QvfQc/5TUhJTBc2iM0U7AWDQtc1nJHvD/cfO2s7jaGkiTEfa/Ep8coLu7zmNmh8+dc5lZDuUeFAGUNA/OY6JVaypQ0vjr7XYjUvJM37vt+j1vuTK5DgVfVUoTjVe+y3/LxMxY2GgU+CSLy4cpfsYorRXuXIOi0Vt40h67uZFTdIo6nLaZcwUJWAzwNS0tBnqqKzQDnjdG/iPyZxo46HaKUpbvYkj8qYRTZsBhge+JHhZyh0x9b95JqjVJkT084kZIPwu/mPWqPgfQ5jXh2+92Ay7HedfAgwA6KDWafb4w3cAAAAASUVORK5CYII=\");\n" + " background-repeat: no-repeat;\n" + " background-position: 2px center;\n" + "}\n" + "\n" + ".ace_gutter-cell.ace_warning {\n" + " background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUM2OEZDQTg4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUM2OEZDQTk4RTU0MTFFMUEzM0VFRTM2RUY1M0RBMjYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQzY4RkNBNjhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQzY4RkNBNzhFNTQxMUUxQTMzRUVFMzZFRjUzREEyNiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pgd7PfIAAAGmSURBVHjaYvr//z8DJZiJgUIANoCRkREb9gLiSVAaQx4OQM7AAkwd7XU2/v++/rOttdYGEB9dASEvOMydGKfH8Gv/p4XTkvRBfLxeQAP+1cUhXopyvzhP7P/IoSj7g7Mw09cNKO6J1QQ0L4gICPIv/veg/8W+JdFvQNLHVsW9/nmn9zk7B+cCkDwhL7gt6knSZnx9/LuCEOcvkIAMP+cvto9nfqyZmmUAksfnBUtbM60gX/3/kgyv3/xSFOL5DZT+L8vP+Yfh5cvfPvp/xUHyQHXGyAYwgpwBjZYFT3Y1OEl/OfCH4ffv3wzc4iwMvNIsDJ+f/mH4+vIPAxsb631WW0Yln6ZpQLXdMK/DXGDflh+sIv37EivD5x//Gb7+YWT4y86sl7BCCkSD+Z++/1dkvsFRl+HnD1Rvje4F8whjMXmGj58YGf5zsDMwcnAwfPvKcml62DsQDeaDxN+/Y0qwlpEHqrdB94IRNIDUgfgfKJChGK4OikEW3gTiXUB950ASLFAF54AC94A0G9QAfOnmF9DCDzABFqS08IHYDIScdijOjQABBgC+/9awBH96jwAAAABJRU5ErkJggg==\");\n" + " background-repeat: no-repeat;\n" + " background-position: 2px center;\n" + "}\n" + "\n" + ".ace_gutter-cell.ace_info {\n" + " background-image: url(\"data:image/gif;base64,R0lGODlhEAAQAMQAAAAAAEFBQVJSUl5eXmRkZGtra39/f4WFhYmJiZGRkaampry8vMPDw8zMzNXV1dzc3OTk5Orq6vDw8P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABQALAAAAAAQABAAAAUuICWOZGmeaBml5XGwFCQSBGyXRSAwtqQIiRuiwIM5BoYVbEFIyGCQoeJGrVptIQA7\");\n" + " background-repeat: no-repeat;\n" + " background-position: 2px center;\n" + "}\n" + "\n" + ".ace_editor .ace_sb {\n" + " position: absolute;\n" + " overflow-x: hidden;\n" + " overflow-y: scroll;\n" + " right: 0;\n" + "}\n" + "\n" + ".ace_editor .ace_sb div {\n" + " position: absolute;\n" + " width: 1px;\n" + " left: 0;\n" + "}\n" + "\n" + ".ace_editor .ace_print_margin_layer {\n" + " z-index: 0;\n" + " position: absolute;\n" + " overflow: hidden;\n" + " margin: 0;\n" + " left: 0;\n" + " height: 100%;\n" + " width: 100%;\n" + "}\n" + "\n" + ".ace_editor .ace_print_margin {\n" + " position: absolute;\n" + " height: 100%;\n" + "}\n" + "\n" + ".ace_editor > textarea {\n" + " position: absolute;\n" + " z-index: 0;\n" + " width: 0.5em;\n" + " height: 1em;\n" + " opacity: 0;\n" + " background: transparent;\n" + " appearance: none;\n" + " -moz-appearance: none;\n" + " border: none;\n" + " resize: none;\n" + " outline: none;\n" + " overflow: hidden;\n" + "}\n" + "\n" + ".ace_editor > textarea.ace_composition {\n" + " background: #fff;\n" + " color: #000;\n" + " z-index: 1000;\n" + " opacity: 1;\n" + " border: solid lightgray 1px;\n" + " margin: -1px\n" + "}\n" + "\n" + ".ace_layer {\n" + " z-index: 1;\n" + " position: absolute;\n" + " overflow: hidden;\n" + " white-space: nowrap;\n" + " height: 100%;\n" + " width: 100%;\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + " /* setting pointer-events: auto; on node under the mouse, which changes\n" + " during scroll, will break mouse wheel scrolling in Safari */\n" + " pointer-events: none;\n" + "}\n" + "\n" + ".ace_gutter .ace_layer {\n" + " position: relative;\n" + " min-width: 40px;\n" + " width: auto;\n" + " text-align: right;\n" + " pointer-events: auto;\n" + "}\n" + "\n" + ".ace_text-layer {\n" + " color: black;\n" + " font: inherit !important;\n" + "}\n" + "\n" + ".ace_cjk {\n" + " display: inline-block;\n" + " text-align: center;\n" + "}\n" + "\n" + ".ace_cursor-layer {\n" + " z-index: 4;\n" + "}\n" + "\n" + ".ace_cursor {\n" + " z-index: 4;\n" + " position: absolute;\n" + "}\n" + "\n" + ".ace_cursor.ace_hidden {\n" + " opacity: 0.2;\n" + "}\n" + "\n" + ".ace_editor.multiselect .ace_cursor {\n" + " border-left-width: 1px;\n" + "}\n" + "\n" + ".ace_line {\n" + " white-space: nowrap;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_step {\n" + " position: absolute;\n" + " z-index: 3;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_selection {\n" + " position: absolute;\n" + " z-index: 5;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_bracket {\n" + " position: absolute;\n" + " z-index: 6;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_active_line {\n" + " position: absolute;\n" + " z-index: 2;\n" + "}\n" + "\n" + ".ace_marker-layer .ace_selected_word {\n" + " position: absolute;\n" + " z-index: 4;\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + "}\n" + "\n" + ".ace_line .ace_fold {\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + "\n" + " display: inline-block;\n" + " height: 11px;\n" + " margin-top: -2px;\n" + " vertical-align: middle;\n" + "\n" + " background-image:\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%3AIDAT8%11c%FC%FF%FF%7F%18%03%1A%60%01%F2%3F%A0%891%80%04%FF%11-%F8%17%9BJ%E2%05%B1ZD%81v%26t%E7%80%F8%A3%82h%A12%1A%20%A3%01%02%0F%01%BA%25%06%00%19%C0%0D%AEF%D5%3ES%00%00%00%00IEND%AEB%60%82\");\n" + " background-repeat: no-repeat, repeat-x;\n" + " background-position: center center, top left;\n" + " color: transparent;\n" + "\n" + " border: 1px solid black;\n" + " -moz-border-radius: 2px;\n" + " -webkit-border-radius: 2px;\n" + " border-radius: 2px;\n" + "\n" + " cursor: pointer;\n" + " pointer-events: auto;\n" + "}\n" + "\n" + ".ace_dark .ace_fold {\n" + "}\n" + "\n" + ".ace_fold:hover{\n" + " background-image:\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%11%00%00%00%09%08%06%00%00%00%D4%E8%C7%0C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%B5IDAT(%15%A5%91%3D%0E%02!%10%85ac%E1%05%D6%CE%D6%C6%CE%D2%E8%ED%CD%DE%C0%C6%D6N.%E0V%F8%3D%9Ca%891XH%C2%BE%D9y%3F%90!%E6%9C%C3%BFk%E5%011%C6-%F5%C8N%04%DF%BD%FF%89%DFt%83DN%60%3E%F3%AB%A0%DE%1A%5Dg%BE%10Q%97%1B%40%9C%A8o%10%8F%5E%828%B4%1B%60%87%F6%02%26%85%1Ch%1E%C1%2B%5Bk%FF%86%EE%B7j%09%9A%DA%9B%ACe%A3%F9%EC%DA!9%B4%D5%A6%81%86%86%98%CC%3C%5B%40%FA%81%B3%E9%CB%23%94%C16Azo%05%D4%E1%C1%95a%3B%8A'%A0%E8%CC%17%22%85%1D%BA%00%A2%FA%DC%0A%94%D1%D1%8D%8B%3A%84%17B%C7%60%1A%25Z%FC%8D%00%00%00%00IEND%AEB%60%82\"),\n" + " url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%007%08%06%00%00%00%C4%DD%80C%00%00%03%1EiCCPICC%20Profile%00%00x%01%85T%DFk%D3P%14%FE%DAe%9D%B0%E1%8B%3Ag%11%09%3Eh%91ndStC%9C%B6kW%BA%CDZ%EA6%B7!H%9B%A6m%5C%9A%C6%24%ED~%B0%07%D9%8Bo%3A%C5w%F1%07%3E%F9%07%0C%D9%83o%7B%92%0D%C6%14a%F8%AC%88%22L%F6%22%B3%9E%9B4M'S%03%B9%F7%BB%DF%F9%EE9'%E7%E4%5E%A0%F9qZ%D3%14%2F%0F%14USO%C5%C2%FC%C4%E4%14%DF%F2%01%5E%1CC%2B%FChM%8B%86%16J%26G%40%0F%D3%B2y%EF%B3%F3%0E%1E%C6lt%EEo%DF%AB%FEc%D5%9A%95%0C%11%F0%1C%20%BE%945%C4%22%E1Y%A0i%5C%D4t%13%E0%D6%89%EF%9D15%C2%CDLsX%A7%04%09%1Fg8oc%81%E1%8C%8D%23%96f45%40%9A%09%C2%07%C5B%3AK%B8%408%98i%E0%F3%0D%D8%CE%81%14%E4'%26%A9%92.%8B%3C%ABER%2F%E5dE%B2%0C%F6%F0%1Fs%83%F2_%B0%A8%94%E9%9B%AD%E7%10%8Dm%9A%19N%D1%7C%8A%DE%1F9%7Dp%8C%E6%00%D5%C1%3F_%18%BDA%B8%9DpX6%E3%A35~B%CD%24%AE%11%26%BD%E7%EEti%98%EDe%9A%97Y)%12%25%1C%24%BCbT%AE3li%E6%0B%03%89%9A%E6%D3%ED%F4P%92%B0%9F4%BF43Y%F3%E3%EDP%95%04%EB1%C5%F5%F6KF%F4%BA%BD%D7%DB%91%93%07%E35%3E%A7)%D6%7F%40%FE%BD%F7%F5r%8A%E5y%92%F0%EB%B4%1E%8D%D5%F4%5B%92%3AV%DB%DB%E4%CD%A6%23%C3%C4wQ%3F%03HB%82%8E%1Cd(%E0%91B%0Ca%9Ac%C4%AA%F8L%16%19%22J%A4%D2itTy%B28%D6%3B(%93%96%ED%1CGx%C9_%0E%B8%5E%16%F5%5B%B2%B8%F6%E0%FB%9E%DD%25%D7%8E%BC%15%85%C5%B7%A3%D8Q%ED%B5%81%E9%BA%B2%13%9A%1B%7Fua%A5%A3n%E17%B9%E5%9B%1Bm%AB%0B%08Q%FE%8A%E5%B1H%5Ee%CAO%82Q%D7u6%E6%90S%97%FCu%0B%CF2%94%EE%25v%12X%0C%BA%AC%F0%5E%F8*l%0AO%85%17%C2%97%BF%D4%C8%CE%DE%AD%11%CB%80q%2C%3E%AB%9ES%CD%C6%EC%25%D2L%D2%EBd%B8%BF%8A%F5B%C6%18%F9%901CZ%9D%BE%24M%9C%8A9%F2%DAP%0B'%06w%82%EB%E6%E2%5C%2F%D7%07%9E%BB%CC%5D%E1%FA%B9%08%AD.r%23%8E%C2%17%F5E%7C!%F0%BE3%BE%3E_%B7o%88a%A7%DB%BE%D3d%EB%A31Z%EB%BB%D3%91%BA%A2%B1z%94%8F%DB'%F6%3D%8E%AA%13%19%B2%B1%BE%B1~V%08%2B%B4%A2cjJ%B3tO%00%03%25mN%97%F3%05%93%EF%11%84%0B%7C%88%AE-%89%8F%ABbW%90O%2B%0Ao%99%0C%5E%97%0CI%AFH%D9.%B0%3B%8F%ED%03%B6S%D6%5D%E6i_s9%F3*p%E9%1B%FD%C3%EB.7U%06%5E%19%C0%D1s.%17%A03u%E4%09%B0%7C%5E%2C%EB%15%DB%1F%3C%9E%B7%80%91%3B%DBc%AD%3Dma%BA%8B%3EV%AB%DBt.%5B%1E%01%BB%0F%AB%D5%9F%CF%AA%D5%DD%E7%E4%7F%0Bx%A3%FC%06%A9%23%0A%D6%C2%A1_2%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%003IDAT8%11c%FC%FF%FF%7F%3E%03%1A%60%01%F2%3F%A3%891%80%04%FFQ%26%F8w%C0%B43%A1%DB%0C%E2%8F%0A%A2%85%CAh%80%8C%06%08%3C%04%E8%96%18%00%A3S%0D%CD%CF%D8%C1%9D%00%00%00%00IEND%AEB%60%82\");\n" + " background-repeat: no-repeat, repeat-x;\n" + " background-position: center center, top left;\n" + "}\n" + "\n" + ".ace_dragging .ace_content {\n" + " cursor: move;\n" + "}\n" + "\n" + ".ace_folding-enabled > .ace_gutter-cell {\n" + " padding-right: 13px;\n" + "}\n" + "\n" + ".ace_fold-widget {\n" + " box-sizing: border-box;\n" + " -moz-box-sizing: border-box;\n" + " -webkit-box-sizing: border-box;\n" + "\n" + " margin: 0 -12px 1px 1px;\n" + " display: inline-block;\n" + " height: 14px;\n" + " width: 11px;\n" + " vertical-align: text-bottom;\n" + "\n" + " background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAe%8A%B1%0D%000%0C%C2%F2%2CK%96%BC%D0%8F9%81%88H%E9%D0%0E%96%C0%10%92%3E%02%80%5E%82%E4%A9*-%EEsw%C8%CC%11%EE%96w%D8%DC%E9*Eh%0C%151(%00%00%00%00IEND%AEB%60%82\");\n" + " background-repeat: no-repeat;\n" + " background-position: center 5px;\n" + "\n" + " border-radius: 3px;\n" + "}\n" + "\n" + ".ace_fold-widget.end {\n" + " background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%05%00%00%00%05%08%06%00%00%00%8Do%26%E5%00%00%004IDATx%DAm%C7%C1%09%000%08C%D1%8C%ECE%C8E(%8E%EC%02)%1EZJ%F1%C1'%04%07I%E1%E5%EE%CAL%F5%A2%99%99%22%E2%D6%1FU%B5%FE0%D9x%A7%26Wz5%0E%D5%00%00%00%00IEND%AEB%60%82\");\n" + "}\n" + "\n" + ".ace_fold-widget.closed {\n" + " background-image: url(\"data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%03%00%00%00%06%08%06%00%00%00%06%E5%24%0C%00%00%009IDATx%DA5%CA%C1%09%000%08%03%C0%AC*(%3E%04%C1%0D%BA%B1%23%A4Uh%E0%20%81%C0%CC%F8%82%81%AA%A2%AArGfr%88%08%11%11%1C%DD%7D%E0%EE%5B%F6%F6%CB%B8%05Q%2F%E9tai%D9%00%00%00%00IEND%AEB%60%82\");\n" + "}\n" + "\n" + ".ace_fold-widget:hover {\n" + " border: 1px solid rgba(0, 0, 0, 0.3);\n" + " background-color: rgba(255, 255, 255, 0.2);\n" + " -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " box-shadow:inset 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\n" + " background-position: center 4px;\n" + "}\n" + "\n" + ".ace_fold-widget:active {\n" + " border: 1px solid rgba(0, 0, 0, 0.4);\n" + " background-color: rgba(0, 0, 0, 0.05);\n" + " -moz-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n" + " -moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n" + " -webkit-box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n" + " -webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n" + " box-shadow:inset 0 1px 1px rgba(255, 255, 255);\n" + " box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\n" + "}\n" + "\n" + ".ace_fold-widget.invalid {\n" + " background-color: #FFB4B4;\n" + " border-color: #DE5555;\n" + "}\n" + "\n" + ".ace_fade-fold-widgets .ace_fold-widget {\n" + " -moz-transition: opacity 0.4s ease 0.05s;\n" + " -webkit-transition: opacity 0.4s ease 0.05s;\n" + " -o-transition: opacity 0.4s ease 0.05s;\n" + " -ms-transition: opacity 0.4s ease 0.05s;\n" + " transition: opacity 0.4s ease 0.05s;\n" + " opacity: 0;\n" + "}\n" + "\n" + ".ace_fade-fold-widgets:hover .ace_fold-widget {\n" + " -moz-transition: opacity 0.05s ease 0.05s;\n" + " -webkit-transition: opacity 0.05s ease 0.05s;\n" + " -o-transition: opacity 0.05s ease 0.05s;\n" + " -ms-transition: opacity 0.05s ease 0.05s;\n" + " transition: opacity 0.05s ease 0.05s;\n" + " opacity:1;\n" + "}\n" + ""); define('ace/multi_select', ['require', 'exports', 'module' , 'ace/range_list', 'ace/range', 'ace/selection', 'ace/mouse/multi_select_handler', 'ace/lib/event', 'ace/commands/multi_select_commands', 'ace/search', 'ace/edit_session', 'ace/editor'], function(require, exports, module) { var RangeList = require("./range_list").RangeList; var Range = require("./range").Range; var Selection = require("./selection").Selection; var onMouseDown = require("./mouse/multi_select_handler").onMouseDown; var event = require("./lib/event"); var commands = require("./commands/multi_select_commands"); exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands); // Todo: session.find or editor.findVolatile that returns range var Search = require("./search").Search; var search = new Search(); function find(session, needle, dir) { search.$options.wrap = true; search.$options.needle = needle; search.$options.backwards = dir == -1; return search.find(session); } // extend EditSession var EditSession = require("./edit_session").EditSession; (function() { this.getSelectionMarkers = function() { return this.$selectionMarkers; }; }).call(EditSession.prototype); // extend Selection (function() { // list of ranges in reverse addition order this.ranges = null; // automatically sorted list of ranges this.rangeList = null; this.addRange = function(range, $blockChangeEvents) { if (!range) return; if (!this.inMultiSelectMode && this.rangeCount == 0) { var oldRange = this.toOrientedRange(); if (range.intersects(oldRange)) return $blockChangeEvents || this.fromOrientedRange(range); this.rangeList.add(oldRange); this.$onAddRange(oldRange); } if (!range.cursor) range.cursor = range.end; var removed = this.rangeList.add(range); this.$onAddRange(range); if (removed.length) this.$onRemoveRange(removed); if (this.rangeCount > 1 && !this.inMultiSelectMode) { this._emit("multiSelect"); this.inMultiSelectMode = true; this.session.$undoSelect = false; this.rangeList.attach(this.session); } return $blockChangeEvents || this.fromOrientedRange(range); }; this.toSingleRange = function(range) { range = range || this.ranges[0]; var removed = this.rangeList.removeAll(); if (removed.length) this.$onRemoveRange(removed); range && this.fromOrientedRange(range); }; this.substractPoint = function(pos) { var removed = this.rangeList.substractPoint(pos); if (removed) { this.$onRemoveRange(removed); return removed[0]; } }; this.mergeOverlappingRanges = function() { var removed = this.rangeList.merge(); if (removed.length) this.$onRemoveRange(removed); else if(this.ranges[0]) this.fromOrientedRange(this.ranges[0]); }; this.$onAddRange = function(range) { this.rangeCount = this.rangeList.ranges.length; this.ranges.unshift(range); this._emit("addRange", {range: range}); }; this.$onRemoveRange = function(removed) { this.rangeCount = this.rangeList.ranges.length; if (this.rangeCount == 1 && this.inMultiSelectMode) { var lastRange = this.rangeList.ranges.pop(); removed.push(lastRange); this.rangeCount = 0; } for (var i = removed.length; i--; ) { var index = this.ranges.indexOf(removed[i]); this.ranges.splice(index, 1); } this._emit("removeRange", {ranges: removed}); if (this.rangeCount == 0 && this.inMultiSelectMode) { this.inMultiSelectMode = false; this._emit("singleSelect"); this.session.$undoSelect = true; this.rangeList.detach(this.session); } lastRange = lastRange || this.ranges[0]; if (lastRange && !lastRange.isEqual(this.getRange())) this.fromOrientedRange(lastRange); }; // adds multicursor support to selection this.$initRangeList = function() { if (this.rangeList) return; this.rangeList = new RangeList(); this.ranges = []; this.rangeCount = 0; }; this.getAllRanges = function() { return this.rangeList.ranges.concat(); }; this.splitIntoLines = function () { if (this.rangeCount > 1) { var ranges = this.rangeList.ranges; var lastRange = ranges[ranges.length - 1]; var range = Range.fromPoints(ranges[0].start, lastRange.end); this.toSingleRange(); this.setSelectionRange(range, lastRange.cursor == lastRange.start); } else { var range = this.getRange(); var startRow = range.start.row; var endRow = range.end.row; if (startRow == endRow) return; var rectSel = []; var r = this.getLineRange(startRow, true); r.start.column = range.start.column; rectSel.push(r); for (var i = startRow + 1; i < endRow; i++) rectSel.push(this.getLineRange(i, true)); r = this.getLineRange(endRow, true); r.end.column = range.end.column; rectSel.push(r); rectSel.forEach(this.addRange, this); } }; this.toggleBlockSelection = function () { if (this.rangeCount > 1) { var ranges = this.rangeList.ranges; var lastRange = ranges[ranges.length - 1]; var range = Range.fromPoints(ranges[0].start, lastRange.end); this.toSingleRange(); this.setSelectionRange(range, lastRange.cursor == lastRange.start); } else { var cursor = this.session.documentToScreenPosition(this.selectionLead); var anchor = this.session.documentToScreenPosition(this.selectionAnchor); var rectSel = this.rectangularRangeBlock(cursor, anchor); rectSel.forEach(this.addRange, this); } }; this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) { var rectSel = []; var xBackwards = screenCursor.column < screenAnchor.column; if (xBackwards) { var startColumn = screenCursor.column; var endColumn = screenAnchor.column; } else { var startColumn = screenAnchor.column; var endColumn = screenCursor.column; } var yBackwards = screenCursor.row < screenAnchor.row; if (yBackwards) { var startRow = screenCursor.row; var endRow = screenAnchor.row; } else { var startRow = screenAnchor.row; var endRow = screenCursor.row; } if (startColumn < 0) startColumn = 0; if (startRow < 0) startRow = 0; if (startRow == endRow) includeEmptyLines = true; for (var row = startRow; row <= endRow; row++) { var range = Range.fromPoints( this.session.screenToDocumentPosition(row, startColumn), this.session.screenToDocumentPosition(row, endColumn) ); if (range.isEmpty()) { if (docEnd && isSamePoint(range.end, docEnd)) break; var docEnd = range.end; } range.cursor = xBackwards ? range.start : range.end; rectSel.push(range); } if (yBackwards) rectSel.reverse(); if (!includeEmptyLines) { var end = rectSel.length - 1; while (rectSel[end].isEmpty() && end > 0) end--; if (end > 0) { var start = 0; while (rectSel[start].isEmpty()) start++; } for (var i = end; i >= start; i--) { if (rectSel[i].isEmpty()) rectSel.splice(i, 1); } } return rectSel; }; }).call(Selection.prototype); // extend Editor var Editor = require("./editor").Editor; (function() { /** extension * Editor.updateSelectionMarkers() * * Updates the cursor and marker layers. **/ this.updateSelectionMarkers = function() { this.renderer.updateCursor(); this.renderer.updateBackMarkers(); }; this.addSelectionMarker = function(orientedRange) { if (!orientedRange.cursor) orientedRange.cursor = orientedRange.end; var style = this.getSelectionStyle(); orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style); this.session.$selectionMarkers.push(orientedRange); this.session.selectionMarkerCount = this.session.$selectionMarkers.length; return orientedRange; }; this.removeSelectionMarker = function(range) { if (!range.marker) return; this.session.removeMarker(range.marker); var index = this.session.$selectionMarkers.indexOf(range); if (index != -1) this.session.$selectionMarkers.splice(index, 1); this.session.selectionMarkerCount = this.session.$selectionMarkers.length; }; this.removeSelectionMarkers = function(ranges) { var markerList = this.session.$selectionMarkers; for (var i = ranges.length; i--; ) { var range = ranges[i]; if (!range.marker) continue; this.session.removeMarker(range.marker); var index = markerList.indexOf(range); if (index != -1) markerList.splice(index, 1); } this.session.selectionMarkerCount = markerList.length; }; this.$onAddRange = function(e) { this.addSelectionMarker(e.range); this.renderer.updateCursor(); this.renderer.updateBackMarkers(); }; this.$onRemoveRange = function(e) { this.removeSelectionMarkers(e.ranges); this.renderer.updateCursor(); this.renderer.updateBackMarkers(); }; this.$onMultiSelect = function(e) { if (this.inMultiSelectMode) return; this.inMultiSelectMode = true; this.setStyle("multiselect"); this.keyBinding.addKeyboardHandler(commands.keyboardHandler); this.commands.on("exec", this.$onMultiSelectExec); this.renderer.updateCursor(); this.renderer.updateBackMarkers(); }; this.$onSingleSelect = function(e) { if (this.session.multiSelect.inVirtualMode) return; this.inMultiSelectMode = false; this.unsetStyle("multiselect"); this.keyBinding.removeKeyboardHandler(commands.keyboardHandler); this.commands.removeEventListener("exec", this.$onMultiSelectExec); this.renderer.updateCursor(); this.renderer.updateBackMarkers(); }; this.$onMultiSelectExec = function(e) { var command = e.command; var editor = e.editor; if (!editor.multiSelect) return; if (!command.multiSelectAction) { command.exec(editor, e.args || {}); editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); editor.multiSelect.mergeOverlappingRanges(); } else if (command.multiSelectAction == "forEach") { editor.forEachSelection(command, e.args); } else if (command.multiSelectAction == "single") { editor.exitMultiSelectMode(); command.exec(editor, e.args || {}); } else { command.multiSelectAction(editor, e.args || {}); } e.preventDefault(); }; this.forEachSelection = function(cmd, args) { if (this.inVirtualSelectionMode) return; var session = this.session; var selection = this.selection; var rangeList = selection.rangeList; var reg = selection._eventRegistry; selection._eventRegistry = {}; var tmpSel = new Selection(session); this.inVirtualSelectionMode = true; for (var i = rangeList.ranges.length; i--;) { tmpSel.fromOrientedRange(rangeList.ranges[i]); this.selection = session.selection = tmpSel; cmd.exec(this, args || {}); tmpSel.toOrientedRange(rangeList.ranges[i]); } tmpSel.detach(); this.selection = session.selection = selection; this.inVirtualSelectionMode = false; selection._eventRegistry = reg; selection.mergeOverlappingRanges(); this.onCursorChange(); this.onSelectionChange(); }; this.exitMultiSelectMode = function() { if (this.inVirtualSelectionMode) return; this.multiSelect.toSingleRange(); }; this.getCopyText = function() { var text = ""; if (this.inMultiSelectMode) { var ranges = this.multiSelect.rangeList.ranges; text = []; for (var i = 0; i < ranges.length; i++) { text.push(this.session.getTextRange(ranges[i])); } text = text.join(this.session.getDocument().getNewLineCharacter()); } else if (!this.selection.isEmpty()) { text = this.session.getTextRange(this.getSelectionRange()); } return text; }; this.onPaste = function(text) { this._emit("paste", text); if (!this.inMultiSelectMode) return this.insert(text); var lines = text.split(/\r\n|\r|\n/); var ranges = this.selection.rangeList.ranges; if (lines.length > ranges.length || (lines.length <= 2 || !lines[1])) return this.commands.exec("insertstring", this, text); for (var i = ranges.length; i--; ) { var range = ranges[i]; if (!range.isEmpty()) this.session.remove(range); this.session.insert(range.start, lines[i]); } }; this.findAll = function(needle, options, additive) { options = options || {}; options.needle = needle || options.needle; this.$search.set(options); var ranges = this.$search.findAll(this.session); if (!ranges.length) return 0; this.$blockScrolling += 1; var selection = this.multiSelect; if (!additive) selection.toSingleRange(ranges[0]); for (var i = ranges.length; i--; ) selection.addRange(ranges[i], true); this.$blockScrolling -= 1; return ranges.length; }; // commands /** extension * Editor.selectMoreLines(dir, skip) * - dir (Number): The direction of lines to select: -1 for up, 1 for down * - skip (Boolean): If `true`, removes the active selection range * * Adds a cursor above or below the active cursor. **/ this.selectMoreLines = function(dir, skip) { var range = this.selection.toOrientedRange(); var isBackwards = range.cursor == range.end; var screenLead = this.session.documentToScreenPosition(range.cursor); if (this.selection.$desiredColumn) screenLead.column = this.selection.$desiredColumn; var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column); if (!range.isEmpty()) { var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start); var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column); } else { var anchor = lead; } if (isBackwards) { var newRange = Range.fromPoints(lead, anchor); newRange.cursor = newRange.start; } else { var newRange = Range.fromPoints(anchor, lead); newRange.cursor = newRange.end; } newRange.desiredColumn = screenLead.column; if (!this.selection.inMultiSelectMode) { this.selection.addRange(range); } else { if (skip) var toRemove = range.cursor; } this.selection.addRange(newRange); if (toRemove) this.selection.substractPoint(toRemove); }; this.transposeSelections = function(dir) { var session = this.session; var sel = session.multiSelect; var all = sel.ranges; for (var i = all.length; i--; ) { var range = all[i]; if (range.isEmpty()) { var tmp = session.getWordRange(range.start.row, range.start.column); range.start.row = tmp.start.row; range.start.column = tmp.start.column; range.end.row = tmp.end.row; range.end.column = tmp.end.column; } } sel.mergeOverlappingRanges(); var words = []; for (var i = all.length; i--; ) { var range = all[i]; words.unshift(session.getTextRange(range)); } if (dir < 0) words.unshift(words.pop()); else words.push(words.shift()); for (var i = all.length; i--; ) { var range = all[i]; var tmp = range.clone(); session.replace(range, words[i]); range.start.row = tmp.start.row; range.start.column = tmp.start.column; } } /** extension * Editor.selectMore(dir, skip) * - dir (Number): The direction of lines to select: -1 for up, 1 for down * - skip (Boolean): If `true`, removes the active selection range * * Finds the next occurence of text in an active selection and adds it to the selections. **/ this.selectMore = function (dir, skip) { var session = this.session; var sel = session.multiSelect; var range = sel.toOrientedRange(); if (range.isEmpty()) { var range = session.getWordRange(range.start.row, range.start.column); range.cursor = range.end; this.multiSelect.addRange(range); } var needle = session.getTextRange(range); var newRange = find(session, needle, dir); if (newRange) { newRange.cursor = dir == -1 ? newRange.start : newRange.end; this.multiSelect.addRange(newRange); } if (skip) this.multiSelect.substractPoint(range.cursor); }; }).call(Editor.prototype); function isSamePoint(p1, p2) { return p1.row == p2.row && p1.column == p2.column; } // patch // adds multicursor support to a session exports.onSessionChange = function(e) { var session = e.session; if (!session.multiSelect) { session.$selectionMarkers = []; session.selection.$initRangeList(); session.multiSelect = session.selection; } this.multiSelect = session.multiSelect; var oldSession = e.oldSession; if (oldSession) { // todo use events if (oldSession.multiSelect && oldSession.multiSelect.editor == this) oldSession.multiSelect.editor = null; session.multiSelect.removeEventListener("addRange", this.$onAddRange); session.multiSelect.removeEventListener("removeRange", this.$onRemoveRange); session.multiSelect.removeEventListener("multiSelect", this.$onMultiSelect); session.multiSelect.removeEventListener("singleSelect", this.$onSingleSelect); } session.multiSelect.on("addRange", this.$onAddRange); session.multiSelect.on("removeRange", this.$onRemoveRange); session.multiSelect.on("multiSelect", this.$onMultiSelect); session.multiSelect.on("singleSelect", this.$onSingleSelect); // this.$onSelectionChange = this.onSelectionChange.bind(this); if (this.inMultiSelectMode != session.selection.inMultiSelectMode) { if (session.selection.inMultiSelectMode) this.$onMultiSelect(); else this.$onSingleSelect(); } }; // MultiSelect(editor) // adds multiple selection support to the editor // (note: should be called only once for each editor instance) function MultiSelect(editor) { editor.$onAddRange = editor.$onAddRange.bind(editor); editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); exports.onSessionChange.call(editor, editor); editor.on("changeSession", exports.onSessionChange.bind(editor)); editor.on("mousedown", onMouseDown); editor.commands.addCommands(commands.defaultCommands); addAltCursorListeners(editor); } function addAltCursorListeners(editor){ var el = editor.textInput.getElement(); var altCursor = false; var contentEl = editor.renderer.content; event.addListener(el, "keydown", function(e) { if (e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey)) { if (!altCursor) { contentEl.style.cursor = "crosshair"; altCursor = true; } } else if (altCursor) { contentEl.style.cursor = ""; } }); event.addListener(el, "keyup", reset); event.addListener(el, "blur", reset); function reset() { if (altCursor) { contentEl.style.cursor = ""; altCursor = false; } } } exports.MultiSelect = MultiSelect; }); define('ace/range_list', ['require', 'exports', 'module' ], function(require, exports, module) { var RangeList = function() { this.ranges = []; }; (function() { this.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; this.pointIndex = function(pos, startIndex) { var list = this.ranges; for (var i = startIndex || 0; i < list.length; i++) { var range = list[i]; var cmp = this.comparePoints(pos, range.end); if (cmp > 0) continue; if (cmp == 0) return i; cmp = this.comparePoints(pos, range.start); if (cmp >= 0) return i; return -i-1; } return -i - 1; }; this.add = function(range) { var startIndex = this.pointIndex(range.start); if (startIndex < 0) startIndex = -startIndex - 1; var endIndex = this.pointIndex(range.end, startIndex); if (endIndex < 0) endIndex = -endIndex - 1; else endIndex++; return this.ranges.splice(startIndex, endIndex - startIndex, range); }; this.addList = function(list) { var removed = []; for (var i = list.length; i--; ) { removed.push.call(removed, this.add(list[i])); } return removed; }; this.substractPoint = function(pos) { var i = this.pointIndex(pos); if (i >= 0) return this.ranges.splice(i, 1); }; // merge overlapping ranges this.merge = function() { var removed = []; var list = this.ranges; var next = list[0], range; for (var i = 1; i < list.length; i++) { range = next; next = list[i]; var cmp = this.comparePoints(range.end, next.start); if (cmp < 0) continue; if (cmp == 0 && !(range.isEmpty() || next.isEmpty())) continue; if (this.comparePoints(range.end, next.end) < 0) { range.end.row = next.end.row; range.end.column = next.end.column; } list.splice(i, 1); removed.push(next); next = range; i--; } return removed; }; this.contains = function(row, column) { return this.pointIndex({row: row, column: column}) >= 0; }; this.containsPoint = function(pos) { return this.pointIndex(pos) >= 0; }; this.rangeAtPoint = function(pos) { var i = this.pointIndex(pos); if (i >= 0) return this.ranges[i]; }; this.clipRows = function(startRow, endRow) { var list = this.ranges; if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow) return []; var startIndex = this.pointIndex({row: startRow, column: 0}); if (startIndex < 0) startIndex = -startIndex - 1; var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex); if (endIndex < 0) endIndex = -endIndex - 1; var clipped = []; for (var i = startIndex; i < endIndex; i++) { clipped.push(list[i]); } return clipped; }; this.removeAll = function() { return this.ranges.splice(0, this.ranges.length); }; this.attach = function(session) { if (this.session) this.detach(); this.session = session; this.onChange = this.$onChange.bind(this); this.session.on('change', this.onChange); }; this.detach = function() { if (!this.session) return; this.session.removeListener('change', this.onChange); this.session = null; }; this.$onChange = function(e) { var changeRange = e.data.range; if (e.data.action[0] == "i"){ var start = changeRange.start; var end = changeRange.end; } else { var end = changeRange.start; var start = changeRange.end; } var startRow = start.row; var endRow = end.row; var lineDif = endRow - startRow; var colDiff = -start.column + end.column; var ranges = this.ranges; for (var i = 0, n = ranges.length; i < n; i++) { var r = ranges[i]; if (r.end.row < startRow) continue; if (r.start.row > startRow) break; if (r.start.row == startRow && r.start.column >= start.column ) { r.start.column += colDiff; r.start.row += lineDif; } if (r.end.row == startRow && r.end.column >= start.column) { r.end.column += colDiff; r.end.row += lineDif; } } if (lineDif != 0 && i < n) { for (; i < n; i++) { var r = ranges[i]; r.start.row += lineDif; r.end.row += lineDif; } } }; }).call(RangeList.prototype); exports.RangeList = RangeList; }); define('ace/mouse/multi_select_handler', ['require', 'exports', 'module' , 'ace/lib/event'], function(require, exports, module) { var event = require("../lib/event"); // mouse function isSamePoint(p1, p2) { return p1.row == p2.row && p1.column == p2.column; } function onMouseDown(e) { var ev = e.domEvent; var alt = ev.altKey; var shift = ev.shiftKey; var ctrl = e.getAccelKey(); var button = e.getButton(); if (!ctrl && !alt) { if (e.editor.inMultiSelectMode) { if (button == 0) { e.editor.exitMultiSelectMode(); } else if (button == 2) { var editor = e.editor; var selectionEmpty = editor.selection.isEmpty(); editor.textInput.onContextMenu({x: e.clientX, y: e.clientY}, selectionEmpty); event.capture(editor.container, function(){}, editor.textInput.onContextMenuClose); e.stop(); } } return; } var editor = e.editor; var selection = editor.selection; var isMultiSelect = editor.inMultiSelectMode; var pos = e.getDocumentPosition(); var cursor = selection.getCursor(); var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor)); var mouseX = e.x, mouseY = e.y; var onMouseSelection = function(e) { mouseX = e.clientX; mouseY = e.clientY; }; var blockSelect = function() { var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column); if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.selectionLead)) return; screenCursor = newCursor; editor.selection.moveCursorToPosition(cursor); editor.selection.clearSelection(); editor.renderer.scrollCursorIntoView(); editor.removeSelectionMarkers(rectSel); rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); rectSel.forEach(editor.addSelectionMarker, editor); editor.updateSelectionMarkers(); }; var session = editor.session; var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); var screenCursor = screenAnchor; if (ctrl && !shift && !alt && button == 0) { if (!isMultiSelect && inSelection) return; // dragging if (!isMultiSelect) { var range = selection.toOrientedRange(); editor.addSelectionMarker(range); } var oldRange = selection.rangeList.rangeAtPoint(pos); event.capture(editor.container, function(){}, function() { var tmpSel = selection.toOrientedRange(); if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) selection.substractPoint(tmpSel.cursor); else { if (range) { editor.removeSelectionMarker(range); selection.addRange(range); } selection.addRange(tmpSel); } }); } else if (!shift && alt && button == 0) { e.stop(); if (isMultiSelect && !ctrl) selection.toSingleRange(); else if (!isMultiSelect && ctrl) selection.addRange(); selection.moveCursorToPosition(pos); selection.clearSelection(); var rectSel = []; var onMouseSelectionEnd = function(e) { clearInterval(timerId); editor.removeSelectionMarkers(rectSel); for (var i = 0; i < rectSel.length; i++) selection.addRange(rectSel[i]); }; var onSelectionInterval = blockSelect; event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); var timerId = setInterval(function() {onSelectionInterval();}, 20); return e.preventDefault(); } } exports.onMouseDown = onMouseDown; }); define('ace/commands/multi_select_commands', ['require', 'exports', 'module' , 'ace/keyboard/hash_handler'], function(require, exports, module) { // commands to enter multiselect mode exports.defaultCommands = [{ name: "addCursorAbove", exec: function(editor) { editor.selectMoreLines(-1); }, bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, readonly: true }, { name: "addCursorBelow", exec: function(editor) { editor.selectMoreLines(1); }, bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, readonly: true }, { name: "addCursorAboveSkipCurrent", exec: function(editor) { editor.selectMoreLines(-1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, readonly: true }, { name: "addCursorBelowSkipCurrent", exec: function(editor) { editor.selectMoreLines(1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, readonly: true }, { name: "selectMoreBefore", exec: function(editor) { editor.selectMore(-1); }, bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, readonly: true }, { name: "selectMoreAfter", exec: function(editor) { editor.selectMore(1); }, bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, readonly: true }, { name: "selectNextBefore", exec: function(editor) { editor.selectMore(-1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, readonly: true }, { name: "selectNextAfter", exec: function(editor) { editor.selectMore(1, true); }, bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, readonly: true }, { name: "splitIntoLines", exec: function(editor) { editor.multiSelect.splitIntoLines(); }, bindKey: {win: "Ctrl-Shift-L", mac: "Ctrl-Shift-L"}, readonly: true }]; // commands active in multiselect mode exports.multiSelectCommands = [{ name: "singleSelection", bindKey: "esc", exec: function(editor) { editor.exitMultiSelectMode(); }, readonly: true, isAvailable: function(editor) {return editor.inMultiSelectMode} }]; var HashHandler = require("../keyboard/hash_handler").HashHandler; exports.keyboardHandler = new HashHandler(exports.multiSelectCommands); }); define('ace/worker/worker_client', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/config'], function(require, exports, module) { var oop = require("../lib/oop"); var EventEmitter = require("../lib/event_emitter").EventEmitter; var config = require("../config"); var WorkerClient = function(topLevelNamespaces, packagedJs, mod, classname) { this.changeListener = this.changeListener.bind(this); if (config.get("packaged")) { this.$worker = new Worker(config.get("workerPath") + "/" + packagedJs); } else { var workerUrl; if (typeof require.supports !== "undefined" && require.supports.indexOf("ucjs2-pinf-0") >= 0) { // We are running in the sourcemint loader. workerUrl = require.nameToUrl("ace/worker/worker_sourcemint"); } else { // We are running in RequireJS. workerUrl = this.$normalizePath(require.nameToUrl("ace/worker/worker", null, "_")); } this.$worker = new Worker(workerUrl); var tlns = {}; for (var i=0; i<topLevelNamespaces.length; i++) { var ns = topLevelNamespaces[i]; var path = this.$normalizePath(require.nameToUrl(ns, null, "_").replace(/.js$/, "")); tlns[ns] = path; } } this.$worker.postMessage({ init : true, tlns: tlns, module: mod, classname: classname }); this.callbackId = 1; this.callbacks = {}; var _self = this; this.$worker.onerror = function(e) { window.console && console.log && console.log(e); throw e; }; this.$worker.onmessage = function(e) { var msg = e.data; switch(msg.type) { case "log": window.console && console.log && console.log(msg.data); break; case "event": _self._emit(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.$normalizePath = function(path) { path = path.replace(/^[a-z]+:\/\/[^\/]+/, ""); // Remove domain name and rebuild it path = location.protocol + "//" + location.host // paths starting with a slash are relative to the root (host) + (path.charAt(0) == "/" ? "" : location.pathname.replace(/\/[^\/]*$/, "")) + "/" + path.replace(/^[\/]+/, ""); return path; }; this.terminate = function() { this._emit("terminate", {}); this.$worker.terminate(); this.$worker = null; this.$doc.removeEventListener("change", this.changeListener); this.$doc = null; }; 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) { try { // firefox refuses to clone objects which have function properties // TODO: cleanup event this.$worker.postMessage({event: event, data: {data: data.data}}); } catch(ex) {} }; this.attachToDocument = function(doc) { if(this.$doc) this.terminate(); this.$doc = doc; this.call("setValue", [doc.getValue()]); doc.on("change", this.changeListener); }; this.changeListener = function(e) { e.range = { start: e.data.range.start, end: e.data.range.end }; this.emit("change", e); }; }).call(WorkerClient.prototype); exports.WorkerClient = WorkerClient; }); define('ace/keyboard/state_handler', ['require', 'exports', 'module' ], function(require, exports, module) { // If you're developing a new keymapping and want to get an idea what's going // on, then enable debugging. var DEBUG = false; function StateHandler(keymapping) { this.keymapping = this.$buildKeymappingRegex(keymapping); } StateHandler.prototype = { /* * Build the RegExp from the keymapping as RegExp can't stored directly * in the metadata JSON and as the RegExp used to match the keys/buffer * need to be adapted. */ $buildKeymappingRegex: function(keymapping) { for (var state in keymapping) { this.$buildBindingsRegex(keymapping[state]); } return keymapping; }, $buildBindingsRegex: function(bindings) { // Escape a given Regex string. bindings.forEach(function(binding) { if (binding.key) { binding.key = new RegExp('^' + binding.key + '$'); } else if (Array.isArray(binding.regex)) { if (!('key' in binding)) binding.key = new RegExp('^' + binding.regex[1] + '$'); binding.regex = new RegExp(binding.regex.join('') + '$'); } else if (binding.regex) { binding.regex = new RegExp(binding.regex + '$'); } }); }, $composeBuffer: function(data, hashId, key, e) { // Initialize the data object. if (data.state == null || data.buffer == null) { data.state = "start"; data.buffer = ""; } var keyArray = []; if (hashId & 1) keyArray.push("ctrl"); if (hashId & 8) keyArray.push("command"); if (hashId & 2) keyArray.push("option"); if (hashId & 4) keyArray.push("shift"); if (key) keyArray.push(key); var symbolicName = keyArray.join("-"); var bufferToUse = data.buffer + symbolicName; // Don't add the symbolic name to the key buffer if the alt_ key is // part of the symbolic name. If it starts with alt_, this means // that the user hit an alt keycombo and there will be a single, // new character detected after this event, which then will be // added to the buffer (e.g. alt_j will result in ∆). // // We test for 2 and not for & 2 as we only want to exclude the case where // the option key is pressed alone. if (hashId != 2) { data.buffer = bufferToUse; } var bufferObj = { bufferToUse: bufferToUse, symbolicName: symbolicName, }; if (e) { bufferObj.keyIdentifier = e.keyIdentifier } return bufferObj; }, $find: function(data, buffer, symbolicName, hashId, key, keyIdentifier) { // Holds the command to execute and the args if a command matched. var result = {}; // Loop over all the bindings of the keymap until a match is found. this.keymapping[data.state].some(function(binding) { var match; // Check if the key matches. if (binding.key && !binding.key.test(symbolicName)) { return false; } // Check if the regex matches. if (binding.regex && !(match = binding.regex.exec(buffer))) { return false; } // Check if the match function matches. if (binding.match && !binding.match(buffer, hashId, key, symbolicName, keyIdentifier)) { return false; } // Check for disallowed matches. if (binding.disallowMatches) { for (var i = 0; i < binding.disallowMatches.length; i++) { if (!!match[binding.disallowMatches[i]]) { return false; } } } // If there is a command to execute, then figure out the // command and the arguments. if (binding.exec) { result.command = binding.exec; // Build the arguments. if (binding.params) { var value; result.args = {}; binding.params.forEach(function(param) { if (param.match != null && match != null) { value = match[param.match] || param.defaultValue; } else { value = param.defaultValue; } if (param.type === 'number') { value = parseInt(value); } result.args[param.name] = value; }); } data.buffer = ""; } // Handle the 'then' property. if (binding.then) { data.state = binding.then; data.buffer = ""; } // If no command is set, then execute the "null" fake command. if (result.command == null) { result.command = "null"; } if (DEBUG) { console.log("KeyboardStateMapper#find", binding); } return true; }); if (result.command) { return result; } else { data.buffer = ""; return false; } }, /* * This function is called by keyBinding. */ handleKeyboard: function(data, hashId, key, keyCode, e) { if (hashId == -1) hashId = 0 // If we pressed any command key but no other key, then ignore the input. // Otherwise "shift-" is added to the buffer, and later on "shift-g" // which results in "shift-shift-g" which doesn't make sense. if (hashId != 0 && (key == "" || key == String.fromCharCode(0))) { return null; } // Compute the current value of the keyboard input buffer. var r = this.$composeBuffer(data, hashId, key, e); var buffer = r.bufferToUse; var symbolicName = r.symbolicName; var keyId = r.keyIdentifier; r = this.$find(data, buffer, symbolicName, hashId, key, keyId); if (DEBUG) { console.log("KeyboardStateMapper#match", buffer, symbolicName, r); } return r; } } /* * This is a useful matching function and therefore is defined here so that * users of KeyboardStateMapper can use it. * * @return boolean * If no command key (Command|Option|Shift|Ctrl) is pressed, it * returns true. If the only the Shift key is pressed + a character * true is returned as well. Otherwise, false is returned. * Summing up, the function returns true whenever the user typed * a normal character on the keyboard and no shortcut. */ exports.matchCharacterOnly = function(buffer, hashId, key, symbolicName) { // If no command keys are pressed, then catch the input. if (hashId == 0) { return true; } // If only the shift key is pressed and a character key, then // catch that input as well. else if ((hashId == 4) && key.length == 1) { return true; } // Otherwise, we let the input got through. else { return false; } }; exports.StateHandler = StateHandler; }); define('ace/placeholder', ['require', 'exports', 'module' , 'ace/range', 'ace/lib/event_emitter', 'ace/lib/oop'], function(require, exports, module) { var Range = require('./range').Range; var EventEmitter = require("./lib/event_emitter").EventEmitter; var oop = require("./lib/oop"); /** * new PlaceHolder(session, length, pos, others, mainClass, othersClass) * - session (Document): The document to associate with the anchor * - length (Number): The starting row position * - pos (Number): The starting column position * - others (String): * - mainClass (String): * - othersClass (String): * * TODO * **/ var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) { var _self = this; this.length = length; this.session = session; this.doc = session.getDocument(); this.mainClass = mainClass; this.othersClass = othersClass; this.$onUpdate = this.onUpdate.bind(this); this.doc.on("change", this.$onUpdate); this.$others = others; this.$onCursorChange = function() { setTimeout(function() { _self.onCursorChange(); }); }; this.$pos = pos; // Used for reset var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1}; this.$undoStackDepth = undoStack.length; this.setup(); session.selection.on("changeCursor", this.$onCursorChange); }; (function() { oop.implement(this, EventEmitter); this.setup = function() { var _self = this; var doc = this.doc; var session = this.session; var pos = this.$pos; 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(event) { var delta = event.data; var range = delta.range; 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 === "insertText" ? 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 === "insertText") { 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.insert(newPos, delta.text); } } else if(delta.action === "removeText") { 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)); } } // Special case: insert in beginning if(range.start.column === this.pos.column && delta.action === "insertText") { 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 === "removeText") { 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) 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.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); } }; }).call(PlaceHolder.prototype); exports.PlaceHolder = PlaceHolder; }); define('ace/theme/textmate', ['require', 'exports', 'module' , 'text!ace/theme/textmate.css', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = false; exports.cssClass = "ace-tm"; exports.cssText = require('text!./textmate.css'); var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); }); define("text!ace/theme/textmate.css", [], ".ace-tm .ace_editor {\n" + " border: 2px solid rgb(159, 159, 159);\n" + "}\n" + "\n" + ".ace-tm .ace_editor.ace_focus {\n" + " border: 2px solid #327fbd;\n" + "}\n" + "\n" + ".ace-tm .ace_gutter {\n" + " background: #e8e8e8;\n" + " color: #333;\n" + "}\n" + "\n" + ".ace-tm .ace_print_margin {\n" + " width: 1px;\n" + " background: #e8e8e8;\n" + "}\n" + "\n" + ".ace-tm .ace_fold {\n" + " background-color: #6B72E6;\n" + "}\n" + "\n" + ".ace-tm .ace_text-layer {\n" + " cursor: text;\n" + "}\n" + "\n" + ".ace-tm .ace_cursor {\n" + " border-left: 2px solid black;\n" + "}\n" + "\n" + ".ace-tm .ace_cursor.ace_overwrite {\n" + " border-left: 0px;\n" + " border-bottom: 1px solid black;\n" + "}\n" + " \n" + ".ace-tm .ace_line .ace_invisible {\n" + " color: rgb(191, 191, 191);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_storage,\n" + ".ace-tm .ace_line .ace_keyword {\n" + " color: blue;\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant {\n" + " color: rgb(197, 6, 11);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_buildin {\n" + " color: rgb(88, 72, 246);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_language {\n" + " color: rgb(88, 92, 246);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_library {\n" + " color: rgb(6, 150, 14);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_invalid {\n" + " background-color: rgba(255, 0, 0, 0.1);\n" + " color: red;\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_support.ace_function {\n" + " color: rgb(60, 76, 114);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_support.ace_constant {\n" + " color: rgb(6, 150, 14);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_support.ace_type,\n" + ".ace-tm .ace_line .ace_support.ace_class {\n" + " color: rgb(109, 121, 222);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_keyword.ace_operator {\n" + " color: rgb(104, 118, 135);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_string {\n" + " color: rgb(3, 106, 7);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_comment {\n" + " color: rgb(76, 136, 107);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_comment.ace_doc {\n" + " color: rgb(0, 102, 255);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_comment.ace_doc.ace_tag {\n" + " color: rgb(128, 159, 191);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_constant.ace_numeric {\n" + " color: rgb(0, 0, 205);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_variable {\n" + " color: rgb(49, 132, 149);\n" + "}\n" + "\n" + ".ace-tm .ace_line .ace_xml_pe {\n" + " color: rgb(104, 104, 91);\n" + "}\n" + "\n" + ".ace-tm .ace_entity.ace_name.ace_function {\n" + " color: #0000A2;\n" + "}\n" + "\n" + ".ace-tm .ace_markup.ace_markupine {\n" + " text-decoration:underline;\n" + "}\n" + "\n" + ".ace-tm .ace_markup.ace_heading {\n" + " color: rgb(12, 7, 255);\n" + "}\n" + "\n" + ".ace-tm .ace_markup.ace_list {\n" + " color:rgb(185, 6, 144);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_selection {\n" + " background: rgb(181, 213, 255);\n" + "}\n" + ".ace-tm.multiselect .ace_selection.start {\n" + " box-shadow: 0 0 3px 0px white;\n" + " border-radius: 2px;\n" + "}\n" + ".ace-tm .ace_marker-layer .ace_step {\n" + " background: rgb(252, 255, 0);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_stack {\n" + " background: rgb(164, 229, 101);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_bracket {\n" + " margin: -1px 0 0 -1px;\n" + " border: 1px solid rgb(192, 192, 192);\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_active_line {\n" + " background: rgba(0, 0, 0, 0.07);\n" + "}\n" + ".ace-tm .ace_gutter_active_line{\n" + " background-color : #dcdcdc;\n" + "}\n" + "\n" + ".ace-tm .ace_marker-layer .ace_selected_word {\n" + " background: rgb(250, 250, 255);\n" + " border: 1px solid rgb(200, 200, 250);\n" + "}\n" + "\n" + ".ace-tm .ace_meta.ace_tag {\n" + " color:rgb(0, 50, 198);\n" + "}\n" + "\n" + ".ace-tm .ace_string.ace_regex {\n" + " color: rgb(255, 0, 0)\n" + "}"); ; (function() { window.require(["ace/ace"], function(a) { a && a.config.init(); if (!window.ace) window.ace = {}; for (var key in a) if (a.hasOwnProperty(key)) ace[key] = a[key]; }); })();
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Gastón Kleiman <gaston.kleiman AT gmail DOT 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 ***** */ define('ace/mode/c_cpp', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/c_cpp_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var c_cppHighlightRules = require("./c_cpp_highlight_rules").c_cppHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new c_cppHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)\/\//; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "//"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/c_cpp_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var c_cppHighlightRules = function() { var keywords = lang.arrayToMap( ("and|double|not_eq|throw|and_eq|dynamic_cast|operator|true|" + "asm|else|or|try|auto|enum|or_eq|typedef|bitand|explicit|private|" + "typeid|bitor|extern|protected|typename|bool|false|public|union|" + "break|float|register|unsigned|case|fro|reinterpret-cast|using|catch|" + "friend|return|virtual|char|goto|short|void|class|if|signed|volatile|" + "compl|inline|sizeof|wchar_t|const|int|static|while|const-cast|long|" + "static_cast|xor|continue|mutable|struct|xor_eq|default|namespace|" + "switch|delete|new|template|do|not|this|for").split("|") ); var buildinConstants = lang.arrayToMap( ("NULL").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment merge : true, regex : "\\/\\*", next : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant", // <CONSTANT> regex : "<[a-zA-Z0-9.]+>" }, { token : "keyword", // pre-compiler directivs regex : "(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(c_cppHighlightRules, TextHighlightRules); exports.c_cppHighlightRules = c_cppHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * The Original Code is Ajax.org Code Editor (ACE). * * Contributor(s): * Jonathan Camile <jonathan.camile AT gmail DOT 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 ***** */ define('ace/mode/sql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sql_highlight_rules', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var SqlHighlightRules = require("./sql_highlight_rules").SqlHighlightRules; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new SqlHighlightRules().getRules()); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var outentedRows = []; var re = /^(\s*)--/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "--"); } }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/sql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var SqlHighlightRules = function() { var keywords = lang.arrayToMap( ("select|from|where|and|or|group|by|order|limit|offset|having|as|case|" + "when|else|end|type|left|right|join|on|outer|desc|asc").split("|") ); var builtinConstants = lang.arrayToMap( ("true|false|null").split("|") ); var builtinFunctions = lang.arrayToMap( ("count|min|max|avg|sum|rank|now|coalesce").split("|") ); this.$rules = { "start" : [ { token : "comment", regex : "--.*$" }, { token : "string", // " string regex : '".*"' }, { token : "string", // ' string regex : "'.*'" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : function(value) { value = value.toLowerCase(); if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token : "paren.lparen", regex : "[\\(]" }, { token : "paren.rparen", regex : "[\\)]" }, { token : "text", regex : "\\s+" } ] }; }; oop.inherits(SqlHighlightRules, TextHighlightRules); exports.SqlHighlightRules = SqlHighlightRules; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Panagiotis Astithas <pastith AT gmail DOT 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 ***** */ define('ace/mode/perl', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/perl_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PerlHighlightRules = require("./perl_highlight_rules").PerlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new PerlHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/perl_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PerlHighlightRules = function() { var keywords = lang.arrayToMap( ("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|" + "no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars").split("|") ); var buildinConstants = lang.arrayToMap( ("ARGV|ENV|INC|SIG").split("|") ); var builtinFunctions = lang.arrayToMap( ("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|" + "gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|" + "getpeername|setpriority|getprotoent|setprotoent|getpriority|" + "endprotoent|getservent|setservent|endservent|sethostent|socketpair|" + "getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|" + "localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|" + "closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|" + "shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|" + "dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|" + "setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|" + "lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|" + "waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|" + "chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|" + "unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|" + "length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|" + "undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|" + "sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|" + "BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|" + "join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|" + "keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|" + "eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|" + "map|die|uc|lc|do").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '["].*\\\\$', next : "qqstring" }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "string", // multi line string start merge : true, regex : "['].*\\\\$", next : "qstring" }, { token : "constant.numeric", // hex regex : "0x[0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)" }, { token : "lparen", regex : "[[({]" }, { token : "rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(PerlHighlightRules, TextHighlightRules); exports.PerlHighlightRules = PerlHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/vibrant_ink', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-vibrant-ink"; exports.cssText = "\ .ace-vibrant-ink .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-vibrant-ink .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-vibrant-ink .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-vibrant-ink .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-vibrant-ink .ace_scroller {\ background-color: #0F0F0F;\ }\ \ .ace-vibrant-ink .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_selection {\ background: #6699CC;\ }\ \ .ace-vibrant-ink.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #0F0F0F;\ border-radius: 2px;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid #404040;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_active_line {\ background: #333333;\ }\ \ .ace-vibrant-ink .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-vibrant-ink .ace_marker-layer .ace_selected_word {\ border: 1px solid #6699CC;\ }\ \ .ace-vibrant-ink .ace_invisible {\ color: #404040;\ }\ \ .ace-vibrant-ink .ace_keyword, .ace-vibrant-ink .ace_meta {\ color:#FF6600;\ }\ \ .ace-vibrant-ink .ace_constant, .ace-vibrant-ink .ace_constant.ace_other {\ color:#339999;\ }\ \ .ace-vibrant-ink .ace_constant.ace_character, {\ color:#339999;\ }\ \ .ace-vibrant-ink .ace_constant.ace_character.ace_escape, {\ color:#339999;\ }\ \ .ace-vibrant-ink .ace_constant.ace_numeric {\ color:#99CC99;\ }\ \ .ace-vibrant-ink .ace_invalid {\ color:#CCFF33;\ background-color:#000000;\ }\ \ .ace-vibrant-ink .ace_invalid.ace_deprecated {\ color:#CCFF33;\ background-color:#000000;\ }\ \ .ace-vibrant-ink .ace_fold {\ background-color: #FFCC00;\ border-color: #FFFFFF;\ }\ \ .ace-vibrant-ink .ace_support.ace_function {\ color:#FFCC00;\ }\ \ .ace-vibrant-ink .ace_variable {\ color:#FFCC00;\ }\ \ .ace-vibrant-ink .ace_variable.ace_parameter {\ font-style:italic;\ }\ \ .ace-vibrant-ink .ace_string {\ color:#66FF00;\ }\ \ .ace-vibrant-ink .ace_string.ace_regexp {\ color:#44B4CC;\ }\ \ .ace-vibrant-ink .ace_comment {\ color:#9933CC;\ }\ \ .ace-vibrant-ink .ace_entity.ace_other.ace_attribute-name {\ font-style:italic;\ color:#99CC99;\ }\ \ .ace-vibrant-ink .ace_entity.ace_name.ace_function {\ color:#FFCC00;\ }\ \ .ace-vibrant-ink .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * * 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 ***** */ define('ace/theme/mono_industrial', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-mono-industrial"; exports.cssText = "\ .ace-mono-industrial .ace_editor {\ border: 2px solid rgb(159, 159, 159);\ }\ \ .ace-mono-industrial .ace_editor.ace_focus {\ border: 2px solid #327fbd;\ }\ \ .ace-mono-industrial .ace_gutter {\ background: #e8e8e8;\ color: #333;\ }\ \ .ace-mono-industrial .ace_print_margin {\ width: 1px;\ background: #e8e8e8;\ }\ \ .ace-mono-industrial .ace_scroller {\ background-color: #222C28;\ }\ \ .ace-mono-industrial .ace_text-layer {\ cursor: text;\ color: #FFFFFF;\ }\ \ .ace-mono-industrial .ace_cursor {\ border-left: 2px solid #FFFFFF;\ }\ \ .ace-mono-industrial .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #FFFFFF;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_selection {\ background: rgba(145, 153, 148, 0.40);\ }\ \ .ace-mono-industrial.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #222C28;\ border-radius: 2px;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0);\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(102, 108, 104, 0.50);\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_active_line {\ background: rgba(12, 13, 12, 0.25);\ }\ \ .ace-mono-industrial .ace_gutter_active_line {\ background-color : #dcdcdc;\ }\ \ .ace-mono-industrial .ace_marker-layer .ace_selected_word {\ border: 1px solid rgba(145, 153, 148, 0.40);\ }\ \ .ace-mono-industrial .ace_invisible {\ color: rgba(102, 108, 104, 0.50);\ }\ \ .ace-mono-industrial .ace_keyword, .ace-mono-industrial .ace_meta {\ color:#A39E64;\ }\ \ .ace-mono-industrial .ace_keyword.ace_operator {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_constant, .ace-mono-industrial .ace_constant.ace_other {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_character, {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_character.ace_escape, {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_constant.ace_numeric {\ color:#E98800;\ }\ \ .ace-mono-industrial .ace_invalid {\ color:#FFFFFF;\ background-color:rgba(153, 0, 0, 0.68);\ }\ \ .ace-mono-industrial .ace_support.ace_constant {\ color:#C87500;\ }\ \ .ace-mono-industrial .ace_fold {\ background-color: #A8B3AB;\ border-color: #FFFFFF;\ }\ \ .ace-mono-industrial .ace_support.ace_function {\ color:#588E60;\ }\ \ .ace-mono-industrial .ace_storage {\ color:#C23B00;\ }\ \ .ace-mono-industrial .ace_variable {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_variable.ace_parameter {\ color:#648BD2;\ }\ \ .ace-mono-industrial .ace_comment {\ color:#666C68;\ background-color:#151C19;\ }\ \ .ace-mono-industrial .ace_variable.ace_language {\ color:#648BD2;\ }\ \ .ace-mono-industrial .ace_entity.ace_other.ace_attribute-name {\ color:#909993;\ }\ \ .ace-mono-industrial .ace_entity.ace_name {\ color:#5778B6;\ }\ \ .ace-mono-industrial .ace_entity.ace_name.ace_function {\ color:#A8B3AB;\ }\ \ .ace-mono-industrial .ace_markup.ace_underline {\ text-decoration:underline;\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
JavaScript
/* ***** BEGIN LICENSE BLOCK ***** * The Original Code is Ajax.org Code Editor (ACE). * * Contributor(s): * Meg Sharkey <megshark AT gmail DOT 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 ***** */ define('ace/mode/yaml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/yaml_highlight_rules', 'ace/mode/matching_brace_outdent'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var YamlHighlightRules = require("./yaml_highlight_rules").YamlHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Mode = function() { this.$tokenizer = new Tokenizer(new YamlHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/yaml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var YamlHighlightRules = function() { // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "comment", regex : "^---" }, { token: "variable", regex: "[&\\*][a-zA-Z0-9-_]+" }, { token: ["identifier", "text"], regex: "(\\w+\\s*:)(\\w*)" }, { token : "keyword.operator", regex : "<<\\w*:\\w*" }, { token : "keyword.operator", regex : "-\\s*(?=[{])" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // multi line string start merge : true, regex : '[\\|>]\\w*', next : "qqstring" }, { token : "string", // single quoted string regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false|yes|no)\\b" }, { token : "invalid.illegal", // comments are not allowed regex : "\\/\\/.*$" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", regex : '(?=(?:(?:\\\\.)|(?:[^:]))*?:)', next : "start" }, { token : "string", merge : true, regex : '.+' } ]} }; oop.inherits(YamlHighlightRules, TextHighlightRules); exports.YamlHighlightRules = YamlHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; });
JavaScript
/* ***** 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 Ajax.org Code Editor (ACE). * * The Initial Developer of the Original Code is * Ajax.org B.V. * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Fabian Jakobs <fabian AT ajax DOT org> * Colin Gourlay <colin DOT j DOT gourlay AT gmail DOT 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 ***** */ define('ace/mode/python', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/python_highlight_rules', 'ace/mode/folding/pythonic', 'ace/range'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules; var PythonFoldMode = require("./folding/pythonic").FoldMode; var Range = require("../range").Range; var Mode = function() { this.$tokenizer = new Tokenizer(new PythonHighlightRules().getRules()); this.foldingRules = new PythonFoldMode("\\:"); }; oop.inherits(Mode, TextMode); (function() { this.toggleCommentLines = function(state, doc, startRow, endRow) { var outdent = true; var re = /^(\s*)#/; for (var i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } if (outdent) { var deleteRange = new Range(0, 0, 0, 0); for (var i=startRow; i<= endRow; i++) { var line = doc.getLine(i); var m = line.match(re); deleteRange.start.row = i; deleteRange.end.row = i; deleteRange.end.column = m[0].length; doc.replace(deleteRange, m[1]); } } else { doc.indentRows(startRow, endRow, "#"); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens; if (!tokens) return false; // ignore trailing comments do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { // outdenting in python is slightly different because it always applies // to the next line and only of a new line is inserted row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/python_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PythonHighlightRules = function() { var keywords = lang.arrayToMap( ("and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + "raise|return|try|while|with|yield").split("|") ); var builtinConstants = lang.arrayToMap( ("True|False|None|NotImplemented|Ellipsis|__debug__").split("|") ); var builtinFunctions = lang.arrayToMap( ("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern").split("|") ); var futureReserved = lang.arrayToMap( ("").split("|") ); var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?"; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // """ string regex : strPre + '"{3}(?:[^\\\\]|\\\\.)*?"{3}' }, { token : "string", // multi line """ string start merge : true, regex : strPre + '"{3}.*$', next : "qqstring" }, { token : "string", // " string regex : strPre + '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ''' string regex : strPre + "'{3}(?:[^\\\\]|\\\\.)*?'{3}" }, { token : "string", // multi line ''' string start merge : true, regex : strPre + "'{3}.*$", next : "qstring" }, { token : "string", // ' string regex : strPre + "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // imaginary regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // long integer regex : integer + "[lL]\\b" }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else return "identifier"; }, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" }, { token : "text", regex : "\\s+" } ], "qqstring" : [ { token : "string", // multi line """ string end regex : '(?:[^\\\\]|\\\\.)*?"{3}', next : "start" }, { token : "string", merge : true, regex : '.+' } ], "qstring" : [ { token : "string", // multi line ''' string end regex : "(?:[^\\\\]|\\\\.)*?'{3}", next : "start" }, { token : "string", merge : true, regex : '.+' } ] }; }; oop.inherits(PythonHighlightRules, TextHighlightRules); exports.PythonHighlightRules = PythonHighlightRules; }); define('ace/mode/folding/pythonic', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(markers) { this.foldingStartMarker = new RegExp("(?:([\\[{])|(" + markers + "))(?:\\s*)(?:#.*)?$"); }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { if (match[1]) return this.openingBracketBlock(session, match[1], row, match.index); if (match[2]) return this.indentationBlock(session, row, match.index + match[2].length); return this.indentationBlock(session, row); } } }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
define('ace/mode/haxe', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/haxe_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) { var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var Tokenizer = require("../tokenizer").Tokenizer; var HaxeHighlightRules = require("./haxe_highlight_rules").HaxeHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.$tokenizer = new Tokenizer(new HaxeHighlightRules().getRules()); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.$tokenizer.getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); if (match) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { return null; }; }).call(Mode.prototype); exports.Mode = Mode; }); define('ace/mode/haxe_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HaxeHighlightRules = function() { var keywords = lang.arrayToMap( ("break|case|cast|catch|class|continue|default|else|enum|extends|for|function|if|implements|import|in|inline|interface|new|override|package|private|public|return|static|super|switch|this|throw|trace|try|typedef|untyped|var|while|Array|Void|Bool|Int|UInt|Float|Dynamic|String|List|Hash|IntHash|Error|Unknown|Type|Std").split("|") ); var buildinConstants = lang.arrayToMap( ("null|true|false").split("|") ); // regexp must not have capturing parentheses. Use (?:) instead. // regexps are ordered -> the first match is used this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", merge : true, next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : function(value) { if (value == "this") return "variable.language"; else if (keywords.hasOwnProperty(value)) return "keyword"; else if (buildinConstants.hasOwnProperty(value)) return "constant.language"; else return "identifier"; }, // TODO: Unicode escape sequences // TODO: Unicode identifiers regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({<]" }, { token : "paren.rparen", regex : "[\\])}>]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line merge : true, regex : ".+" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(HaxeHighlightRules, TextHighlightRules); exports.HaxeHighlightRules = HaxeHighlightRules; }); define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) { var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, { token : "comment.doc", merge : true, regex : "\\s+" }, { token : "comment.doc", merge : true, regex : "TODO" }, { token : "comment.doc", merge : true, regex : "[^@\\*]+" }, { token : "comment.doc", merge : true, regex : "." }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment merge : true, regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment merge : true, regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { var match = line.match(/^(\s+)/); if (match) { return match[1]; } return ""; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) { var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = function () { this.add("braces", "insertion", function (state, action, editor, session, text) { if (text == '{') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '{' + selected + '}', selection: false }; } else { return { text: '{}', selection: [1, 1] }; } } else if (text == '}') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } else if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1}); if (!openBracePos) return null; var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString()); var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row)); return { text: '\n' + indent + '\n' + next_indent, selection: [1, indent.length, 1, indent.length] }; } } }); this.add("braces", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } } }); this.add("parens", "insertion", function (state, action, editor, session, text) { if (text == '(') { var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: '(' + selected + ')', selection: false }; } else { return { text: '()', selection: [1, 1] }; } } else if (text == ')') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null) { return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "") { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); // We're escaped. if (leftChar == '\\') { return null; } // Find what token we're inside. var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } // Try and be smart about when we auto insert. if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { // Ignore input and move right one if we're typing over the closing quote. var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == '"') { range.end.column++; return range; } } }); }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) { var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length); range.end.column -= 2; return range; } if (foldStyle !== "markbeginend") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[2]) { var range = session.getCommentFoldRange(row, i); range.end.column -= 2; return range; } var end = {row: row, column: i}; var start = session.$findOpeningBracket(match[1], end); if (!start) return; start.column++; end.column--; return Range.fromPoints(start, end); } }; }).call(FoldMode.prototype); }); define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) { var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; (function() { this.foldingStartMarker = null; this.foldingStopMarker = null; // must return "" if there's no fold, to enable caching this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.foldingStartMarker.test(line)) return "start"; if (foldStyle == "markbeginend" && this.foldingStopMarker && this.foldingStopMarker.test(line)) return "end"; return ""; }; this.getFoldWidgetRange = function(session, foldStyle, row) { return null; }; this.indentationBlock = function(session, row, column) { var re = /^\s*/; var startRow = row; var endRow = row; var line = session.getLine(row); var startColumn = column || line.length; var startLevel = line.match(re)[0].length; var maxRow = session.getLength() while (++row < maxRow) { line = session.getLine(row); var level = line.match(re)[0].length; if (level == line.length) continue; if (level <= startLevel) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) { var start = {row: row, column: column + 1}; var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine); if (!end) return; var fw = session.foldWidgets[end.row]; if (fw == null) fw = this.getFoldWidget(session, end.row); if (fw == "start") { end.row --; end.column = session.getLine(end.row).length; } return Range.fromPoints(start, end); }; }).call(FoldMode.prototype); });
JavaScript
function create_menu(basepath) { var base = (basepath == 'null') ? '' : basepath; document.write( '<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' + '<td class="td" valign="top">' + '<ul>' + '<li><a href="'+base+'index.html">User Guide Home</a></li>' + '<li><a href="'+base+'toc.html">Table of Contents Page</a></li>' + '</ul>' + '<h3>Basic Info</h3>' + '<ul>' + '<li><a href="'+base+'general/requirements.html">Server Requirements</a></li>' + '<li><a href="'+base+'license.html">License Agreement</a></li>' + '<li><a href="'+base+'changelog.html">Change Log</a></li>' + '<li><a href="'+base+'general/credits.html">Credits</a></li>' + '</ul>' + '<h3>Installation</h3>' + '<ul>' + '<li><a href="'+base+'installation/downloads.html">Downloading CodeIgniter</a></li>' + '<li><a href="'+base+'installation/index.html">Installation Instructions</a></li>' + '<li><a href="'+base+'installation/upgrading.html">Upgrading from a Previous Version</a></li>' + '<li><a href="'+base+'installation/troubleshooting.html">Troubleshooting</a></li>' + '</ul>' + '<h3>Introduction</h3>' + '<ul>' + '<li><a href="'+base+'overview/getting_started.html">Getting Started</a></li>' + '<li><a href="'+base+'overview/at_a_glance.html">CodeIgniter at a Glance</a></li>' + '<li><a href="'+base+'overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li>' + '<li><a href="'+base+'overview/features.html">Supported Features</a></li>' + '<li><a href="'+base+'overview/appflow.html">Application Flow Chart</a></li>' + '<li><a href="'+base+'overview/mvc.html">Model-View-Controller</a></li>' + '<li><a href="'+base+'overview/goals.html">Architectural Goals</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>General Topics</h3>' + '<ul>' + '<li><a href="'+base+'general/urls.html">CodeIgniter URLs</a></li>' + '<li><a href="'+base+'general/controllers.html">Controllers</a></li>' + '<li><a href="'+base+'general/reserved_names.html">Reserved Names</a></li>' + '<li><a href="'+base+'general/views.html">Views</a></li>' + '<li><a href="'+base+'general/models.html">Models</a></li>' + '<li><a href="'+base+'general/helpers.html">Helpers</a></li>' + '<li><a href="'+base+'general/libraries.html">Using CodeIgniter Libraries</a></li>' + '<li><a href="'+base+'general/creating_libraries.html">Creating Your Own Libraries</a></li>' + '<li><a href="'+base+'general/core_classes.html">Creating Core Classes</a></li>' + '<li><a href="'+base+'general/hooks.html">Hooks - Extending the Core</a></li>' + '<li><a href="'+base+'general/autoloader.html">Auto-loading Resources</a></li>' + '<li><a href="'+base+'general/common_functions.html">Common Functions</a></li>' + '<li><a href="'+base+'general/routing.html">URI Routing</a></li>' + '<li><a href="'+base+'general/errors.html">Error Handling</a></li>' + '<li><a href="'+base+'general/caching.html">Caching</a></li>' + '<li><a href="'+base+'general/profiling.html">Profiling Your Application</a></li>' + '<li><a href="'+base+'general/cli.html">Running via the CLI</a></li>' + '<li><a href="'+base+'general/managing_apps.html">Managing Applications</a></li>' + '<li><a href="'+base+'general/environments.html">Handling Multiple Environments</a></li>' + '<li><a href="'+base+'general/alternative_php.html">Alternative PHP Syntax</a></li>' + '<li><a href="'+base+'general/security.html">Security</a></li>' + '<li><a href="'+base+'general/styleguide.html">PHP Style Guide</a></li>' + '<li><a href="'+base+'doc_style/index.html">Writing Documentation</a></li>' + '</ul>' + '<h3>Additional Resources</h3>' + '<ul>' + '<li><a href="http://codeigniter.com/forums/">Community Forums</a></li>' + '<li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>Class Reference</h3>' + '<ul>' + '<li><a href="'+base+'libraries/benchmark.html">Benchmarking Class</a></li>' + '<li><a href="'+base+'libraries/calendar.html">Calendar Class</a></li>' + '<li><a href="'+base+'libraries/cart.html">Cart Class</a></li>' + '<li><a href="'+base+'libraries/config.html">Config Class</a></li>' + '<li><a href="'+base+'libraries/email.html">Email Class</a></li>' + '<li><a href="'+base+'libraries/encryption.html">Encryption Class</a></li>' + '<li><a href="'+base+'libraries/file_uploading.html">File Uploading Class</a></li>' + '<li><a href="'+base+'libraries/form_validation.html">Form Validation Class</a></li>' + '<li><a href="'+base+'libraries/ftp.html">FTP Class</a></li>' + '<li><a href="'+base+'libraries/table.html">HTML Table Class</a></li>' + '<li><a href="'+base+'libraries/image_lib.html">Image Manipulation Class</a></li>' + '<li><a href="'+base+'libraries/input.html">Input Class</a></li>' + '<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' + '<li><a href="'+base+'libraries/loader.html">Loader Class</a></li>' + '<li><a href="'+base+'libraries/language.html">Language Class</a></li>' + '<li><a href="'+base+'libraries/output.html">Output Class</a></li>' + '<li><a href="'+base+'libraries/pagination.html">Pagination Class</a></li>' + '<li><a href="'+base+'libraries/security.html">Security Class</a></li>' + '<li><a href="'+base+'libraries/sessions.html">Session Class</a></li>' + '<li><a href="'+base+'libraries/trackback.html">Trackback Class</a></li>' + '<li><a href="'+base+'libraries/parser.html">Template Parser Class</a></li>' + '<li><a href="'+base+'libraries/typography.html">Typography Class</a></li>' + '<li><a href="'+base+'libraries/unit_testing.html">Unit Testing Class</a></li>' + '<li><a href="'+base+'libraries/uri.html">URI Class</a></li>' + '<li><a href="'+base+'libraries/user_agent.html">User Agent Class</a></li>' + '<li><a href="'+base+'libraries/xmlrpc.html">XML-RPC Class</a></li>' + '<li><a href="'+base+'libraries/zip.html">Zip Encoding Class</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>Driver Reference</h3>' + '<ul>' + '<li><a href="'+base+'libraries/caching.html">Caching Class</a></li>' + '<li><a href="'+base+'database/index.html">Database Class</a></li>' + '<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' + '</ul>' + '<h3>Helper Reference</h3>' + '<ul>' + '<li><a href="'+base+'helpers/array_helper.html">Array Helper</a></li>' + '<li><a href="'+base+'helpers/captcha_helper.html">CAPTCHA Helper</a></li>' + '<li><a href="'+base+'helpers/cookie_helper.html">Cookie Helper</a></li>' + '<li><a href="'+base+'helpers/date_helper.html">Date Helper</a></li>' + '<li><a href="'+base+'helpers/directory_helper.html">Directory Helper</a></li>' + '<li><a href="'+base+'helpers/download_helper.html">Download Helper</a></li>' + '<li><a href="'+base+'helpers/email_helper.html">Email Helper</a></li>' + '<li><a href="'+base+'helpers/file_helper.html">File Helper</a></li>' + '<li><a href="'+base+'helpers/form_helper.html">Form Helper</a></li>' + '<li><a href="'+base+'helpers/html_helper.html">HTML Helper</a></li>' + '<li><a href="'+base+'helpers/inflector_helper.html">Inflector Helper</a></li>' + '<li><a href="'+base+'helpers/language_helper.html">Language Helper</a></li>' + '<li><a href="'+base+'helpers/number_helper.html">Number Helper</a></li>' + '<li><a href="'+base+'helpers/path_helper.html">Path Helper</a></li>' + '<li><a href="'+base+'helpers/security_helper.html">Security Helper</a></li>' + '<li><a href="'+base+'helpers/smiley_helper.html">Smiley Helper</a></li>' + '<li><a href="'+base+'helpers/string_helper.html">String Helper</a></li>' + '<li><a href="'+base+'helpers/text_helper.html">Text Helper</a></li>' + '<li><a href="'+base+'helpers/typography_helper.html">Typography Helper</a></li>' + '<li><a href="'+base+'helpers/url_helper.html">URL Helper</a></li>' + '<li><a href="'+base+'helpers/xml_helper.html">XML Helper</a></li>' + '</ul>' + '</td></tr></table>'); }
JavaScript
/* moo.fx, simple effects library built with prototype.js (http://prototype.conio.net). by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE. for more info (http://moofx.mad4milk.net). 10/24/2005 v(1.0.2) */ //base var fx = new Object(); fx.Base = function(){}; fx.Base.prototype = { setOptions: function(options) { this.options = { duration: 500, onComplete: '' } Object.extend(this.options, options || {}); }, go: function() { this.duration = this.options.duration; this.startTime = (new Date).getTime(); this.timer = setInterval (this.step.bind(this), 13); }, step: function() { var time = (new Date).getTime(); var Tpos = (time - this.startTime) / (this.duration); if (time >= this.duration+this.startTime) { this.now = this.to; clearInterval (this.timer); this.timer = null; if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10); } else { this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from; //this time-position, sinoidal transition thing is from script.aculo.us } this.increase(); }, custom: function(from, to) { if (this.timer != null) return; this.from = from; this.to = to; this.go(); }, hide: function() { this.now = 0; this.increase(); }, clearTimer: function() { clearInterval(this.timer); this.timer = null; } } //stretchers fx.Layout = Class.create(); fx.Layout.prototype = Object.extend(new fx.Base(), { initialize: function(el, options) { this.el = $(el); this.el.style.overflow = "hidden"; this.el.iniWidth = this.el.offsetWidth; this.el.iniHeight = this.el.offsetHeight; this.setOptions(options); } }); fx.Height = Class.create(); Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), { increase: function() { this.el.style.height = this.now + "px"; }, toggle: function() { if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0); else this.custom(0, this.el.scrollHeight); } });
JavaScript
window.onload = function() { myHeight = new fx.Height('nav', {duration: 400}); myHeight.hide(); }
JavaScript
$(document).ready(function() { $("#newFortune").click(function() { $("#content").hide(); $("#content").fadeIn(); }); $(function() { $('.tooltip').tooltip({ track: true, delay: 0, showURL: false, showBody: " - ", fade: 250 }); }); $(function() { $('.tooltip_info').tooltip({ delay: 0, showURL: false, showBody: " - ", fade: 250 }); }); });
JavaScript
(function ($) { var daysInWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var shortMonthsInYear = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var longMonthsInYear = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var shortMonthsToNumber = []; shortMonthsToNumber["Jan"] = "01"; shortMonthsToNumber["Feb"] = "02"; shortMonthsToNumber["Mar"] = "03"; shortMonthsToNumber["Apr"] = "04"; shortMonthsToNumber["May"] = "05"; shortMonthsToNumber["Jun"] = "06"; shortMonthsToNumber["Jul"] = "07"; shortMonthsToNumber["Aug"] = "08"; shortMonthsToNumber["Sep"] = "09"; shortMonthsToNumber["Oct"] = "10"; shortMonthsToNumber["Nov"] = "11"; shortMonthsToNumber["Dec"] = "12"; $.format = (function () { function strDay(value) { return daysInWeek[parseInt(value, 10)] || value; } function strMonth(value) { var monthArrayIndex = parseInt(value, 10) - 1; return shortMonthsInYear[monthArrayIndex] || value; } function strLongMonth(value) { var monthArrayIndex = parseInt(value, 10) - 1; return longMonthsInYear[monthArrayIndex] || value; } var parseMonth = function (value) { return shortMonthsToNumber[value] || value; }; var parseTime = function (value) { var retValue = value; var millis = ""; if (retValue.indexOf(".") !== -1) { var delimited = retValue.split('.'); retValue = delimited[0]; millis = delimited[1]; } var values3 = retValue.split(":"); if (values3.length === 3) { hour = values3[0]; minute = values3[1]; second = values3[2]; return { time: retValue, hour: hour, minute: minute, second: second, millis: millis }; } else { return { time: "", hour: "", minute: "", second: "", millis: "" }; } }; return { date: function (value, format) { /* value = new java.util.Date() 2009-12-18 10:54:50.546 */ try { var date = null; var year = null; var month = null; var dayOfMonth = null; var dayOfWeek = null; var time = null; if (typeof value.getFullYear === "function") { year = value.getFullYear(); month = value.getMonth() + 1; dayOfMonth = value.getDate(); dayOfWeek = value.getDay(); time = parseTime(value.toTimeString()); } else if (value.search(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.?\d{0,3}[-+]?\d{2}:\d{2}/) != -1) { /* 2009-04-19T16:11:05+02:00 */ var values = value.split(/[T\+-]/); year = values[0]; month = values[1]; dayOfMonth = values[2]; time = parseTime(values[3].split(".")[0]); date = new Date(year, month - 1, dayOfMonth); dayOfWeek = date.getDay(); } else { var values = value.split(" "); switch (values.length) { case 6: /* Wed Jan 13 10:43:41 CET 2010 */ year = values[5]; month = parseMonth(values[1]); dayOfMonth = values[2]; time = parseTime(values[3]); date = new Date(year, month - 1, dayOfMonth); dayOfWeek = date.getDay(); break; case 2: /* 2009-12-18 10:54:50.546 */ var values2 = values[0].split("-"); year = values2[0]; month = values2[1]; dayOfMonth = values2[2]; time = parseTime(values[1]); date = new Date(year, month - 1, dayOfMonth); dayOfWeek = date.getDay(); break; case 7: /* Tue Mar 01 2011 12:01:42 GMT-0800 (PST) */ case 9: /*added by Larry, for Fri Apr 08 2011 00:00:00 GMT+0800 (China Standard Time) */ case 10: /* added by Larry, for Fri Apr 08 2011 00:00:00 GMT+0200 (W. Europe Daylight Time) */ year = values[3]; month = parseMonth(values[1]); dayOfMonth = values[2]; time = parseTime(values[4]); date = new Date(year, month - 1, dayOfMonth); dayOfWeek = date.getDay(); break; default: return value; } } var pattern = ""; var retValue = ""; /* Issue 1 - variable scope issue in format.date Thanks jakemonO */ for (var i = 0; i < format.length; i++) { var currentPattern = format.charAt(i); pattern += currentPattern; switch (pattern) { case "ddd": retValue += strDay(dayOfWeek); pattern = ""; break; case "dd": if (format.charAt(i + 1) == "d") { break; } if (String(dayOfMonth).length === 1) { dayOfMonth = '0' + dayOfMonth; } retValue += dayOfMonth; pattern = ""; break; case "MMMM": retValue += strLongMonth(month); pattern = ""; break; case "MMM": if (format.charAt(i + 1) === "M") { break; } retValue += strMonth(month); pattern = ""; break; case "MM": if (format.charAt(i + 1) == "M") { break; } if (String(month).length === 1) { month = '0' + month; } retValue += month; pattern = ""; break; case "yyyy": retValue += year; pattern = ""; break; case "HH": retValue += time.hour; pattern = ""; break; case "hh": /* time.hour is "00" as string == is used instead of === */ retValue += (time.hour == 0 ? 12 : time.hour < 13 ? time.hour : time.hour - 12); pattern = ""; break; case "mm": retValue += time.minute; pattern = ""; break; case "ss": /* ensure only seconds are added to the return string */ retValue += time.second.substring(0, 2); pattern = ""; break; case "SSS": retValue += time.millis.substring(0, 3); pattern = ""; break; case "a": retValue += time.hour >= 12 ? "PM" : "AM"; pattern = ""; break; case " ": retValue += currentPattern; pattern = ""; break; case "/": retValue += currentPattern; pattern = ""; break; case ":": retValue += currentPattern; pattern = ""; break; default: if (pattern.length === 2 && pattern.indexOf("y") !== 0 && pattern != "SS") { retValue += pattern.substring(0, 1); pattern = pattern.substring(1, 2); } else if ((pattern.length === 3 && pattern.indexOf("yyy") === -1)) { pattern = ""; } } } return retValue; } catch (e) { console.log(e); return value; } } }; }()); }(jQuery)); $(document).ready(function () { $(".shortDateFormat").each(function (idx, elem) { if ($(elem).is(":input")) { $(elem).val($.format.date($(elem).val(), "dd/MM/yyyy")); } else { $(elem).text($.format.date($(elem).text(), "dd/MM/yyyy")); } }); $(".longDateFormat").each(function (idx, elem) { if ($(elem).is(":input")) { $(elem).val($.format.date($(elem).val(), "dd/MM/yyyy hh:mm:ss")); } else { $(elem).text($.format.date($(elem).text(), "dd/MM/yyyy hh:mm:ss")); } }); });
JavaScript
var tocRoot, tocBranch, tocSel, tocLoading, tocLastID, tableSel, tabHead, data, tocTab, tocInitRoot, tocMemToc, rFStatus, oldData, tableSelTable; var initI; var icon=new Array(); var preloadIcons=new Array(1,10,101,102,103,104,106,107,108,11,113,116,118,16,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,19,20,21,24,25,26,28,29,31,34,4,5,52,53,56,57,6,60,68,69,7,8,82,9,99); var browser=browserCheck(); var content=0; var Linkguid=""; function browserCheck() { browser=navigator.userAgent.toLowerCase(); if (browser.indexOf('msie')!=-1) { if(browser.substring(browser.indexOf('msie')+5,browser.indexOf('.',browser.indexOf('msie')))>6) return("ie7"); if(browser.substring(browser.indexOf('msie')+5,browser.indexOf('.',browser.indexOf('msie')))>5) return("ie6"); else return("ie_old"); } else if (browser.indexOf('firefox')!=-1) return("ff"); else if (browser.indexOf('opera')!=-1) return("op"); else if (browser.indexOf('gecko')!=-1) return("ff"); } function changeCSS(theClass,element,value,target) { var cssRules; target = eval(target+'.document.styleSheets'); if (browser=='ie6'||browser=='ie7') { cssRules = 'rules'; } else if (browser=='ff'||browser=='op') { cssRules = 'cssRules'; } for (var S = 0; S < target.length; S++){ for (var R = 0; R < target[S][cssRules].length; R++) { if (target[S][cssRules][R].selectorText == theClass) { try { target[S][cssRules][R].style[element] = value; } catch(e) {} } } } } function initItem(item) { tableSel=null; if (cont.document.getElementById('TableGroup')!=null) { toggleItem(cont.document.getElementById('TableGroup').getElementsByTagName('li')[0].id.replace("Title","")); } } function initLoad(src,toc,home) { var qs=document.location.search.substring(1); if (qs.substring(0,qs.indexOf('='))=='goto') { var gotoPage = qs.substring(qs.indexOf('=')+1).split(':'); var fExt = home.substring(home.lastIndexOf('.')); var home = "./EARoot/"; for (var i=0; i<gotoPage.length; i++) { home += "EA"+gotoPage[i]; if (i!=gotoPage.length-1) home += "/"; else home += fExt; } } content = document.createElement('div'); content.className = "IndexBody"; content.innerHTML=" <iframe src='"+toc+"' name='toc' id='tocIFrame' frameborder='0'></iframe>\n"; if (qs.substring(0,qs.indexOf('='))=='guid') { Linkguid = qs.substring(qs.indexOf('=')+1).split('?guid='); var sGuid = new String(Linkguid); if(sGuid.substring(0,1)=="{" && sGuid.substring(sGuid.length,sGuid.length-1)=="}") sGuid = sGuid.substring(1,sGuid.length-1); Linkguid = sGuid; LoadGuidMap(OnReadyLoadGuidMap); } else{ // We don't have a guid in the address bar, so set the default homepage and continue content.innerHTML+=" <iframe src='"+home+"' name='cont' id='contentIFrame' frameborder='0'></iframe>"; content.innerHTML+=" <div id=\"resizeFrames\"></div>"; // Pass in the guid of the home page or class. initPreLoad(content); } } function LoadGuidMap(ResponseFunc){ // Get the correct file var FirstTwoHexDigits = new String(Linkguid); FirstTwoHexDigits = FirstTwoHexDigits.slice(0,2).toLowerCase(); var src = "js/data/guidmaps/"+"GuidMap"+FirstTwoHexDigits+".xml"; RequestPage(src,ResponseFunc);// Request the page passing in the filelocation and the response function. } function OnReadyLoadGuidMap(){ if (data.readyState == 4){ try{ var Home = GetPageAddressFromMapString(data.responseText); //Set the home page. content.innerHTML+=" <iframe src='"+Home+"' name='cont' id='contentIFrame' frameborder='0'></iframe>"; content.innerHTML+=" <div id=\"resizeFrames\"></div>"; //Make sure memory for the string is cleared. The browser should do this anyway but just in case. Home=null; // Continue loading the rest of the page. initPreLoad(content); } catch(e){ return; } } } function GetPageAddressFromMapString(MapString) { var LG = new String(Linkguid); var Page = new String(MapString); LG = LG.toLowerCase(); //Make searching case insensitive. Page = Page.toLowerCase(); var Pos1 = Page.search(LG); // Search the the guid in the string and return the position. Page = Page.slice(Pos1);// Remove the top half of the string. var Pos2 = Page.search("/"); //Search for the start of the web address. var Pos3 = Page.search(";"); //Search for the end of the web address. Page = Page.slice(Pos2+1,Pos3); // extract the web address. // Leave the page address in the original case as Linux is case sensitive. var sExt = ".html"; Pos1 = Page.search(sExt); if(Pos1 == -1) { sExt = ".htm"; Pos1 = Page.search(sExt); } Page = Page.slice(0,Pos1); Page = Page.toUpperCase(); Page = "EARoot/" + Page + sExt; // At the root back onto the page. return Page; } function guidLink(guid,qs) { guid = guid.substring(1,guid.length-1); //Remove the brakets Linkguid = guid; LoadGuidMap(OnReadyGuidLink); } function OnReadyGuidLink(){ if (data.readyState == 4){ try{ // Get the page location from the guid map. var Page = GetPageAddressFromMapString(data.responseText); cont.location = Page; //Make sure memory for the string is cleared. The browser should do this anyway but just in case. Page=null; Linkguid=null; } catch(e){ return; } } } function RequestPage(Page,ResponseFunc) { try { data = new XMLHttpRequest(); data.onreadystatechange = ResponseFunc; data.open("GET", Page, true); data.send(null); } catch(e) { if (browser=="ie6"||browser=="ie7"||browser=="ie8"){ data = new ActiveXObject("Microsoft.XMLHTTP"); if (data) { data.onreadystatechange = ResponseFunc; data.open("GET", Page, true); data.send(); } } else{ alert(e); } } } function initPage(src) { if (browser=="ie_old") return; if (toc.document==null) toc=top.frames[0]; if (cont.document==null) cont=top.frames[1]; if (cont.document==null) { setTimeout("initPage('"+src+"')","1000"); return; } var curPage = cont.document.location+""; if (curPage.indexOf('EARoot')!=-1) curPage = curPage.substring(curPage.indexOf('EARoot')); else curPage = curPage.substring(curPage.lastIndexOf('/')+1); for (var j=0; j<cont.document.getElementsByTagName('div').length; j++) { if (cont.document.getElementsByTagName('div')[j].className=="ObjectDetailsNotes") { var tmpStr = cont.document.getElementsByTagName('div')[j].innerHTML; //tmpStr=tmpStr.replace(/&nbsp;<WBR>/g," "); //GAS 810 - removed as it adversely affect PreserveWS tmpStr=tmpStr.replace(/&gt;/g,">"); tmpStr=tmpStr.replace(/&lt;/g,"<"); cont.document.getElementsByTagName('div')[j].innerHTML=tmpStr; } } if (src!=null) initItem(); if(curPage.substr(0,curPage.indexOf('.'))=="blank") return; //Check ToC is loaded if (toc.document.body==null) { setTimeout("initPage('"+src+"')","1"); return; } else if (toc.document.body.childNodes && toc.document.body.childNodes.length==1) { setTimeout("initPage('"+src+"')","1"); return; } else if (toc.document.body.lastChild && toc.document.body.lastChild.childNodes && toc.document.body.lastChild.childNodes.length==0) { setTimeout("initPage('"+src+"')","1"); return; } else if (!toc.document.body.childNodes || !toc.document.body.lastChild || !toc.document.body.lastChild.childNodes) { setTimeout("initPage('"+src+"')","1"); return; } else { var parTree = curPage.substr(0,curPage.lastIndexOf('/')).substr(curPage.indexOf('/')+1).replace(/EA/g,"").replace(/\//g,"."); if (parTree) { if (parTree.indexOf('0')!=0) parTree = "0."+parTree; parTree=parTree.split('.'); var tocTmp; for (var j=0; parTree.length>j; j++) { if (j>=2) tocTmp += "."+parTree[j]; else tocTmp = parTree[j]; if (toc.document.getElementById('toc'+tocTmp)==null) { setTimeout("initPage('"+src+"')","1"); return; } var tmpCurToc = toc.document.getElementById('toc'+tocTmp).parentNode.childNodes; toc.tocMemToc = parTree.length-j; if (tmpCurToc.length>3&&tmpCurToc[tmpCurToc.length-4].src.substring(tmpCurToc[tmpCurToc.length-4].src.lastIndexOf('images')).indexOf('plus')!=-1) { toc.tocClick(tmpCurToc[tmpCurToc.length-4]); } } } if (toc.document.getElementById(curPage)==null) { setTimeout("initPage('"+src+"')","1"); return; } if (toc.document.getElementById(curPage).parentNode.parentNode.parentNode.parentNode&&toc.document.getElementById(curPage).parentNode.parentNode.parentNode.parentNode.childNodes.length>3) { if (toc.document.getElementById(curPage).parentNode.parentNode.parentNode.parentNode.childNodes[toc.document.getElementById(curPage).parentNode.parentNode.parentNode.parentNode.childNodes.length-4].src.indexOf('plus')!=-1) { toc.tocClick(toc.document.getElementById(curPage).parentNode.parentNode.parentNode.parentNode.childNodes[toc.document.getElementById(curPage).parentNode.parentNode.parentNode.parentNode.childNodes.length-4]); } } if (toc.document.getElementById(curPage).parentNode.parentNode.childNodes[toc.document.getElementById(curPage).parentNode.parentNode.childNodes.length-4].src.indexOf('plus')!=-1) { toc.tocClick(toc.document.getElementById(curPage).parentNode.parentNode.childNodes[toc.document.getElementById(curPage).parentNode.parentNode.childNodes.length-4]); } if (tocSel) tocSel.parentNode.childNodes[tocSel.parentNode.childNodes.length-2].style.backgroundColor = ""; //Highlight selected ToC item and store in memory if (toc.document.getElementById(curPage)) { tocSel = toc.document.getElementById(curPage).parentNode; tocSel.parentNode.childNodes[tocSel.parentNode.childNodes.length-2].style.backgroundColor = "#B2B4BF"; if (tocSel.offsetTop<toc.document.body.scrollTop||tocSel.offsetTop>toc.document.body.offsetHeight+toc.document.body.scrollTop) { toc.scrollTo(0, tocSel.offsetTop-20); } } } } function initPreLoad(content) { var preload=document.getElementById('IndexHeader').parentNode.insertBefore(document.createElement('div'), document.getElementById('IndexHeader').nextSibling); preload.id="Preload"; preload.appendChild(document.createElement('p')); preload.firstChild.appendChild(document.createTextNode("Loading...")); if (browser=="ie_old") return; if (browser=="ie6"||browser=="ie7") changeCSS('#Preload','height',top.document.body.clientHeight-67+'px','this'); else changeCSS('#Preload','height',top.innerHeight-67+'px','this'); for (var i=0; i<preloadIcons.length; i++) { icon[preloadIcons[i]]=new Image(); icon[preloadIcons[i]].src="images/"+preloadIcons[i]+".png"; } var preloader = document.body.appendChild(document.createElement('div')); preloader.style.display="none"; preloader.id="preloader"; preloader.appendChild(content); resizeFrames('init'); } function initPreLoaded() { if (browser=="op") setCSS(); var preloader = document.getElementById('preloader'); document.getElementById('Preload').parentNode.replaceChild(preloader.firstChild, document.getElementById('Preload')); preloader.parentNode.removeChild(preloader); if (browser!="op") setTimeout('setCSS();','1000'); } function resizeFrames(str) { var resizeFrames = document.getElementById('resizeFrames'); if (str=="init") { resizeFrames.onmousedown = resizeFramesOn; resizeFrames.onmouseup = resizeFramesOff; resizeFrames.onmouseout = resizeFramesOff; resizeFrames.onmousemove = resizeFramesMove; } } function resizeFramesOn(e) { rFStatus=1; var resizeFrames = document.getElementById('resizeFrames'); tmpRF = resizeFrames.parentNode.appendChild(document.createElement('div')); tmpRF.style.left=(document.getElementById('tocIFrame').clientWidth+1)+"px"; tmpRF.id="tmpRF"; resizeFrames.style.width="100%" resizeFrames.style.left="0px"; } function resizeFramesOff(e) { rFStatus=0; var resizeFrames = document.getElementById('resizeFrames'); if (document.getElementById('tmpRF')!=null) document.getElementById('tmpRF').parentNode.removeChild(document.getElementById('tmpRF')); resizeFrames.style.width="5px"; resizeFrames.style.left=(document.getElementById('tocIFrame').clientWidth+1)+"px"; } function resizeFramesMove(e) { if (rFStatus!=0) { if (rFStatus==2) var posX = e+2; else if (browser=="ff") var posX = e.pageX; else var posX = event.x; if (posX<=150) posX=150; else if (posX>=top.document.body.clientWidth/2) posX=top.document.body.clientWidth/2; document.getElementById('contentIFrame').style.left=(posX+3)+"px"; document.getElementById('contentIFrame').style.width=(top.document.body.clientWidth-posX-4)+"px"; if (document.getElementById('tmpRF')!=null) document.getElementById('tmpRF').style.left=(posX-2)+"px"; if (browser=="ie6") document.getElementById('tocIFrame').style.width=(posX-4)+"px"; else document.getElementById('tocIFrame').style.width=(posX-3)+"px"; if(tableSelTable!=null) { if(tableSelTable.childNodes.length>1&&document.getElementById('tmpRF')!=null) { tableSelTable.style.width=(document.body.clientWidth-(document.getElementById('tmpRF').offsetLeft+6)-20)+"px"; if(tableSelTable.childNodes[0].style) tableSelTable.childNodes[0].style.width=(tableSelTable.offsetWidth-19)+"px"; if(tableSelTable.childNodes[1].style) tableSelTable.childNodes[1].style.width=(tableSelTable.offsetWidth-19)+"px"; } } } } function resizePage() { if(rFStatus==1) return; rFStatus=2; if(document.getElementById('resizeFrames')==null) return; if (browser=="ie6") { pHeight=top.document.body.clientHeight; } else { pHeight=top.document.documentElement.clientHeight; } resizeFramesMove(document.getElementById('resizeFrames').offsetLeft); document.getElementById('contentIFrame').style.height=pHeight-74+'px'; if (browser=="ie7") { document.getElementById('resizeFrames').style.height=pHeight-72+'px'; changeCSS('#tmpRF','height',pHeight-72+'px','this'); } else { document.getElementById('resizeFrames').style.height=pHeight-70+'px'; changeCSS('#tmpRF','height',pHeight-70+'px','this'); } document.getElementById('tocIFrame').style.height=pHeight-74+'px'; rFStatus=0; } function setCSS() { if (browser=="ie6") { pHeight=top.document.body.clientHeight; } else { pHeight=top.document.documentElement.clientHeight; } if (browser=="ie6"||browser=="ie7") { changeCSS('.IndexBody','width','','this'); changeCSS('.IndexBody','top','0px','this'); changeCSS('.IndexBody','position','relative','this'); changeCSS('#contentIFrame','height',pHeight-74+'px','this'); changeCSS('#contentIFrame','left','257px','this'); changeCSS('#resizeFrames','background','#000000','this'); changeCSS('#resizeFrames','filter','progid:DXImageTransform.Microsoft.Alpha(opacity=0)','this'); changeCSS('#resizeFrames','height',pHeight-72+'px','this'); changeCSS('#tmpRF','border','0px','this'); changeCSS('#tmpRF','height',pHeight-70+'px','this'); changeCSS('#tocIFrame','height',pHeight-74+'px','this'); } changeCSS('#contentIFrame','width',top.document.body.clientWidth-258+'px','this'); } function tocBuild(data) { var tocType = new Array(); var tocTypes = new Array(); var tocErrs = new Array(); for (var i=0; i<tocTab.length; i++) { if (!tocTab[i][8]) tocTab[i][8] = 'misc'; if (tocTab[i][8].toLowerCase().indexOf('diagram')!=-1 && (tocTab[i][6]=="" || tocTab[i][6]=="0")) tocTab[i][8] = "0Diagram"; if (tocTab[i][8].toLowerCase().indexOf('package')!=-1) tocTab[i][8] = "1Package"; if (!tocType[tocTab[i][8]]) { tocType[tocTab[i][8]] = new Array(); tocTypes[tocTypes.length]=tocTab[i][8]; } tocType[tocTab[i][8]][tocType[tocTab[i][8]].length] = i; } tocTypes.sort(); for (var i=0; i<tocTypes.length; i++) { for (var j=0; j<tocType[tocTypes[i]].length; j++) { var build = tocBuildItem(tocType[tocTypes[i]][j]); if (build!=true) { build = build.substring(1); tocErrs[tocErrs.length]=build; } } } var errRuns=0; var errTotal=tocErrs.length; while(tocErrs.length!=0) { if (errNums==tocErrs.length) { errRuns++; if (errRuns>errTotal) { break; } } var errNums=tocErrs.length; var tmp=tocBuildItem(tocErrs.shift()); if(tmp!=true) { tocErrs[tocErrs.length]=tmp.substring(1); } } while(tocErrs.length!=0) { tocTab[tocErrs[0]][6]="0"; tocBuildItem(tocErrs.shift()); } if (tocLastID!=0) { var tocLastSrc = document.getElementById("toc"+tocLastID).parentNode.childNodes[document.getElementById("toc"+tocLastID).parentNode.childNodes.length-4]; tocLastSrc.src = tocLastSrc.src.substring(tocLastSrc.src.lastIndexOf('images')).replace("01","02"); } } function tocBuildItem(i) { var childItem = false; if (tocTab[i][0].indexOf(':')!=-1) tocBranch = document.getElementById("toc"+tocTab[i][0].substring(0, tocTab[i][0].lastIndexOf(':'))); else if (tocTab[i][0].indexOf('.')!=-1) tocBranch = document.getElementById("toc"+tocTab[i][0].substring(0, tocTab[i][0].lastIndexOf('.'))); else if (tocTab[i][0]!="0") tocBranch = document.getElementById("toc0"); else if (tocTab[i][1]==3) tocBranch = document.getElementById("System").parentNode.lastChild; else tocBranch = tocRoot; //Check if item is child if (tocTab[i][5]&&tocTab[i][6]&&tocTab[i][6]!="0") { if (document.getElementById(tocTab[i][6])==null) return 'i'+i; tocBranch = document.getElementById(tocTab[i][6]).parentNode.lastChild; childItem = true; } tocBranch = tocBranch.appendChild(document.createElement('li')); if (tocTab[i][0]!=0||tocTab[i][1]==3) { tocImage = tocBranch.appendChild(document.createElement('img')); if (tocTab[i][0].indexOf('.')==-1&&(tocTab[i][0].indexOf(':')==-1||tocTab[i][0].indexOf('0')==0)) tocImage.src = "images/join01.gif"; else if (tocTab[i][0].indexOf('.')!=-1||tocTab[i][0].indexOf(':')!=-1) { var tocTmp=tocTab[i][0].replace(':','.'); for (var m=0; tocTmp.split('.').length>m+1; m++) { if (document.getElementById("toc"+tocTmp.substring(0,tocTmp.lastIndexOf('.'))).parentNode.childNodes[m].src.substring(document.getElementById("toc"+tocTmp.substring(0,tocTmp.lastIndexOf('.'))).parentNode.childNodes[m].src.lastIndexOf('images')).indexOf('02')!=-1||document.getElementById("toc"+tocTmp.substring(0,tocTmp.lastIndexOf('.'))).parentNode.childNodes[m].src.substring(document.getElementById("toc"+tocTmp.substring(0,tocTmp.lastIndexOf('.'))).parentNode.childNodes[m].src.lastIndexOf('images')).indexOf('04')!=-1) tocImage.src = "images/join04.gif"; else tocImage.src = "images/join03.gif"; tocImage = tocBranch.appendChild(document.createElement('img')); } tocImage.src = "images/join01.gif"; } tocImage.onclick = function() { tocClick(this); } if (tocTab[i][1]==3) { tocImage.src=tocImage.src.substring(tocImage.src.lastIndexOf('images')).replace("01","02"); if (tocImage.parentNode.parentNode.childNodes.length>1) { tocTmp = tocImage.parentNode.previousSibling.childNodes[tocImage.parentNode.previousSibling.childNodes.length-4]; tocTmp.src=tocTmp.src.substring(tocTmp.src.lastIndexOf('images')).replace("02","01"); } } //Check if item has children data if (tocTab[i][1]&&tocTab[i][1]!=3) { tocImage.id=tocTab[i][7]; tocImage.alt=tocTab[i][7]; } else if (childItem==true) { while (tocImage.parentNode.childNodes.length<document.getElementById(tocTab[i][6]).parentNode.childNodes.length-2) { tocImage.parentNode.insertBefore(document.createElement('img'), tocImage).src="images/join03.gif"; } tocImage.src=tocImage.src.substring(tocImage.src.lastIndexOf("images")).replace('01','02'); if (document.getElementById(tocTab[i][6]).parentNode.lastChild.childNodes.length>1) { tocTmpSrc=document.getElementById(tocTab[i][6]).parentNode.lastChild.lastChild.previousSibling.childNodes[document.getElementById(tocTab[i][6]).parentNode.lastChild.lastChild.previousSibling.childNodes.length-4]; tocTmpSrc.src=tocTmpSrc.src.substring(tocTmpSrc.src.lastIndexOf('images')).replace('02','01'); } tocImage = document.getElementById(tocTab[i][6]).parentNode.childNodes[document.getElementById(tocTab[i][6]).parentNode.childNodes.length-4]; tocImage.parentNode.lastChild.style.display = "none"; } if ((tocTab[i][1]&&tocTab[i][1]!=3)||childItem==true) { tocImage.id=tocImage.id.substr(1,tocImage.id.length-2); tocImage.src=tocImage.src.substring(tocImage.src.lastIndexOf('images')).replace('join','plus'); } } //Set Icon if (tocTab[i][3]) { tocImg = tocBranch.appendChild(document.createElement('a')); tocImg.href = tocTab[i][3]; tocImg.target = top.frames[1].name; } else tocImg = tocBranch; tocTab[i][4]=tocTab[i][4].substring(0,tocTab[i][4].indexOf('.')) tocImg = tocImg.appendChild(document.createElement('img')); if(top.icon[tocTab[i][4]]) tocImg.src = top.icon[tocTab[i][4]].src; else tocImg.src = "images/"+tocTab[i][4]+".png"; if (tocTab[i][3]) tocImg.id=tocTab[i][3]; //Set Text/Link if (tocTab[i][5]&&tocTab[i][8]!="0Diagram") tocBranch.lastChild.id=tocTab[i][5]; else tocBranch.lastChild.id="0"; tocBranch.lastChild.style.marginRight="4px"; if (tocTab[i][3]) { tocText = tocBranch.appendChild(document.createElement('a')); tocText.href = tocTab[i][3]; tocText.target = top.frames[1].name; if (tocTab[i][9]) tocText.id = tocTab[i][9]; else if (tocTab[i][7]) tocText.id = tocTab[i][7]; } else tocText = tocBranch; var j=0; var nodeText; //Replace values while (tocTab[i][2].indexOf('&quot;')!=-1) tocTab[i][2] = tocTab[i][2].replace('&quot;','\"'); while (tocTab[i][2].indexOf('<br />')!=-1) tocTab[i][2] = tocTab[i][2].replace('<br />','\n'); while (tocTab[i][2].indexOf('&#39;')!=-1) tocTab[i][2] = tocTab[i][2].replace('&#39;','\''); if (tocTab[i][2]=="") tocTab[i][2]=" "; nodeText = tocText.appendChild(document.createTextNode(tocTab[i][2])); while (nodeText.nodeValue.indexOf('&lt;')!=-1) nodeText.nodeValue = nodeText.nodeValue.replace('&lt;','<'); while (nodeText.nodeValue.indexOf('&gt;')!=-1) nodeText.nodeValue = nodeText.nodeValue.replace('&gt;','>'); tocBranch.appendChild(document.createElement('ul')).id = "toc"+tocTab[i][0]; tocLastID = tocTab[i][0]; return true; } function tocClick(tocSrc) { if (tocSrc.src.substring(tocSrc.src.lastIndexOf('images')).indexOf('minus')!=-1) { tocSrc.parentNode.childNodes[tocSrc.parentNode.childNodes.length-1].style.display = "none"; tocSrc.src=tocSrc.src.substring(tocSrc.src.lastIndexOf('images')).replace('minus','plus'); } else if (tocSrc.src.substring(tocSrc.src.lastIndexOf('images')).indexOf('plus')!=-1) { tocSrc.parentNode.childNodes[tocSrc.parentNode.childNodes.length-1].style.display = "block"; tocSrc.src=tocSrc.src.substring(tocSrc.src.lastIndexOf('images')).replace('plus','minus'); //Check if children data built if (tocSrc.parentNode.childNodes[tocSrc.parentNode.childNodes.length-1].childNodes.length==0) { tocLoadData(tocSrc.id+".xml"); } } } function tocInit() { if (browser=="ie_old") { top.document.getElementById('Preload').childNodes[0].innerHTML="<strong>It appears you are using an outdated version of Internet Explorer, please download a later version from <a href=\"http://www.microsoft.com/windows/ie/default.mspx\">Microsoft</a></strong>"; return; } tocLoading = document.body.appendChild(document.createElement('div')); tocRoot = document.body.appendChild(document.createElement('ul')); tocRoot.id = "tocRoot"; tocInitRoot = 1; tocLoadData('root.xml'); } function tocLoadData(src) { var tmp=document.location+""; tmp=tmp.substring(0,tmp.indexOf('toc.')); src = tmp+"js/data/"+src; tocTab = new Array(); RequestPage(src,tocLoadDataProcess); } function tocLoadDataProcess() { if (data.readyState == 4) { if (oldData==data) return; oldData=data; try { eval(data.responseText); tocBuild(); tocInitRoot++; if (tocInitRoot==2) { tocLoadData(tocTab[0][7].substring(1,tocTab[0][7].length-1)+".xml"); } else if (tocInitRoot==3&&top.document.getElementById('Preload')!=null) { tocInitRoot=0; top.initPreLoaded(); } } catch(e) { if(top.document.getElementById('Preload')!=null) top.document.getElementById('Preload').childNodes[0].innerHTML="<strong>An error occured while loading data files, please confirm that all files have been generated and are intact.</strong>"; return; } } } function toggleDiv(idDiv,idImage){ var ele = cont.document.getElementById(idDiv); if(ele && ele.style.display == "none"){ ele.style.display = "block"; cont.document.getElementById(idImage).src=cont.document.getElementById(idImage).src.substring(0,cont.document.getElementById(idImage).src.lastIndexOf('images'))+cont.document.getElementById(idImage).src.substring(cont.document.getElementById(idImage).src.lastIndexOf('images')).replace('plus','minus'); } else if(ele){ ele.style.display = "none"; cont.document.getElementById(idImage).src=cont.document.getElementById(idImage).src.substring(0,cont.document.getElementById(idImage).src.lastIndexOf('images'))+cont.document.getElementById(idImage).src.substring(cont.document.getElementById(idImage).src.lastIndexOf('images')).replace('minus','plus'); } } function toggleData(src) { var dataRoot = cont.document.getElementById(src).parentNode.parentNode.parentNode; if (cont.document.getElementById(src).src.substring(cont.document.getElementById(src).src.lastIndexOf('images')).indexOf('plus')!=-1) cont.document.getElementById(src).src=cont.document.getElementById(src).src.substring(0,cont.document.getElementById(src).src.lastIndexOf('images'))+cont.document.getElementById(src).src.substring(cont.document.getElementById(src).src.lastIndexOf('images')).replace('plus','minus'); else cont.document.getElementById(src).src=cont.document.getElementById(src).src.substring(0,cont.document.getElementById(src).src.lastIndexOf('images'))+cont.document.getElementById(src).src.substring(cont.document.getElementById(src).src.lastIndexOf('images')).replace('minus','plus'); for (var i=0; i<dataRoot.getElementsByTagName('tr').length; i++) { if (dataRoot.getElementsByTagName('tr')[i].id.indexOf(src)!=-1&&cont.document.getElementById(src).src.substring(cont.document.getElementById(src).src.lastIndexOf('images')).indexOf('minus')!=-1&&dataRoot.getElementsByTagName('tr')[i].getElementsByTagName('td')[1].firstChild!=null) dataRoot.getElementsByTagName('tr')[i].style.display=""; else if (dataRoot.getElementsByTagName('tr')[i].id.indexOf(src)!=-1) dataRoot.getElementsByTagName('tr')[i].style.display="none"; } if (cont.document.getElementById('TableGroup')!=null) { toggleItem(tableSel,2); } } function toggleItem(item,type) { if (tableSel!=null) { cont.document.getElementById(tableSel+"Title").style.background="#FFFFFF"; cont.document.getElementById(tableSel+"Title").style.color="#000000"; cont.document.getElementById(tableSel+"Table").style.display="none"; } tableSel=item; tableSelTable = cont.document.getElementById(item+"Table"); tableSelTitle = cont.document.getElementById(item+"Title"); tableSelTitle.style.background="#DDDDDD"; tableSelTitle.style.color="#666666"; tableSelTable.style.display="block"; if (browser=="ff"||browser=="op"||browser=="ie7") { var contWHeight = document.documentElement.clientHeight-78; var contWWidth = cont.document.documentElement.clientWidth; } else { var contWHeight = document.body.clientHeight-74; var contWWidth = document.body.clientWidth-(top.document.getElementById('resizeFrames').offsetLeft+6); } if (tableSelTable.id=="LinkedDocumentTable") tableSelTable.style.overflow="scroll"; if (cont.document.body.offsetHeight-contWHeight>0) { if (tableSelTable.id!="LinkedDocumentTable") tableSelTable.style.overflow="scroll"; if (browser=="ff"||browser=="op") { tableSelTable.style.height=tableSelTable.offsetHeight-(cont.document.body.offsetHeight-cont.innerHeight)-12+"px"; } else { tableSelTable.style.height=tableSelTable.offsetHeight-(cont.document.body.offsetHeight-contWHeight)-3+"px"; if (cont.document.body.offsetWidth>contWWidth||type==null) { tableSelTable.style.width=contWWidth-20+"px"; if(tableSelTable.getElementsByTagName('table').length!=0) tableSelTable.getElementsByTagName('table')[0].style.width=tableSelTable.getElementsByTagName('table')[0].offsetWidth-18+"px"; } } if(tableSelTable.getElementsByTagName('table').length!=0) { tabHead = tableSelTable.appendChild(tableSelTable.getElementsByTagName('table')[0].cloneNode(true)); tabHead.style.position="absolute"; if (browser=="ff"||browser=="op") tabHead.style.width=tableSelTable.offsetWidth+"px"; tabHead.style.top=tableSelTable.offsetTop+1+"px"; for (var i=0; i<tabHead.getElementsByTagName('tr').length; i++) { if (i!=0) tabHead.getElementsByTagName('tr')[i].style.display="none"; } } } else if (cont.document.getElementById('TableGroup').offsetHeight+cont.document.getElementById('TableGroup').offsetTop<(contWHeight-6)&&tableSelTable.style.overflow=="scroll") { if (browser=="ff"||browser=="op") { tableSelTable.style.height=tableSelTable.offsetHeight-(cont.document.body.offsetHeight-cont.innerHeight)-12+"px"; } else { tableSelTable.style.height=tableSelTable.offsetHeight+((contWHeight-8)-(cont.document.getElementById('TableGroup').offsetHeight+cont.document.getElementById('TableGroup').offsetTop))+"px"; } } if(tableSelTable.childNodes.length>1) { tableSelTable.style.width=(document.body.clientWidth-(top.document.getElementById('resizeFrames').offsetLeft+6)-20)+"px"; if(tableSelTable.childNodes[0].style) tableSelTable.childNodes[0].style.width=(tableSelTable.offsetWidth-19)+"px"; if(tableSelTable.childNodes[1].style) tableSelTable.childNodes[1].style.width=(tableSelTable.offsetWidth-19)+"px"; } }
JavaScript
// ==UserScript== // @name Optimize userscripts.org for mobile screen // @description Hide right-hand navigation bar on userscripts.org to optimize for mobile screens // @author Jeffrey Sharkey // @include http://*userscripts.org* // ==/UserScript== function hideById(id) { var target = document.getElementById(id); if(target == null) return; target.style.display = 'none'; } function flattenById(id) { var target = document.getElementById(id); if(target == null) return; target.style.padding = '0px'; target.style.margin = '0px'; } flattenById('content'); hideById('right'); document.body.style.background = "#ffffff";
JavaScript
// ==UserScript== // @name Pick E-mail address // @description Fill forms by picking an E-mail address from Android contacts // @author Jeffrey Sharkey // @include http://*digg.com/register* // @include http://*facebook.com* // @include http://*m.yahoo.com/p/mail/compose* // @include http://*m.half.com* // ==/UserScript== function insertAfter(newElement,targetElement) { var parent = targetElement.parentNode; if(parent.lastchild == targetElement) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } } function generate(item) { var helper = document.createElement('input'); helper.type = 'button'; helper.value = 'Pick Android contact...'; helper.style.background = '#cfc'; helper.style.color = '#484'; helper.style.border = '1px solid #484'; helper.style.padding = '5px'; helper.style.marginLeft = '10px'; helper.addEventListener('click', function(event) { var result = window.intentHelper.startActivityForResult(JSON.stringify({ action:'ACTION_GET_CONTENT', type:'vnd.android.cursor.item/email' })); result = JSON.parse(result); item.value = result['data']['data']; }, false); return helper; } var append = []; var items = document.body.getElementsByTagName('input'); for(i in items) { var item = items[i]; var digg = (item.name == 'email' || item.name == 'emailverify'); var facebook = (item.name == 'reg_email__'); var yahoo = (item.className == 'd' && (item.name.substr(0,2) == 'to' || item.name.substr(0,2) == 'cc')); var half = (item.name == 'email'); if(digg || facebook || yahoo || half) append.push([item,generate(item)]); } for(i in append) { var target = append[i][0]; var generated = append[i][1]; insertAfter(generated, target); }
JavaScript
// ==UserScript== // @name Scan barcode into Half.com // @description Add button to Half.com search box to scan barcode // @author Jeffrey Sharkey // @include http://*m.half.com* // ==/UserScript== function insertAfter(newElement,targetElement) { var parent = targetElement.parentNode; if(parent.lastchild == targetElement) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } } function generate(item) { var helper = document.createElement('input'); helper.type = 'button'; helper.value = 'Scan barcode...'; helper.style.background = '#cfc'; helper.style.color = '#484'; helper.style.border = '1px solid #484'; helper.style.padding = '5px'; helper.style.marginLeft = '10px'; helper.addEventListener('click', function(event) { var result = window.intentHelper.startActivityForResult(JSON.stringify({ action:'com.google.zxing.client.android.SCAN', category:['CATEGORY_DEFAULT'] })); result = JSON.parse(result); item.value = result['extras']['SCAN_RESULT']; }, false); return helper; } var append = []; var items = document.body.getElementsByTagName('input'); for(i in items) { var item = items[i]; if(item.name == 'query') append.push([item,generate(item)]); } for(i in append) { var target = append[i][0]; var generated = append[i][1]; insertAfter(generated, target); }
JavaScript
// ==UserScript== // @name Optimize Slashdot for mobile screen // @description Hide navigation bars on Slashdot to optimize for mobile screens // @author Jeffrey Sharkey // @include http://*slashdot.org* // ==/UserScript== function hideById(id) { var target = document.getElementById(id); if(target == null) return; target.style.display = 'none'; } function flattenById(id) { var target = document.getElementById(id); if(target == null) return; target.style.padding = '0px'; target.style.margin = '0px'; } function flattenByClass(parent, tag, className) { var items = parent.getElementsByTagName(tag); for(i in items) { var item = items[i]; if(typeof item.className !== 'string') continue; if(item.className.indexOf(className) != -1) { item.style.padding = '0px'; item.style.margin = '0px'; } } } hideById('links'); hideById('fad1'); hideById('fad2'); hideById('fad3'); hideById('fad6'); hideById('fad30'); hideById('fad60'); hideById('slashboxes'); var yuimain = document.getElementById('yui-main'); flattenByClass(yuimain,'div','yui-b'); flattenByClass(yuimain,'div','maincol'); flattenByClass(yuimain,'div','article usermode thumbs'); // these usually only apply when logged in flattenById('contents'); flattenById('articles'); flattenById('indexhead');
JavaScript
// ==UserScript== // @name Share Digg story // @description One-click to share any Digg Mobile story through an E-mail // @author Jeffrey Sharkey // @include http://m.digg.com/* // ==/UserScript== function generate(item) { var header = item.getElementsByTagName('h3')[0]; var link = header.getElementsByTagName('a')[0]; var body = item.getElementsByTagName('p')[0]; var helper = document.createElement('input'); helper.type = 'button'; helper.value = 'Share in E-mail'; helper.style.background = '#cfc'; helper.style.color = '#484'; helper.style.border = '1px solid #484'; helper.style.padding = '5px'; helper.style.marginLeft = '10px'; helper.addEventListener('click', function(event) { window.intentHelper.startActivity(JSON.stringify({ action:'ACTION_SEND', type:'plain/html', 'EXTRA_SUBJECT':link.textContent, 'EXTRA_TEXT':link.href+'\n\n'+body.textContent })); }, false); return helper; } var items = document.body.getElementsByTagName('div'); for(i in items) { var item = items[i]; if(item.className == 'news-summary') item.appendChild(generate(item)); }
JavaScript
// ==UserScript== // @name Optimize Wikipedia and view coordinates in Maps and Radar // @description Hide navigation bars to optimize for mobile screens and link coordinates from articles to Maps and Radar apps. // @author Jeffrey Sharkey // @include http://*wikipedia.org/wiki/* // ==/UserScript== function hideByClass(tag, className) { var items = document.body.getElementsByTagName(tag); for(i in items) { var item = items[i]; if(typeof item.className !== 'string') continue; if(item.className.indexOf(className) != -1) item.style.display = 'none'; } } function hideById(id) { var target = document.getElementById(id); target.style.display = 'none'; } var content = document.getElementById('content'); content.style.padding = '0px'; content.style.margin = '0px'; hideByClass('table','ambox'); hideById('column-one'); hideById('siteNotice'); hideById('toc'); function getElementByClass(parent, tag, className) { var items = parent.getElementsByTagName(tag); var answer = []; for(i in items) { var item = items[i]; if(typeof item.className !== 'string') continue; if(item.className.indexOf(className) != -1) answer.push(item); } return answer; } function createButton(title) { var button = document.createElement('input'); button.type = 'button'; button.value = title; button.style.background = '#cfc'; button.style.color = '#484'; button.style.border = '1px solid #484'; button.style.padding = '5px'; button.style.marginLeft = '10px'; return button; } var coords = document.getElementById('coordinates'); var dec = getElementByClass(coords, 'span', 'geo-dec')[0]; var lat = parseFloat(getElementByClass(dec, 'span', 'latitude')[0].textContent); var lon = parseFloat(getElementByClass(dec, 'span', 'longitude')[0].textContent); coords.appendChild(document.createElement('br')); var maps = createButton('View in Maps'); maps.addEventListener('click', function(event) { window.intentHelper.startActivity(JSON.stringify({ action:'ACTION_VIEW', data:'geo:'+lat+','+lon+'?z=14' })); }, false); coords.appendChild(maps); var radar = createButton('Find using Radar'); radar.addEventListener('click', function(event) { window.intentHelper.startActivity(JSON.stringify({ action:'com.google.android.radar.SHOW_RADAR', category:['CATEGORY_DEFAULT'], 'latitude':lat, 'longitude':lon })); }, false); coords.appendChild(radar);
JavaScript
// ==UserScript== // @name Optimize userscripts.org for mobile screen // @description Hide right-hand navigation bar on userscripts.org to optimize for mobile screens // @author Jeffrey Sharkey // @include http://*userscripts.org* // ==/UserScript== function hideById(id) { var target = document.getElementById(id); if(target == null) return; target.style.display = 'none'; } function flattenById(id) { var target = document.getElementById(id); if(target == null) return; target.style.padding = '0px'; target.style.margin = '0px'; } flattenById('content'); hideById('right'); document.body.style.background = "#ffffff";
JavaScript
// ==UserScript== // @name Pick E-mail address // @description Fill forms by picking an E-mail address from Android contacts // @author Jeffrey Sharkey // @include http://*digg.com/register* // @include http://*facebook.com* // @include http://*m.yahoo.com/p/mail/compose* // @include http://*m.half.com* // ==/UserScript== function insertAfter(newElement,targetElement) { var parent = targetElement.parentNode; if(parent.lastchild == targetElement) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } } function generate(item) { var helper = document.createElement('input'); helper.type = 'button'; helper.value = 'Pick Android contact...'; helper.style.background = '#cfc'; helper.style.color = '#484'; helper.style.border = '1px solid #484'; helper.style.padding = '5px'; helper.style.marginLeft = '10px'; helper.addEventListener('click', function(event) { var result = window.intentHelper.startActivityForResult(JSON.stringify({ action:'ACTION_GET_CONTENT', type:'vnd.android.cursor.item/email' })); result = JSON.parse(result); item.value = result['data']['data']; }, false); return helper; } var append = []; var items = document.body.getElementsByTagName('input'); for(i in items) { var item = items[i]; var digg = (item.name == 'email' || item.name == 'emailverify'); var facebook = (item.name == 'reg_email__'); var yahoo = (item.className == 'd' && (item.name.substr(0,2) == 'to' || item.name.substr(0,2) == 'cc')); var half = (item.name == 'email'); if(digg || facebook || yahoo || half) append.push([item,generate(item)]); } for(i in append) { var target = append[i][0]; var generated = append[i][1]; insertAfter(generated, target); }
JavaScript
// ==UserScript== // @name Scan barcode into Half.com // @description Add button to Half.com search box to scan barcode // @author Jeffrey Sharkey // @include http://*m.half.com* // ==/UserScript== function insertAfter(newElement,targetElement) { var parent = targetElement.parentNode; if(parent.lastchild == targetElement) { parent.appendChild(newElement); } else { parent.insertBefore(newElement, targetElement.nextSibling); } } function generate(item) { var helper = document.createElement('input'); helper.type = 'button'; helper.value = 'Scan barcode...'; helper.style.background = '#cfc'; helper.style.color = '#484'; helper.style.border = '1px solid #484'; helper.style.padding = '5px'; helper.style.marginLeft = '10px'; helper.addEventListener('click', function(event) { var result = window.intentHelper.startActivityForResult(JSON.stringify({ action:'com.google.zxing.client.android.SCAN', category:['CATEGORY_DEFAULT'] })); result = JSON.parse(result); item.value = result['extras']['SCAN_RESULT']; }, false); return helper; } var append = []; var items = document.body.getElementsByTagName('input'); for(i in items) { var item = items[i]; if(item.name == 'query') append.push([item,generate(item)]); } for(i in append) { var target = append[i][0]; var generated = append[i][1]; insertAfter(generated, target); }
JavaScript
// ==UserScript== // @name Optimize Slashdot for mobile screen // @description Hide navigation bars on Slashdot to optimize for mobile screens // @author Jeffrey Sharkey // @include http://*slashdot.org* // ==/UserScript== function hideById(id) { var target = document.getElementById(id); if(target == null) return; target.style.display = 'none'; } function flattenById(id) { var target = document.getElementById(id); if(target == null) return; target.style.padding = '0px'; target.style.margin = '0px'; } function flattenByClass(parent, tag, className) { var items = parent.getElementsByTagName(tag); for(i in items) { var item = items[i]; if(typeof item.className !== 'string') continue; if(item.className.indexOf(className) != -1) { item.style.padding = '0px'; item.style.margin = '0px'; } } } hideById('links'); hideById('fad1'); hideById('fad2'); hideById('fad3'); hideById('fad6'); hideById('fad30'); hideById('fad60'); hideById('slashboxes'); var yuimain = document.getElementById('yui-main'); flattenByClass(yuimain,'div','yui-b'); flattenByClass(yuimain,'div','maincol'); flattenByClass(yuimain,'div','article usermode thumbs'); // these usually only apply when logged in flattenById('contents'); flattenById('articles'); flattenById('indexhead');
JavaScript
// ==UserScript== // @name Share Digg story // @description One-click to share any Digg Mobile story through an E-mail // @author Jeffrey Sharkey // @include http://m.digg.com/* // ==/UserScript== function generate(item) { var header = item.getElementsByTagName('h3')[0]; var link = header.getElementsByTagName('a')[0]; var body = item.getElementsByTagName('p')[0]; var helper = document.createElement('input'); helper.type = 'button'; helper.value = 'Share in E-mail'; helper.style.background = '#cfc'; helper.style.color = '#484'; helper.style.border = '1px solid #484'; helper.style.padding = '5px'; helper.style.marginLeft = '10px'; helper.addEventListener('click', function(event) { window.intentHelper.startActivity(JSON.stringify({ action:'ACTION_SEND', type:'plain/html', 'EXTRA_SUBJECT':link.textContent, 'EXTRA_TEXT':link.href+'\n\n'+body.textContent })); }, false); return helper; } var items = document.body.getElementsByTagName('div'); for(i in items) { var item = items[i]; if(item.className == 'news-summary') item.appendChild(generate(item)); }
JavaScript
// ==UserScript== // @name Optimize Wikipedia and view coordinates in Maps and Radar // @description Hide navigation bars to optimize for mobile screens and link coordinates from articles to Maps and Radar apps. // @author Jeffrey Sharkey // @include http://*wikipedia.org/wiki/* // ==/UserScript== function hideByClass(tag, className) { var items = document.body.getElementsByTagName(tag); for(i in items) { var item = items[i]; if(typeof item.className !== 'string') continue; if(item.className.indexOf(className) != -1) item.style.display = 'none'; } } function hideById(id) { var target = document.getElementById(id); target.style.display = 'none'; } var content = document.getElementById('content'); content.style.padding = '0px'; content.style.margin = '0px'; hideByClass('table','ambox'); hideById('column-one'); hideById('siteNotice'); hideById('toc'); function getElementByClass(parent, tag, className) { var items = parent.getElementsByTagName(tag); var answer = []; for(i in items) { var item = items[i]; if(typeof item.className !== 'string') continue; if(item.className.indexOf(className) != -1) answer.push(item); } return answer; } function createButton(title) { var button = document.createElement('input'); button.type = 'button'; button.value = title; button.style.background = '#cfc'; button.style.color = '#484'; button.style.border = '1px solid #484'; button.style.padding = '5px'; button.style.marginLeft = '10px'; return button; } var coords = document.getElementById('coordinates'); var dec = getElementByClass(coords, 'span', 'geo-dec')[0]; var lat = parseFloat(getElementByClass(dec, 'span', 'latitude')[0].textContent); var lon = parseFloat(getElementByClass(dec, 'span', 'longitude')[0].textContent); coords.appendChild(document.createElement('br')); var maps = createButton('View in Maps'); maps.addEventListener('click', function(event) { window.intentHelper.startActivity(JSON.stringify({ action:'ACTION_VIEW', data:'geo:'+lat+','+lon+'?z=14' })); }, false); coords.appendChild(maps); var radar = createButton('Find using Radar'); radar.addEventListener('click', function(event) { window.intentHelper.startActivity(JSON.stringify({ action:'com.google.android.radar.SHOW_RADAR', category:['CATEGORY_DEFAULT'], 'latitude':lat, 'longitude':lon })); }, false); coords.appendChild(radar);
JavaScript
/* * jQuery UI selectmenu * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ (function($) { $.widget("ui.selectmenu", { _init: function() { var self = this, o = this.options; //quick array of button and menu id's this.ids = [this.element.attr('id') + '-' + 'button', this.element.attr('id') + '-' + 'menu']; //define safe mouseup for future toggling this._safemouseup = true; //create menu button wrapper this.newelement = $('<a class="'+ this.widgetBaseClass +' ui-widget ui-state-default ui-corner-all" id="'+this.ids[0]+'" role="button" href="#" aria-haspopup="true" aria-owns="'+this.ids[1]+'"></a>') .insertAfter(this.element); //transfer tabindex var tabindex = this.element.attr('tabindex'); if(tabindex){ this.newelement.attr('tabindex', tabindex); } //save reference to select in data for ease in calling methods this.newelement.data('selectelement', this.element); //menu icon this.selectmenuIcon = $('<span class="'+ this.widgetBaseClass +'-icon ui-icon"></span>') .prependTo(this.newelement) .addClass( (o.style == "popup")? 'ui-icon-triangle-2-n-s' : 'ui-icon-triangle-1-s' ); //make associated form label trigger focus $('label[for='+this.element.attr('id')+']') .attr('for', this.ids[0]) .bind('click', function(){ self.newelement[0].focus(); return false; }); //click toggle for menu visibility this.newelement .bind('mousedown', function(event){ self._toggle(event); //make sure a click won't open/close instantly if(o.style == "popup"){ self._safemouseup = false; setTimeout(function(){self._safemouseup = true;}, 300); } return false; }) .bind('click',function(){ return false; }) .keydown(function(event){ var ret = true; switch (event.keyCode) { case $.ui.keyCode.ENTER: ret = true; break; case $.ui.keyCode.SPACE: ret = false; self._toggle(event); break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: ret = false; self._moveSelection(-1); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.RIGHT: ret = false; self._moveSelection(1); break; case $.ui.keyCode.TAB: ret = true; break; default: ret = false; self._typeAhead(event.keyCode, 'mouseup'); break; } return ret; }) .bind('mouseover focus', function(){ $(this).addClass(self.widgetBaseClass+'-focus ui-state-hover'); }) .bind('mouseout blur', function(){ $(this).removeClass(self.widgetBaseClass+'-focus ui-state-hover'); }); //document click closes menu $(document) .mousedown(function(event){ self.close(event); }); //change event on original selectmenu this.element .click(function(){ this._refreshValue(); }) .focus(function(){ this.newelement[0].focus(); }); //create menu portion, append to body var cornerClass = (o.style == "dropdown")? " ui-corner-bottom" : " ui-corner-all" this.list = $('<ul class="' + self.widgetBaseClass + '-menu ui-widget ui-widget-content'+cornerClass+'" aria-hidden="true" role="listbox" aria-labelledby="'+this.ids[0]+'" id="'+this.ids[1]+'"></ul>').appendTo('body'); //serialize selectmenu element options var selectOptionData = []; this.element .find('option') .each(function(){ selectOptionData.push({ value: $(this).attr('value'), text: self._formatText(jQuery(this).text()), selected: $(this).attr('selected'), classes: $(this).attr('class'), parentOptGroup: $(this).parent('optgroup').attr('label') }); }); //active state class is only used in popup style var activeClass = (self.options.style == "popup") ? " ui-state-active" : ""; //write li's for(var i in selectOptionData){ var thisLi = $('<li role="presentation"><a href="#" tabindex="-1" role="option" aria-selected="false">'+ selectOptionData[i].text +'</a></li>') .data('index',i) .addClass(selectOptionData[i].classes) .data('optionClasses', selectOptionData[i].classes|| '') .mouseup(function(event){ if(self._safemouseup){ var changed = $(this).data('index') != self._selectedIndex(); self.value($(this).data('index')); self.select(event); if(changed){ self.change(event); } self.close(event,true); } return false; }) .click(function(){ return false; }) .bind('mouseover focus', function(){ self._selectedOptionLi().addClass(activeClass); self._focusedOptionLi().removeClass(self.widgetBaseClass+'-item-focus ui-state-hover'); $(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover'); }) .bind('mouseout blur', function(){ if($(this).is( self._selectedOptionLi() )){ $(this).addClass(activeClass); } $(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover'); }); //optgroup or not... if(selectOptionData[i].parentOptGroup){ var optGroupName = self.widgetBaseClass + '-group-' + selectOptionData[i].parentOptGroup; if(this.list.find('li.' + optGroupName).size()){ this.list.find('li.' + optGroupName + ':last ul').append(thisLi); } else{ $('<li role="presentation" class="'+self.widgetBaseClass+'-group '+optGroupName+'"><span class="'+self.widgetBaseClass+'-group-label">'+selectOptionData[i].parentOptGroup+'</span><ul></ul></li>') .appendTo(this.list) .find('ul') .append(thisLi); } } else{ thisLi.appendTo(this.list); } //this allows for using the scrollbar in an overflowed list this.list.bind('mousedown mouseup', function(){return false;}); //append icon if option is specified if(o.icons){ for(var j in o.icons){ if(thisLi.is(o.icons[j].find)){ thisLi .data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon') .addClass(self.widgetBaseClass + '-hasIcon'); var iconClass = o.icons[j].icon || ""; thisLi .find('a:eq(0)') .prepend('<span class="'+self.widgetBaseClass+'-item-icon ui-icon '+iconClass + '"></span>'); } } } } //add corners to top and bottom menu items this.list.find('li:last').addClass("ui-corner-bottom"); if(o.style == 'popup'){ this.list.find('li:first').addClass("ui-corner-top"); } //transfer classes to selectmenu and list if(o.transferClasses){ var transferClasses = this.element.attr('class') || ''; this.newelement.add(this.list).addClass(transferClasses); } //original selectmenu width var selectWidth = this.element.width(); //set menu button width this.newelement.width( (o.width) ? o.width : selectWidth); //set menu width to either menuWidth option value, width option value, or select width if(o.style == 'dropdown'){ this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width : selectWidth)); } else { this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width - o.handleWidth : selectWidth - o.handleWidth)); } //set max height from option if(o.maxHeight && o.maxHeight < this.list.height()){ this.list.height(o.maxHeight); } //save reference to actionable li's (not group label li's) this._optionLis = this.list.find('li:not(.'+ self.widgetBaseClass +'-group)'); //transfer menu click to menu button this.list .keydown(function(event){ var ret = true; switch (event.keyCode) { case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: ret = false; self._moveFocus(-1); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.RIGHT: ret = false; self._moveFocus(1); break; case $.ui.keyCode.HOME: ret = false; self._moveFocus(':first'); break; case $.ui.keyCode.PAGE_UP: ret = false; self._scrollPage('up'); break; case $.ui.keyCode.PAGE_DOWN: ret = false; self._scrollPage('down'); break; case $.ui.keyCode.END: ret = false; self._moveFocus(':last'); break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: ret = false; self.close(event,true); $(event.target).parents('li:eq(0)').trigger('mouseup'); break; case $.ui.keyCode.TAB: ret = true; self.close(event,true); break; case $.ui.keyCode.ESCAPE: ret = false; self.close(event,true); break; default: ret = false; self._typeAhead(event.keyCode,'focus'); break; } return ret; }); //selectmenu style if(o.style == 'dropdown'){ this.newelement .addClass(self.widgetBaseClass+"-dropdown"); this.list .addClass(self.widgetBaseClass+"-menu-dropdown"); } else { this.newelement .addClass(self.widgetBaseClass+"-popup"); this.list .addClass(self.widgetBaseClass+"-menu-popup"); } //append status span to button this.newelement.prepend('<span class="'+self.widgetBaseClass+'-status">'+ selectOptionData[this._selectedIndex()].text +'</span>'); //hide original selectmenu element this.element.hide(); //transfer disabled state if(this.element.attr('disabled') == true){ this.disable(); } //update value this.value(this._selectedIndex()); }, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); //unbind click on label, reset its for attr $('label[for='+this.newelement.attr('id')+']') .attr('for',this.element.attr('id')) .unbind('click'); this.newelement.remove(); this.list.remove(); this.element.show(); }, _typeAhead: function(code, eventType){ var self = this; //define self._prevChar if needed if(!self._prevChar){ self._prevChar = ['',0]; } var C = String.fromCharCode(code); c = C.toLowerCase(); var focusFound = false; function focusOpt(elem, ind){ focusFound = true; $(elem).trigger(eventType); self._prevChar[1] = ind; }; this.list.find('li a').each(function(i){ if(!focusFound){ var thisText = $(this).text(); if( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){ if(self._prevChar[0] == C){ if(self._prevChar[1] < i){ focusOpt(this,i); } } else{ focusOpt(this,i); } } } }); this._prevChar[0] = C; }, _uiHash: function(){ return { value: this.value() }; }, open: function(event){ var self = this; var disabledStatus = this.newelement.attr("aria-disabled"); if(disabledStatus != 'true'){ this._refreshPosition(); this._closeOthers(event); this.newelement .addClass('ui-state-active'); this.list .appendTo('body') .addClass(self.widgetBaseClass + '-open') .attr('aria-hidden', false) .find('li:not(.'+ self.widgetBaseClass +'-group):eq('+ this._selectedIndex() +') a')[0].focus(); if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-all').addClass('ui-corner-top'); } this._refreshPosition(); this._trigger("open", event, this._uiHash()); } }, close: function(event, retainFocus){ if(this.newelement.is('.ui-state-active')){ this.newelement .removeClass('ui-state-active'); this.list .attr('aria-hidden', true) .removeClass(this.widgetBaseClass+'-open'); if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all'); } if(retainFocus){this.newelement[0].focus();} this._trigger("close", event, this._uiHash()); } }, change: function(event) { this.element.trigger('change'); this._trigger("change", event, this._uiHash()); }, select: function(event) { this._trigger("select", event, this._uiHash()); }, _closeOthers: function(event){ $('.'+ this.widgetBaseClass +'.ui-state-active').not(this.newelement).each(function(){ $(this).data('selectelement').selectmenu('close',event); }); $('.'+ this.widgetBaseClass +'.ui-state-hover').trigger('mouseout'); }, _toggle: function(event,retainFocus){ if(this.list.is('.'+ this.widgetBaseClass +'-open')){ this.close(event,retainFocus); } else { this.open(event); } }, _formatText: function(text){ return this.options.format ? this.options.format(text) : text; }, _selectedIndex: function(){ return this.element[0].selectedIndex; }, _selectedOptionLi: function(){ return this._optionLis.eq(this._selectedIndex()); }, _focusedOptionLi: function(){ return this.list.find('.'+ this.widgetBaseClass +'-item-focus'); }, _moveSelection: function(amt){ var currIndex = parseInt(this._selectedOptionLi().data('index'), 10); var newIndex = currIndex + amt; return this._optionLis.eq(newIndex).trigger('mouseup'); }, _moveFocus: function(amt){ if(!isNaN(amt)){ var currIndex = parseInt(this._focusedOptionLi().data('index'), 10); var newIndex = currIndex + amt; } else { var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10); } if(newIndex < 0){ newIndex = 0; } if(newIndex > this._optionLis.size()-1){ newIndex = this._optionLis.size()-1; } var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000); this._focusedOptionLi().find('a:eq(0)').attr('id',''); this._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID)[0].focus(); this.list.attr('aria-activedescendant', activeID); }, _scrollPage: function(direction){ var numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight()); numPerPage = (direction == 'up') ? -numPerPage : numPerPage; this._moveFocus(numPerPage); }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.close(); this.element .add(this.newelement) .add(this.list) [value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, value: function(newValue) { if (arguments.length) { this.element[0].selectedIndex = newValue; this._refreshValue(); this._refreshPosition(); } return this.element[0].selectedIndex; }, _refreshValue: function() { var activeClass = (this.options.style == "popup") ? " ui-state-active" : ""; var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000); //deselect previous this.list .find('.'+ this.widgetBaseClass +'-item-selected') .removeClass(this.widgetBaseClass + "-item-selected" + activeClass) .find('a') .attr('aria-selected', 'false') .attr('id', ''); //select new this._selectedOptionLi() .addClass(this.widgetBaseClass + "-item-selected"+activeClass) .find('a') .attr('aria-selected', 'true') .attr('id', activeID); //toggle any class brought in from option var currentOptionClasses = this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : ""; var newOptionClasses = this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : ""; this.newelement .removeClass(currentOptionClasses) .data('optionClasses', newOptionClasses) .addClass( newOptionClasses ) .find('.'+this.widgetBaseClass+'-status') .html( this._selectedOptionLi() .find('a:eq(0)') .html() ); this.list.attr('aria-activedescendant', activeID) }, _refreshPosition: function(){ //set left value this.list.css('left', this.newelement.offset().left); //set top value var menuTop = this.newelement.offset().top; var scrolledAmt = this.list[0].scrollTop; this.list.find('li:lt('+this._selectedIndex()+')').each(function(){ scrolledAmt -= $(this).outerHeight(); }); if(this.newelement.is('.'+this.widgetBaseClass+'-popup')){ menuTop+=scrolledAmt; this.list.css('top', menuTop); } else { menuTop += this.newelement.height(); this.list.css('top', menuTop); } } }); $.extend($.ui.selectmenu, { getter: "value", version: "@VERSION", eventPrefix: "selectmenu", defaults: { transferClasses: true, style: 'popup', width: null, menuWidth: null, handleWidth: 26, maxHeight: null, icons: null, format: null } }); })(jQuery);
JavaScript
$(document).ready(function(){ $('select.styled').selectmenu(); $('input[type="checkbox"]').each(function(){ checkerToggle(this); }); $('input[type="checkbox"]').change(function(){ checkerToggle(this); }); function checkerToggle(el) { if($(el).attr('checked')) { $(el).parent().addClass('checked'); } else { $(el).parent().removeClass('checked'); } } console.log($('#control-panel').length); if($('#control-panel').length != 0) { $('.scroll-pane').addClass('has-controls'); } $('.scroll-pane').jScrollPane({ verticalDragMinHeight: 30, verticalDragMaxHeight: 30 }); $('.scroll-pane').hover(function(){ $('.jspVerticalBar').fadeIn(500); }, function(){ $('.jspVerticalBar').fadeOut(500); }); });
JavaScript
/* * jQuery UI selectmenu * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ (function($) { $.widget("ui.selectmenu", { _init: function() { var self = this, o = this.options; //quick array of button and menu id's this.ids = [this.element.attr('id') + '-' + 'button', this.element.attr('id') + '-' + 'menu']; //define safe mouseup for future toggling this._safemouseup = true; //create menu button wrapper this.newelement = $('<a class="'+ this.widgetBaseClass +' ui-widget ui-state-default ui-corner-all" id="'+this.ids[0]+'" role="button" href="#" aria-haspopup="true" aria-owns="'+this.ids[1]+'"></a>') .insertAfter(this.element); //transfer tabindex var tabindex = this.element.attr('tabindex'); if(tabindex){ this.newelement.attr('tabindex', tabindex); } //save reference to select in data for ease in calling methods this.newelement.data('selectelement', this.element); //menu icon this.selectmenuIcon = $('<span class="'+ this.widgetBaseClass +'-icon ui-icon"></span>') .prependTo(this.newelement) .addClass( (o.style == "popup")? 'ui-icon-triangle-2-n-s' : 'ui-icon-triangle-1-s' ); //make associated form label trigger focus $('label[for='+this.element.attr('id')+']') .attr('for', this.ids[0]) .bind('click', function(){ self.newelement[0].focus(); return false; }); //click toggle for menu visibility this.newelement .bind('mousedown', function(event){ self._toggle(event); //make sure a click won't open/close instantly if(o.style == "popup"){ self._safemouseup = false; setTimeout(function(){self._safemouseup = true;}, 300); } return false; }) .bind('click',function(){ return false; }) .keydown(function(event){ var ret = true; switch (event.keyCode) { case $.ui.keyCode.ENTER: ret = true; break; case $.ui.keyCode.SPACE: ret = false; self._toggle(event); break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: ret = false; self._moveSelection(-1); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.RIGHT: ret = false; self._moveSelection(1); break; case $.ui.keyCode.TAB: ret = true; break; default: ret = false; self._typeAhead(event.keyCode, 'mouseup'); break; } return ret; }) .bind('mouseover focus', function(){ $(this).addClass(self.widgetBaseClass+'-focus ui-state-hover'); }) .bind('mouseout blur', function(){ $(this).removeClass(self.widgetBaseClass+'-focus ui-state-hover'); }); //document click closes menu $(document) .mousedown(function(event){ self.close(event); }); //change event on original selectmenu this.element .click(function(){ this._refreshValue(); }) .focus(function(){ this.newelement[0].focus(); }); //create menu portion, append to body var cornerClass = (o.style == "dropdown")? " ui-corner-bottom" : " ui-corner-all" this.list = $('<ul class="' + self.widgetBaseClass + '-menu ui-widget ui-widget-content'+cornerClass+'" aria-hidden="true" role="listbox" aria-labelledby="'+this.ids[0]+'" id="'+this.ids[1]+'"></ul>').appendTo('body'); //serialize selectmenu element options var selectOptionData = []; this.element .find('option') .each(function(){ selectOptionData.push({ value: $(this).attr('value'), text: self._formatText(jQuery(this).text()), selected: $(this).attr('selected'), classes: $(this).attr('class'), parentOptGroup: $(this).parent('optgroup').attr('label') }); }); //active state class is only used in popup style var activeClass = (self.options.style == "popup") ? " ui-state-active" : ""; //write li's for(var i in selectOptionData){ var thisLi = $('<li role="presentation"><a href="#" tabindex="-1" role="option" aria-selected="false">'+ selectOptionData[i].text +'</a></li>') .data('index',i) .addClass(selectOptionData[i].classes) .data('optionClasses', selectOptionData[i].classes|| '') .mouseup(function(event){ if(self._safemouseup){ var changed = $(this).data('index') != self._selectedIndex(); self.value($(this).data('index')); self.select(event); if(changed){ self.change(event); } self.close(event,true); } return false; }) .click(function(){ return false; }) .bind('mouseover focus', function(){ self._selectedOptionLi().addClass(activeClass); self._focusedOptionLi().removeClass(self.widgetBaseClass+'-item-focus ui-state-hover'); $(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover'); }) .bind('mouseout blur', function(){ if($(this).is( self._selectedOptionLi() )){ $(this).addClass(activeClass); } $(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover'); }); //optgroup or not... if(selectOptionData[i].parentOptGroup){ var optGroupName = self.widgetBaseClass + '-group-' + selectOptionData[i].parentOptGroup; if(this.list.find('li.' + optGroupName).size()){ this.list.find('li.' + optGroupName + ':last ul').append(thisLi); } else{ $('<li role="presentation" class="'+self.widgetBaseClass+'-group '+optGroupName+'"><span class="'+self.widgetBaseClass+'-group-label">'+selectOptionData[i].parentOptGroup+'</span><ul></ul></li>') .appendTo(this.list) .find('ul') .append(thisLi); } } else{ thisLi.appendTo(this.list); } //this allows for using the scrollbar in an overflowed list this.list.bind('mousedown mouseup', function(){return false;}); //append icon if option is specified if(o.icons){ for(var j in o.icons){ if(thisLi.is(o.icons[j].find)){ thisLi .data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon') .addClass(self.widgetBaseClass + '-hasIcon'); var iconClass = o.icons[j].icon || ""; thisLi .find('a:eq(0)') .prepend('<span class="'+self.widgetBaseClass+'-item-icon ui-icon '+iconClass + '"></span>'); } } } } //add corners to top and bottom menu items this.list.find('li:last').addClass("ui-corner-bottom"); if(o.style == 'popup'){ this.list.find('li:first').addClass("ui-corner-top"); } //transfer classes to selectmenu and list if(o.transferClasses){ var transferClasses = this.element.attr('class') || ''; this.newelement.add(this.list).addClass(transferClasses); } //original selectmenu width var selectWidth = this.element.width(); //set menu button width this.newelement.width( (o.width) ? o.width : selectWidth); //set menu width to either menuWidth option value, width option value, or select width if(o.style == 'dropdown'){ this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width : selectWidth)); } else { this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width - o.handleWidth : selectWidth - o.handleWidth)); } //set max height from option if(o.maxHeight && o.maxHeight < this.list.height()){ this.list.height(o.maxHeight); } //save reference to actionable li's (not group label li's) this._optionLis = this.list.find('li:not(.'+ self.widgetBaseClass +'-group)'); //transfer menu click to menu button this.list .keydown(function(event){ var ret = true; switch (event.keyCode) { case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: ret = false; self._moveFocus(-1); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.RIGHT: ret = false; self._moveFocus(1); break; case $.ui.keyCode.HOME: ret = false; self._moveFocus(':first'); break; case $.ui.keyCode.PAGE_UP: ret = false; self._scrollPage('up'); break; case $.ui.keyCode.PAGE_DOWN: ret = false; self._scrollPage('down'); break; case $.ui.keyCode.END: ret = false; self._moveFocus(':last'); break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: ret = false; self.close(event,true); $(event.target).parents('li:eq(0)').trigger('mouseup'); break; case $.ui.keyCode.TAB: ret = true; self.close(event,true); break; case $.ui.keyCode.ESCAPE: ret = false; self.close(event,true); break; default: ret = false; self._typeAhead(event.keyCode,'focus'); break; } return ret; }); //selectmenu style if(o.style == 'dropdown'){ this.newelement .addClass(self.widgetBaseClass+"-dropdown"); this.list .addClass(self.widgetBaseClass+"-menu-dropdown"); } else { this.newelement .addClass(self.widgetBaseClass+"-popup"); this.list .addClass(self.widgetBaseClass+"-menu-popup"); } //append status span to button this.newelement.prepend('<span class="'+self.widgetBaseClass+'-status">'+ selectOptionData[this._selectedIndex()].text +'</span>'); //hide original selectmenu element this.element.hide(); //transfer disabled state if(this.element.attr('disabled') == true){ this.disable(); } //update value this.value(this._selectedIndex()); }, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); //unbind click on label, reset its for attr $('label[for='+this.newelement.attr('id')+']') .attr('for',this.element.attr('id')) .unbind('click'); this.newelement.remove(); this.list.remove(); this.element.show(); }, _typeAhead: function(code, eventType){ var self = this; //define self._prevChar if needed if(!self._prevChar){ self._prevChar = ['',0]; } var C = String.fromCharCode(code); c = C.toLowerCase(); var focusFound = false; function focusOpt(elem, ind){ focusFound = true; $(elem).trigger(eventType); self._prevChar[1] = ind; }; this.list.find('li a').each(function(i){ if(!focusFound){ var thisText = $(this).text(); if( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){ if(self._prevChar[0] == C){ if(self._prevChar[1] < i){ focusOpt(this,i); } } else{ focusOpt(this,i); } } } }); this._prevChar[0] = C; }, _uiHash: function(){ return { value: this.value() }; }, open: function(event){ var self = this; var disabledStatus = this.newelement.attr("aria-disabled"); if(disabledStatus != 'true'){ this._refreshPosition(); this._closeOthers(event); this.newelement .addClass('ui-state-active'); this.list .appendTo('body') .addClass(self.widgetBaseClass + '-open') .attr('aria-hidden', false) .find('li:not(.'+ self.widgetBaseClass +'-group):eq('+ this._selectedIndex() +') a')[0].focus(); if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-all').addClass('ui-corner-top'); } this._refreshPosition(); this._trigger("open", event, this._uiHash()); } }, close: function(event, retainFocus){ if(this.newelement.is('.ui-state-active')){ this.newelement .removeClass('ui-state-active'); this.list .attr('aria-hidden', true) .removeClass(this.widgetBaseClass+'-open'); if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all'); } if(retainFocus){this.newelement[0].focus();} this._trigger("close", event, this._uiHash()); } }, change: function(event) { this.element.trigger('change'); this._trigger("change", event, this._uiHash()); }, select: function(event) { this._trigger("select", event, this._uiHash()); }, _closeOthers: function(event){ $('.'+ this.widgetBaseClass +'.ui-state-active').not(this.newelement).each(function(){ $(this).data('selectelement').selectmenu('close',event); }); $('.'+ this.widgetBaseClass +'.ui-state-hover').trigger('mouseout'); }, _toggle: function(event,retainFocus){ if(this.list.is('.'+ this.widgetBaseClass +'-open')){ this.close(event,retainFocus); } else { this.open(event); } }, _formatText: function(text){ return this.options.format ? this.options.format(text) : text; }, _selectedIndex: function(){ return this.element[0].selectedIndex; }, _selectedOptionLi: function(){ return this._optionLis.eq(this._selectedIndex()); }, _focusedOptionLi: function(){ return this.list.find('.'+ this.widgetBaseClass +'-item-focus'); }, _moveSelection: function(amt){ var currIndex = parseInt(this._selectedOptionLi().data('index'), 10); var newIndex = currIndex + amt; return this._optionLis.eq(newIndex).trigger('mouseup'); }, _moveFocus: function(amt){ if(!isNaN(amt)){ var currIndex = parseInt(this._focusedOptionLi().data('index'), 10); var newIndex = currIndex + amt; } else { var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10); } if(newIndex < 0){ newIndex = 0; } if(newIndex > this._optionLis.size()-1){ newIndex = this._optionLis.size()-1; } var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000); this._focusedOptionLi().find('a:eq(0)').attr('id',''); this._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID)[0].focus(); this.list.attr('aria-activedescendant', activeID); }, _scrollPage: function(direction){ var numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight()); numPerPage = (direction == 'up') ? -numPerPage : numPerPage; this._moveFocus(numPerPage); }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.close(); this.element .add(this.newelement) .add(this.list) [value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, value: function(newValue) { if (arguments.length) { this.element[0].selectedIndex = newValue; this._refreshValue(); this._refreshPosition(); } return this.element[0].selectedIndex; }, _refreshValue: function() { var activeClass = (this.options.style == "popup") ? " ui-state-active" : ""; var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000); //deselect previous this.list .find('.'+ this.widgetBaseClass +'-item-selected') .removeClass(this.widgetBaseClass + "-item-selected" + activeClass) .find('a') .attr('aria-selected', 'false') .attr('id', ''); //select new this._selectedOptionLi() .addClass(this.widgetBaseClass + "-item-selected"+activeClass) .find('a') .attr('aria-selected', 'true') .attr('id', activeID); //toggle any class brought in from option var currentOptionClasses = this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : ""; var newOptionClasses = this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : ""; this.newelement .removeClass(currentOptionClasses) .data('optionClasses', newOptionClasses) .addClass( newOptionClasses ) .find('.'+this.widgetBaseClass+'-status') .html( this._selectedOptionLi() .find('a:eq(0)') .html() ); this.list.attr('aria-activedescendant', activeID) }, _refreshPosition: function(){ //set left value this.list.css('left', this.newelement.offset().left); //set top value var menuTop = this.newelement.offset().top; var scrolledAmt = this.list[0].scrollTop; this.list.find('li:lt('+this._selectedIndex()+')').each(function(){ scrolledAmt -= $(this).outerHeight(); }); if(this.newelement.is('.'+this.widgetBaseClass+'-popup')){ menuTop+=scrolledAmt; this.list.css('top', menuTop); } else { menuTop += this.newelement.height(); this.list.css('top', menuTop); } } }); $.extend($.ui.selectmenu, { getter: "value", version: "@VERSION", eventPrefix: "selectmenu", defaults: { transferClasses: true, style: 'popup', width: null, menuWidth: null, handleWidth: 26, maxHeight: null, icons: null, format: null } }); })(jQuery);
JavaScript
$(document).ready(function(){ $('select.styled').selectmenu(); $('input[type="checkbox"]').each(function(){ checkerToggle(this); }); $('input[type="checkbox"]').change(function(){ checkerToggle(this); }); function checkerToggle(el) { if($(el).attr('checked')) { $(el).parent().addClass('checked'); } else { $(el).parent().removeClass('checked'); } } $('.scroll-pane').jScrollPane({ verticalDragMinHeight: 30, verticalDragMaxHeight: 30 }); $('.scroll-pane').hover(function(){ $('.jspVerticalBar').fadeIn(500); }, function(){ $('.jspVerticalBar').fadeOut(500); }); });
JavaScript
/* * jQuery UI selectmenu * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ (function($) { $.widget("ui.selectmenu", { _init: function() { var self = this, o = this.options; //quick array of button and menu id's this.ids = [this.element.attr('id') + '-' + 'button', this.element.attr('id') + '-' + 'menu']; //define safe mouseup for future toggling this._safemouseup = true; //create menu button wrapper this.newelement = $('<a class="'+ this.widgetBaseClass +' ui-widget ui-state-default ui-corner-all" id="'+this.ids[0]+'" role="button" href="#" aria-haspopup="true" aria-owns="'+this.ids[1]+'"></a>') .insertAfter(this.element); //transfer tabindex var tabindex = this.element.attr('tabindex'); if(tabindex){ this.newelement.attr('tabindex', tabindex); } //save reference to select in data for ease in calling methods this.newelement.data('selectelement', this.element); //menu icon this.selectmenuIcon = $('<span class="'+ this.widgetBaseClass +'-icon ui-icon"></span>') .prependTo(this.newelement) .addClass( (o.style == "popup")? 'ui-icon-triangle-2-n-s' : 'ui-icon-triangle-1-s' ); //make associated form label trigger focus $('label[for='+this.element.attr('id')+']') .attr('for', this.ids[0]) .bind('click', function(){ self.newelement[0].focus(); return false; }); //click toggle for menu visibility this.newelement .bind('mousedown', function(event){ self._toggle(event); //make sure a click won't open/close instantly if(o.style == "popup"){ self._safemouseup = false; setTimeout(function(){self._safemouseup = true;}, 300); } return false; }) .bind('click',function(){ return false; }) .keydown(function(event){ var ret = true; switch (event.keyCode) { case $.ui.keyCode.ENTER: ret = true; break; case $.ui.keyCode.SPACE: ret = false; self._toggle(event); break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: ret = false; self._moveSelection(-1); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.RIGHT: ret = false; self._moveSelection(1); break; case $.ui.keyCode.TAB: ret = true; break; default: ret = false; self._typeAhead(event.keyCode, 'mouseup'); break; } return ret; }) .bind('mouseover focus', function(){ $(this).addClass(self.widgetBaseClass+'-focus ui-state-hover'); }) .bind('mouseout blur', function(){ $(this).removeClass(self.widgetBaseClass+'-focus ui-state-hover'); }); //document click closes menu $(document) .mousedown(function(event){ self.close(event); }); //change event on original selectmenu this.element .click(function(){ this._refreshValue(); }) .focus(function(){ this.newelement[0].focus(); }); //create menu portion, append to body var cornerClass = (o.style == "dropdown")? " ui-corner-bottom" : " ui-corner-all" this.list = $('<ul class="' + self.widgetBaseClass + '-menu ui-widget ui-widget-content'+cornerClass+'" aria-hidden="true" role="listbox" aria-labelledby="'+this.ids[0]+'" id="'+this.ids[1]+'"></ul>').appendTo('body'); //serialize selectmenu element options var selectOptionData = []; this.element .find('option') .each(function(){ selectOptionData.push({ value: $(this).attr('value'), text: self._formatText(jQuery(this).text()), selected: $(this).attr('selected'), classes: $(this).attr('class'), parentOptGroup: $(this).parent('optgroup').attr('label') }); }); //active state class is only used in popup style var activeClass = (self.options.style == "popup") ? " ui-state-active" : ""; //write li's for(var i in selectOptionData){ var thisLi = $('<li role="presentation"><a href="#" tabindex="-1" role="option" aria-selected="false">'+ selectOptionData[i].text +'</a></li>') .data('index',i) .addClass(selectOptionData[i].classes) .data('optionClasses', selectOptionData[i].classes|| '') .mouseup(function(event){ if(self._safemouseup){ var changed = $(this).data('index') != self._selectedIndex(); self.value($(this).data('index')); self.select(event); if(changed){ self.change(event); } self.close(event,true); } return false; }) .click(function(){ return false; }) .bind('mouseover focus', function(){ self._selectedOptionLi().addClass(activeClass); self._focusedOptionLi().removeClass(self.widgetBaseClass+'-item-focus ui-state-hover'); $(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover'); }) .bind('mouseout blur', function(){ if($(this).is( self._selectedOptionLi() )){ $(this).addClass(activeClass); } $(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover'); }); //optgroup or not... if(selectOptionData[i].parentOptGroup){ var optGroupName = self.widgetBaseClass + '-group-' + selectOptionData[i].parentOptGroup; if(this.list.find('li.' + optGroupName).size()){ this.list.find('li.' + optGroupName + ':last ul').append(thisLi); } else{ $('<li role="presentation" class="'+self.widgetBaseClass+'-group '+optGroupName+'"><span class="'+self.widgetBaseClass+'-group-label">'+selectOptionData[i].parentOptGroup+'</span><ul></ul></li>') .appendTo(this.list) .find('ul') .append(thisLi); } } else{ thisLi.appendTo(this.list); } //this allows for using the scrollbar in an overflowed list this.list.bind('mousedown mouseup', function(){return false;}); //append icon if option is specified if(o.icons){ for(var j in o.icons){ if(thisLi.is(o.icons[j].find)){ thisLi .data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon') .addClass(self.widgetBaseClass + '-hasIcon'); var iconClass = o.icons[j].icon || ""; thisLi .find('a:eq(0)') .prepend('<span class="'+self.widgetBaseClass+'-item-icon ui-icon '+iconClass + '"></span>'); } } } } //add corners to top and bottom menu items this.list.find('li:last').addClass("ui-corner-bottom"); if(o.style == 'popup'){ this.list.find('li:first').addClass("ui-corner-top"); } //transfer classes to selectmenu and list if(o.transferClasses){ var transferClasses = this.element.attr('class') || ''; this.newelement.add(this.list).addClass(transferClasses); } //original selectmenu width var selectWidth = this.element.width(); //set menu button width this.newelement.width( (o.width) ? o.width : selectWidth); //set menu width to either menuWidth option value, width option value, or select width if(o.style == 'dropdown'){ this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width : selectWidth)); } else { this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width - o.handleWidth : selectWidth - o.handleWidth)); } //set max height from option if(o.maxHeight && o.maxHeight < this.list.height()){ this.list.height(o.maxHeight); } //save reference to actionable li's (not group label li's) this._optionLis = this.list.find('li:not(.'+ self.widgetBaseClass +'-group)'); //transfer menu click to menu button this.list .keydown(function(event){ var ret = true; switch (event.keyCode) { case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: ret = false; self._moveFocus(-1); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.RIGHT: ret = false; self._moveFocus(1); break; case $.ui.keyCode.HOME: ret = false; self._moveFocus(':first'); break; case $.ui.keyCode.PAGE_UP: ret = false; self._scrollPage('up'); break; case $.ui.keyCode.PAGE_DOWN: ret = false; self._scrollPage('down'); break; case $.ui.keyCode.END: ret = false; self._moveFocus(':last'); break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: ret = false; self.close(event,true); $(event.target).parents('li:eq(0)').trigger('mouseup'); break; case $.ui.keyCode.TAB: ret = true; self.close(event,true); break; case $.ui.keyCode.ESCAPE: ret = false; self.close(event,true); break; default: ret = false; self._typeAhead(event.keyCode,'focus'); break; } return ret; }); //selectmenu style if(o.style == 'dropdown'){ this.newelement .addClass(self.widgetBaseClass+"-dropdown"); this.list .addClass(self.widgetBaseClass+"-menu-dropdown"); } else { this.newelement .addClass(self.widgetBaseClass+"-popup"); this.list .addClass(self.widgetBaseClass+"-menu-popup"); } //append status span to button this.newelement.prepend('<span class="'+self.widgetBaseClass+'-status">'+ selectOptionData[this._selectedIndex()].text +'</span>'); //hide original selectmenu element this.element.hide(); //transfer disabled state if(this.element.attr('disabled') == true){ this.disable(); } //update value this.value(this._selectedIndex()); }, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); //unbind click on label, reset its for attr $('label[for='+this.newelement.attr('id')+']') .attr('for',this.element.attr('id')) .unbind('click'); this.newelement.remove(); this.list.remove(); this.element.show(); }, _typeAhead: function(code, eventType){ var self = this; //define self._prevChar if needed if(!self._prevChar){ self._prevChar = ['',0]; } var C = String.fromCharCode(code); c = C.toLowerCase(); var focusFound = false; function focusOpt(elem, ind){ focusFound = true; $(elem).trigger(eventType); self._prevChar[1] = ind; }; this.list.find('li a').each(function(i){ if(!focusFound){ var thisText = $(this).text(); if( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){ if(self._prevChar[0] == C){ if(self._prevChar[1] < i){ focusOpt(this,i); } } else{ focusOpt(this,i); } } } }); this._prevChar[0] = C; }, _uiHash: function(){ return { value: this.value() }; }, open: function(event){ var self = this; var disabledStatus = this.newelement.attr("aria-disabled"); if(disabledStatus != 'true'){ this._refreshPosition(); this._closeOthers(event); this.newelement .addClass('ui-state-active'); this.list .appendTo('body') .addClass(self.widgetBaseClass + '-open') .attr('aria-hidden', false) .find('li:not(.'+ self.widgetBaseClass +'-group):eq('+ this._selectedIndex() +') a')[0].focus(); if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-all').addClass('ui-corner-top'); } this._refreshPosition(); this._trigger("open", event, this._uiHash()); } }, close: function(event, retainFocus){ if(this.newelement.is('.ui-state-active')){ this.newelement .removeClass('ui-state-active'); this.list .attr('aria-hidden', true) .removeClass(this.widgetBaseClass+'-open'); if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all'); } if(retainFocus){this.newelement[0].focus();} this._trigger("close", event, this._uiHash()); } }, change: function(event) { this.element.trigger('change'); this._trigger("change", event, this._uiHash()); }, select: function(event) { this._trigger("select", event, this._uiHash()); }, _closeOthers: function(event){ $('.'+ this.widgetBaseClass +'.ui-state-active').not(this.newelement).each(function(){ $(this).data('selectelement').selectmenu('close',event); }); $('.'+ this.widgetBaseClass +'.ui-state-hover').trigger('mouseout'); }, _toggle: function(event,retainFocus){ if(this.list.is('.'+ this.widgetBaseClass +'-open')){ this.close(event,retainFocus); } else { this.open(event); } }, _formatText: function(text){ return this.options.format ? this.options.format(text) : text; }, _selectedIndex: function(){ return this.element[0].selectedIndex; }, _selectedOptionLi: function(){ return this._optionLis.eq(this._selectedIndex()); }, _focusedOptionLi: function(){ return this.list.find('.'+ this.widgetBaseClass +'-item-focus'); }, _moveSelection: function(amt){ var currIndex = parseInt(this._selectedOptionLi().data('index'), 10); var newIndex = currIndex + amt; return this._optionLis.eq(newIndex).trigger('mouseup'); }, _moveFocus: function(amt){ if(!isNaN(amt)){ var currIndex = parseInt(this._focusedOptionLi().data('index'), 10); var newIndex = currIndex + amt; } else { var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10); } if(newIndex < 0){ newIndex = 0; } if(newIndex > this._optionLis.size()-1){ newIndex = this._optionLis.size()-1; } var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000); this._focusedOptionLi().find('a:eq(0)').attr('id',''); this._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID)[0].focus(); this.list.attr('aria-activedescendant', activeID); }, _scrollPage: function(direction){ var numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight()); numPerPage = (direction == 'up') ? -numPerPage : numPerPage; this._moveFocus(numPerPage); }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.close(); this.element .add(this.newelement) .add(this.list) [value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, value: function(newValue) { if (arguments.length) { this.element[0].selectedIndex = newValue; this._refreshValue(); this._refreshPosition(); } return this.element[0].selectedIndex; }, _refreshValue: function() { var activeClass = (this.options.style == "popup") ? " ui-state-active" : ""; var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000); //deselect previous this.list .find('.'+ this.widgetBaseClass +'-item-selected') .removeClass(this.widgetBaseClass + "-item-selected" + activeClass) .find('a') .attr('aria-selected', 'false') .attr('id', ''); //select new this._selectedOptionLi() .addClass(this.widgetBaseClass + "-item-selected"+activeClass) .find('a') .attr('aria-selected', 'true') .attr('id', activeID); //toggle any class brought in from option var currentOptionClasses = this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : ""; var newOptionClasses = this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : ""; this.newelement .removeClass(currentOptionClasses) .data('optionClasses', newOptionClasses) .addClass( newOptionClasses ) .find('.'+this.widgetBaseClass+'-status') .html( this._selectedOptionLi() .find('a:eq(0)') .html() ); this.list.attr('aria-activedescendant', activeID) }, _refreshPosition: function(){ //set left value this.list.css('left', this.newelement.offset().left); //set top value var menuTop = this.newelement.offset().top; var scrolledAmt = this.list[0].scrollTop; this.list.find('li:lt('+this._selectedIndex()+')').each(function(){ scrolledAmt -= $(this).outerHeight(); }); if(this.newelement.is('.'+this.widgetBaseClass+'-popup')){ menuTop+=scrolledAmt; this.list.css('top', menuTop); } else { menuTop += this.newelement.height(); this.list.css('top', menuTop); } } }); $.extend($.ui.selectmenu, { getter: "value", version: "@VERSION", eventPrefix: "selectmenu", defaults: { transferClasses: true, style: 'popup', width: null, menuWidth: null, handleWidth: 26, maxHeight: null, icons: null, format: null } }); })(jQuery);
JavaScript
$(document).ready(function(){ $('select.styled').selectmenu(); $('input[type="checkbox"]').each(function(){ checkerToggle(this); }); $('input[type="checkbox"]').change(function(){ checkerToggle(this); }); function checkerToggle(el) { if($(el).attr('checked')) { $(el).parent().addClass('checked'); } else { $(el).parent().removeClass('checked'); } } console.log($('#control-panel').length); if($('#control-panel').length != 0) { $('.scroll-pane').addClass('has-controls'); } $('.scroll-pane').jScrollPane({ verticalDragMinHeight: 30, verticalDragMaxHeight: 30 }); $('.scroll-pane').hover(function(){ $('.jspVerticalBar').fadeIn(500); }, function(){ $('.jspVerticalBar').fadeOut(500); }); });
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
JavaScript
var activeta; var phonetic=new Array(); var shift=false; phonetic['k']='\u0995'; phonetic['0']='\u09e6'; phonetic['1']='\u09e7'; phonetic['2']='\u09e8'; phonetic['3']='\u09e9'; phonetic['4']='\u09ea'; phonetic['5']='\u09eb'; phonetic['6']='\u09ec'; phonetic['7']='\u09ed'; phonetic['8']='\u09ee'; phonetic['9']='\u09ef'; phonetic['i']='\u09BF'; phonetic['I']='\u0987'; phonetic['ii']='\u09C0'; phonetic['II']='\u0988'; phonetic['e']='\u09C7'; phonetic['E']='\u098F'; phonetic['U']='\u0989'; phonetic['u']='\u09C1'; phonetic['uu']='\u09C2'; phonetic['UU']='\u098A'; phonetic['r']='\u09B0'; phonetic['WR']='\u098B'; phonetic['a']='\u09BE'; phonetic['A']='\u0986'; phonetic['ao']='\u0985'; phonetic['s']='\u09B8'; phonetic['t']='\u099f'; phonetic['K']='\u0996'; phonetic['kh']='\u0996'; phonetic['n']='\u09A8'; phonetic['N']='\u09A3'; phonetic['T']='\u09A4'; phonetic['Th']='\u09A5'; phonetic['d']='\u09A1'; phonetic['dh']='\u09A2'; phonetic['b']='\u09AC'; phonetic['bh']='\u09AD'; phonetic['v']='\u09AD'; phonetic['R']='\u09DC'; phonetic['Rh']='\u09DD'; phonetic['g']='\u0997'; phonetic['G']='\u0998'; phonetic['gh']='\u0998'; phonetic['h']='\u09B9'; phonetic['NG']='\u099E'; phonetic['j']='\u099C'; phonetic['J']='\u099D'; phonetic['jh']='\u099D'; phonetic['c']='\u099A'; phonetic['ch']='\u099B'; phonetic['C']='\u099B'; phonetic['th']='\u09A0'; phonetic['p']='\u09AA'; phonetic['f']='\u09AB'; phonetic['ph']='\u09AB'; phonetic['D']='\u09A6'; phonetic['Dh']='\u09A7'; phonetic['z']='\u09AF'; phonetic['y']='\u09DF'; phonetic['Ng']='\u0999'; phonetic['ng']='\u0982'; phonetic['l']='\u09B2'; phonetic['m']='\u09AE'; phonetic['sh']='\u09B6'; phonetic['S']='\u09B7'; phonetic['O']='\u0993'; phonetic['ou']='\u099C'; phonetic['OU']='\u0994'; phonetic['Ou']='\u0994'; phonetic['Oi']='\u0990'; phonetic['OI']='\u0990'; phonetic['tt']='\u09CE'; phonetic['H']='\u0983'; phonetic["."]="\u0964"; phonetic[".."]="."; phonetic['HH']='\u09CD'+'\u200c'; phonetic['NN']='\u0981'; phonetic['Y']='\u09CD'+'\u09AF'; phonetic['w']='\u09CD'+'\u09AC'; phonetic['W']='\u09C3'; phonetic['wr']='\u09C3'; phonetic['x']="\u0995"+'\u09CD'+'\u09B8'; phonetic['rY']=phonetic['r']+'\u200D'+'\u09CD'+'\u09AF'; phonetic['L']=phonetic['l']; phonetic['Z']=phonetic['z']; phonetic['P']=phonetic['p']; phonetic['V']=phonetic['v']; phonetic['B']=phonetic['b']; phonetic['M']=phonetic['m']; phonetic['V']=phonetic['v']; phonetic['X']=phonetic['x']; phonetic['V']=phonetic['v']; phonetic['F']=phonetic['f']; phonetic['vowels']='aIiUuoiiouueEiEu'; var carry=''; var old_len=0; var ctrlPressed=false; var len_to_process_oi_kar=0; var first_letter=false; var carry2=""; isIE=document.all?1:0; var switched=true; function checkKeyDown(ev){ var e=(window.event)?event.keyCode:ev.which; if(e=='17'){ ctrlPressed=true; }else if(e==16)shift=true; } function checkKeyUp(ev){ var e=(window.event)?event.keyCode:ev.which; if(e=='17'){ ctrlPressed=false; } } function parsePhonetic(evnt){ var t=document.getElementById(activeta); var e=(window.event)?event.keyCode:evnt.which; if(e=='109'){ if(ctrlPressed){ switched=!switched; return true; } } if(switched)return true; if(ctrlPressed){ e=0; } if(shift){ var char_e=String.fromCharCode(e).toUpperCase(); shift=false; }else var char_e=String.fromCharCode(e); if(e==8||e==32){ carry=" "; old_len=1; return; } lastcarry=carry; carry+=""+char_e; if((phonetic['vowels'].indexOf(lastcarry)!=-1&&phonetic['vowels'].indexOf(char_e)!=-1)||(lastcarry==" "&&phonetic['vowels'].indexOf(char_e)!=-1)){ if(carry=='ii'||carry=='uu'){ carry=lastcarry+char_e; }else { char_e=char_e.toUpperCase(); carry=lastcarry+char_e; } } bangla=parsePhoneticCarry(carry); tempBangla=parsePhoneticCarry(char_e); if(tempBangla==".."||bangla==".."){ return false; } if(char_e=="+"||char_e=="="||char_e=="`"){ if(carry=="++"||carry=="=="||carry=="``"){ insertConjunction(char_e,old_len); old_len=1; return false; } insertAtCursor("\u09CD"); old_len=1; carry2=carry; carry=char_e; return false; }else if(old_len==0){ insertConjunction(bangla,1); old_len=1; return false; }else if(carry=="Ao"){ insertConjunction(parsePhoneticCarry("ao"),old_len); old_len=1; return false; }else if(carry=="ii"){ insertConjunction(phonetic['ii'],1); old_len=1; return false; }else if(carry=="oI"){ insertConjunction('\u09C8',old_len); old_len=1; return false; }else if(char_e=="o"){ old_len=1; insertAtCursor('\u09CB'); carry="o"; return false; }else if(carry=="oU"){ insertConjunction("\u09CC",old_len); old_len=1; return false; }else if((bangla==""&&tempBangla!="")){ bangla=tempBangla; if(bangla==""){ carry=""; return; }else { carry=char_e; insertAtCursor(bangla); old_len=bangla.length; return false; } }else if(bangla!=""){ insertConjunction(bangla,old_len); old_len=bangla.length; return false; } } function parsePhoneticCarry(code){ if(!phonetic[code]){ return''; }else { return(phonetic[code]); } } function insertAtCursor(myValue){ var myField=document.getElementById(activeta); if(document.selection){ myField.focus(); sel=document.selection.createRange(); sel.text=myValue; sel.collapse(true); sel.select(); }else if(myField.selectionStart||myField.selectionStart==0){ var startPos=myField.selectionStart; var endPos=myField.selectionEnd; var scrollTop=myField.scrollTop; startPos=(startPos==-1?myField.value.length:startPos); myField.value=myField.value.substring(0,startPos)+myValue +myField.value.substring(endPos,myField.value.length); myField.focus(); myField.selectionStart=startPos+myValue.length; myField.selectionEnd=startPos+myValue.length; myField.scrollTop=scrollTop; }else{ var scrollTop=myField.scrollTop; myField.value+=myValue; myField.focus(); myField.scrollTop=scrollTop; } } function insertConjunction(myValue,len){ var myField=document.getElementById(activeta); if(document.selection){ myField.focus(); sel=document.selection.createRange(); if(myField.value.length>=len){ sel.moveStart('character',-1*(len)); } sel.text=myValue; sel.collapse(true); sel.select(); }else if(myField.selectionStart||myField.selectionStart==0){ myField.focus(); var startPos=myField.selectionStart-len; var endPos=myField.selectionEnd; var scrollTop=myField.scrollTop; startPos=(startPos==-1?myField.value.length:startPos); myField.value=myField.value.substring(0,startPos)+myValue +myField.value.substring(endPos,myField.value.length); myField.focus(); myField.selectionStart=startPos+myValue.length; myField.selectionEnd=startPos+myValue.length; myField.scrollTop=scrollTop; }else{ var scrollTop=myField.scrollTop; myField.value+=myValue; myField.focus(); myField.scrollTop=scrollTop; } } function makePhoneticEditor(textAreaId){ activeTextAreaInstance=document.getElementById(textAreaId); activeTextAreaInstance.onkeypress=parsePhonetic; activeTextAreaInstance.onkeydown=checkKeyDown; activeTextAreaInstance.onkeyup=checkKeyUp; activeTextAreaInstance.onfocus=function(){ activeta=textAreaId; }; } function makeVirtualEditor(textAreaId){ activeTextAreaInstance=document.getElementById(textAreaId); activeTextAreaInstance.onfocus=function(){ activeta=textAreaId; }; }
JavaScript
/***************************************************************** typeface.js, version 0.15 | typefacejs.neocracy.org Copyright (c) 2008 - 2009, David Chester davidchester@gmx.net Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************/ (function() { var _typeface_js = { faces: {}, loadFace: function(typefaceData) { var familyName = typefaceData.familyName.toLowerCase(); if (!this.faces[familyName]) { this.faces[familyName] = {}; } if (!this.faces[familyName][typefaceData.cssFontWeight]) { this.faces[familyName][typefaceData.cssFontWeight] = {}; } var face = this.faces[familyName][typefaceData.cssFontWeight][typefaceData.cssFontStyle] = typefaceData; face.loaded = true; }, log: function(message) { if (this.quiet) { return; } message = "typeface.js: " + message; if (this.customLogFn) { this.customLogFn(message); } else if (window.console && window.console.log) { window.console.log(message); } }, pixelsFromPoints: function(face, style, points, dimension) { var pixels = points * parseInt(style.fontSize) * 72 / (face.resolution * 100); if (dimension == 'horizontal' && style.fontStretchPercent) { pixels *= style.fontStretchPercent; } return pixels; }, pointsFromPixels: function(face, style, pixels, dimension) { var points = pixels * face.resolution / (parseInt(style.fontSize) * 72 / 100); if (dimension == 'horizontal' && style.fontStretchPrecent) { points *= style.fontStretchPercent; } return points; }, cssFontWeightMap: { normal: 'normal', bold: 'bold', 400: 'normal', 700: 'bold' }, cssFontStretchMap: { 'ultra-condensed': 0.55, 'extra-condensed': 0.77, 'condensed': 0.85, 'semi-condensed': 0.93, 'normal': 1, 'semi-expanded': 1.07, 'expanded': 1.15, 'extra-expanded': 1.23, 'ultra-expanded': 1.45, 'default': 1 }, fallbackCharacter: '.', configure: function(args) { var configurableOptionNames = [ 'customLogFn', 'customClassNameRegex', 'customTypefaceElementsList', 'quiet', 'verbose', 'disableSelection' ]; for (var i = 0; i < configurableOptionNames.length; i++) { var optionName = configurableOptionNames[i]; if (args[optionName]) { if (optionName == 'customLogFn') { if (typeof args[optionName] != 'function') { throw "customLogFn is not a function"; } else { this.customLogFn = args.customLogFn; } } else { this[optionName] = args[optionName]; } } } }, getTextExtents: function(face, style, text) { var extentX = 0; var extentY = 0; var horizontalAdvance; var textLength = text.length; for (var i = 0; i < textLength; i++) { var glyph = face.glyphs[text.charAt(i)] ? face.glyphs[text.charAt(i)] : face.glyphs[this.fallbackCharacter]; var letterSpacingAdjustment = this.pointsFromPixels(face, style, style.letterSpacing); // if we're on the last character, go with the glyph extent if that's more than the horizontal advance extentX += i + 1 == textLength ? Math.max(glyph.x_max, glyph.ha) : glyph.ha; extentX += letterSpacingAdjustment; horizontalAdvance += glyph.ha + letterSpacingAdjustment; } return { x: extentX, y: extentY, ha: horizontalAdvance }; }, pixelsFromCssAmount: function(cssAmount, defaultValue, element) { var matches = undefined; if (cssAmount == 'normal') { return defaultValue; } else if (matches = cssAmount.match(/([\-\d+\.]+)px/)) { return matches[1]; } else { // thanks to Dean Edwards for this very sneaky way to get IE to convert // relative values to pixel values var pixelAmount; var leftInlineStyle = element.style.left; var leftRuntimeStyle = element.runtimeStyle.left; element.runtimeStyle.left = element.currentStyle.left; if (!cssAmount.match(/\d(px|pt)$/)) { element.style.left = '1em'; } else { element.style.left = cssAmount || 0; } pixelAmount = element.style.pixelLeft; element.style.left = leftInlineStyle; element.runtimeStyle.left = leftRuntimeStyle; return pixelAmount || defaultValue; } }, capitalizeText: function(text) { return text.replace(/(^|\s)[a-z]/g, function(match) { return match.toUpperCase() } ); }, getElementStyle: function(e) { if (window.getComputedStyle) { return window.getComputedStyle(e, ''); } else if (e.currentStyle) { return e.currentStyle; } }, getRenderedText: function(e) { var browserStyle = this.getElementStyle(e.parentNode); var inlineStyleAttribute = e.parentNode.getAttribute('style'); if (inlineStyleAttribute && typeof(inlineStyleAttribute) == 'object') { inlineStyleAttribute = inlineStyleAttribute.cssText; } if (inlineStyleAttribute) { var inlineStyleDeclarations = inlineStyleAttribute.split(/\s*\;\s*/); var inlineStyle = {}; for (var i = 0; i < inlineStyleDeclarations.length; i++) { var declaration = inlineStyleDeclarations[i]; var declarationOperands = declaration.split(/\s*\:\s*/); inlineStyle[declarationOperands[0]] = declarationOperands[1]; } } var style = { color: browserStyle.color, fontFamily: browserStyle.fontFamily.split(/\s*,\s*/)[0].replace(/(^"|^'|'$|"$)/g, '').toLowerCase(), fontSize: this.pixelsFromCssAmount(browserStyle.fontSize, 12, e.parentNode), fontWeight: this.cssFontWeightMap[browserStyle.fontWeight], fontStyle: browserStyle.fontStyle ? browserStyle.fontStyle : 'normal', fontStretchPercent: this.cssFontStretchMap[inlineStyle && inlineStyle['font-stretch'] ? inlineStyle['font-stretch'] : 'default'], textDecoration: browserStyle.textDecoration, lineHeight: this.pixelsFromCssAmount(browserStyle.lineHeight, 'normal', e.parentNode), letterSpacing: this.pixelsFromCssAmount(browserStyle.letterSpacing, 0, e.parentNode), textTransform: browserStyle.textTransform }; var face; if ( this.faces[style.fontFamily] && this.faces[style.fontFamily][style.fontWeight] ) { face = this.faces[style.fontFamily][style.fontWeight][style.fontStyle]; } var text = e.nodeValue; if ( e.previousSibling && e.previousSibling.nodeType == 1 && e.previousSibling.tagName != 'BR' && this.getElementStyle(e.previousSibling).display.match(/inline/) ) { text = text.replace(/^\s+/, ' '); } else { text = text.replace(/^\s+/, ''); } if ( e.nextSibling && e.nextSibling.nodeType == 1 && e.nextSibling.tagName != 'BR' && this.getElementStyle(e.nextSibling).display.match(/inline/) ) { text = text.replace(/\s+$/, ' '); } else { text = text.replace(/\s+$/, ''); } text = text.replace(/\s+/g, ' '); if (style.textTransform && style.textTransform != 'none') { switch (style.textTransform) { case 'capitalize': text = this.capitalizeText(text); break; case 'uppercase': text = text.toUpperCase(); break; case 'lowercase': text = text.toLowerCase(); break; } } if (!face) { var excerptLength = 12; var textExcerpt = text.substring(0, excerptLength); if (text.length > excerptLength) { textExcerpt += '...'; } var fontDescription = style.fontFamily; if (style.fontWeight != 'normal') fontDescription += ' ' + style.fontWeight; if (style.fontStyle != 'normal') fontDescription += ' ' + style.fontStyle; this.log("couldn't find typeface font: " + fontDescription + ' for text "' + textExcerpt + '"'); return; } var words = text.split(/\b(?=\w)/); var containerSpan = document.createElement('span'); containerSpan.className = 'typeface-js-vector-container'; var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { var word = words[i]; var vector = this.renderWord(face, style, word); if (vector) { containerSpan.appendChild(vector.element); if (!this.disableSelection) { var selectableSpan = document.createElement('span'); selectableSpan.className = 'typeface-js-selected-text'; var wordNode = document.createTextNode(word); selectableSpan.appendChild(wordNode); if (this.vectorBackend != 'vml') { selectableSpan.style.marginLeft = -1 * (vector.width + 1) + 'px'; } selectableSpan.targetWidth = vector.width; //selectableSpan.style.lineHeight = 1 + 'px'; if (this.vectorBackend == 'vml') { vector.element.appendChild(selectableSpan); } else { containerSpan.appendChild(selectableSpan); } } } } return containerSpan; }, renderDocument: function(callback) { if (!callback) callback = function(e) { e.style.visibility = 'visible' }; var elements = document.getElementsByTagName('*'); var elementsLength = elements.length; for (var i = 0; i < elements.length; i++) { if (elements[i].className.match(/(^|\s)typeface-js(\s|$)/) || elements[i].tagName.match(/^(H1|H2|H3|H4|H5|H6)$/)) { this.replaceText(elements[i]); if (typeof callback == 'function') { callback(elements[i]); } } } if (this.vectorBackend == 'vml') { // lamely work around IE's quirky leaving off final dynamic shapes var dummyShape = document.createElement('v:shape'); dummyShape.style.display = 'none'; document.body.appendChild(dummyShape); } }, replaceText: function(e) { var childNodes = []; var childNodesLength = e.childNodes.length; for (var i = 0; i < childNodesLength; i++) { this.replaceText(e.childNodes[i]); } if (e.nodeType == 3 && e.nodeValue.match(/\S/)) { var parentNode = e.parentNode; if (parentNode.className == 'typeface-js-selected-text') { return; } var renderedText = this.getRenderedText(e); if ( parentNode.tagName == 'A' && this.vectorBackend == 'vml' && this.getElementStyle(parentNode).display == 'inline' ) { // something of a hack, use inline-block to get IE to accept clicks in whitespace regions parentNode.style.display = 'inline-block'; parentNode.style.cursor = 'pointer'; } if (this.getElementStyle(parentNode).display == 'inline') { parentNode.style.display = 'inline-block'; } if (renderedText) { if (parentNode.replaceChild) { parentNode.replaceChild(renderedText, e); } else { parentNode.insertBefore(renderedText, e); parentNode.removeChild(e); } if (this.vectorBackend == 'vml') { renderedText.innerHTML = renderedText.innerHTML; } var childNodesLength = renderedText.childNodes.length for (var i; i < childNodesLength; i++) { // do our best to line up selectable text with rendered text var e = renderedText.childNodes[i]; if (e.hasChildNodes() && !e.targetWidth) { e = e.childNodes[0]; } if (e && e.targetWidth) { var letterSpacingCount = e.innerHTML.length; var wordSpaceDelta = e.targetWidth - e.offsetWidth; var letterSpacing = wordSpaceDelta / (letterSpacingCount || 1); if (this.vectorBackend == 'vml') { letterSpacing = Math.ceil(letterSpacing); } e.style.letterSpacing = letterSpacing + 'px'; e.style.width = e.targetWidth + 'px'; } } } } }, applyElementVerticalMetrics: function(face, style, e) { if (style.lineHeight == 'normal') { style.lineHeight = this.pixelsFromPoints(face, style, face.lineHeight); } var cssLineHeightAdjustment = style.lineHeight - this.pixelsFromPoints(face, style, face.lineHeight); e.style.marginTop = Math.round( cssLineHeightAdjustment / 2 ) + 'px'; e.style.marginBottom = Math.round( cssLineHeightAdjustment / 2) + 'px'; }, vectorBackends: { canvas: { _initializeSurface: function(face, style, text) { var extents = this.getTextExtents(face, style, text); var canvas = document.createElement('canvas'); if (this.disableSelection) { canvas.innerHTML = text; } canvas.height = Math.round(this.pixelsFromPoints(face, style, face.lineHeight)); canvas.width = Math.round(this.pixelsFromPoints(face, style, extents.x, 'horizontal')); this.applyElementVerticalMetrics(face, style, canvas); if (extents.x > extents.ha) canvas.style.marginRight = Math.round(this.pixelsFromPoints(face, style, extents.x - extents.ha, 'horizontal')) + 'px'; var ctx = canvas.getContext('2d'); var pointScale = this.pixelsFromPoints(face, style, 1); ctx.scale(pointScale * style.fontStretchPercent, -1 * pointScale); ctx.translate(0, -1 * face.ascender); ctx.fillStyle = style.color; return { context: ctx, canvas: canvas }; }, _renderGlyph: function(ctx, face, char, style) { var glyph = face.glyphs[char]; if (!glyph) { //this.log.error("glyph not defined: " + char); return this.renderGlyph(ctx, face, this.fallbackCharacter, style); } if (glyph.o) { var outline; if (glyph.cached_outline) { outline = glyph.cached_outline; } else { outline = glyph.o.split(' '); glyph.cached_outline = outline; } var outlineLength = outline.length; for (var i = 0; i < outlineLength; ) { var action = outline[i++]; switch(action) { case 'm': ctx.moveTo(outline[i++], outline[i++]); break; case 'l': ctx.lineTo(outline[i++], outline[i++]); break; case 'q': var cpx = outline[i++]; var cpy = outline[i++]; ctx.quadraticCurveTo(outline[i++], outline[i++], cpx, cpy); break; case 'b': var x = outline[i++]; var y = outline[i++]; ctx.bezierCurveTo(outline[i++], outline[i++], outline[i++], outline[i++], x, y); break; } } } if (glyph.ha) { var letterSpacingPoints = style.letterSpacing && style.letterSpacing != 'normal' ? this.pointsFromPixels(face, style, style.letterSpacing) : 0; ctx.translate(glyph.ha + letterSpacingPoints, 0); } }, _renderWord: function(face, style, text) { var surface = this.initializeSurface(face, style, text); var ctx = surface.context; var canvas = surface.canvas; ctx.beginPath(); ctx.save(); var chars = text.split(''); var charsLength = chars.length; for (var i = 0; i < charsLength; i++) { this.renderGlyph(ctx, face, chars[i], style); } ctx.fill(); if (style.textDecoration == 'underline') { ctx.beginPath(); ctx.moveTo(0, face.underlinePosition); ctx.restore(); ctx.lineTo(0, face.underlinePosition); ctx.strokeStyle = style.color; ctx.lineWidth = face.underlineThickness; ctx.stroke(); } return { element: ctx.canvas, width: Math.floor(canvas.width) }; } }, vml: { _initializeSurface: function(face, style, text) { var shape = document.createElement('v:shape'); var extents = this.getTextExtents(face, style, text); shape.style.width = shape.style.height = style.fontSize + 'px'; shape.style.marginLeft = '-1px'; // this seems suspect... if (extents.x > extents.ha) { shape.style.marginRight = this.pixelsFromPoints(face, style, extents.x - extents.ha, 'horizontal') + 'px'; } this.applyElementVerticalMetrics(face, style, shape); var resolutionScale = face.resolution * 100 / 72; shape.coordsize = (resolutionScale / style.fontStretchPercent) + "," + resolutionScale; shape.coordorigin = '0,' + face.ascender; shape.style.flip = 'y'; shape.fillColor = style.color; shape.stroked = false; shape.path = 'hh m 0,' + face.ascender + ' l 0,' + face.descender + ' '; return shape; }, _renderGlyph: function(shape, face, char, offsetX, style, vmlSegments) { var glyph = face.glyphs[char]; if (!glyph) { this.log("glyph not defined: " + char); this.renderGlyph(shape, face, this.fallbackCharacter, offsetX, style); return; } vmlSegments.push('m'); if (glyph.o) { var outline, outlineLength; if (glyph.cached_outline) { outline = glyph.cached_outline; outlineLength = outline.length; } else { outline = glyph.o.split(' '); outlineLength = outline.length; for (var i = 0; i < outlineLength;) { switch(outline[i++]) { case 'q': outline[i] = Math.round(outline[i++]); outline[i] = Math.round(outline[i++]); case 'm': case 'l': outline[i] = Math.round(outline[i++]); outline[i] = Math.round(outline[i++]); break; } } glyph.cached_outline = outline; } var prevX, prevY; for (var i = 0; i < outlineLength;) { var action = outline[i++]; var x = Math.round(outline[i++]) + offsetX; var y = Math.round(outline[i++]); switch(action) { case 'm': vmlSegments.push('xm ', x, ',', y); break; case 'l': vmlSegments.push('l ', x, ',', y); break; case 'q': var cpx = outline[i++] + offsetX; var cpy = outline[i++]; var cp1x = Math.round(prevX + 2.0 / 3.0 * (cpx - prevX)); var cp1y = Math.round(prevY + 2.0 / 3.0 * (cpy - prevY)); var cp2x = Math.round(cp1x + (x - prevX) / 3.0); var cp2y = Math.round(cp1y + (y - prevY) / 3.0); vmlSegments.push('c ', cp1x, ',', cp1y, ',', cp2x, ',', cp2y, ',', x, ',', y); break; case 'b': var cp1x = Math.round(outline[i++]) + offsetX; var cp1y = outline[i++]; var cp2x = Math.round(outline[i++]) + offsetX; var cp2y = outline[i++]; vmlSegments.push('c ', cp1x, ',', cp1y, ',', cp2x, ',', cp2y, ',', x, ',', y); break; } prevX = x; prevY = y; } } vmlSegments.push('x e'); return vmlSegments; }, _renderWord: function(face, style, text) { var offsetX = 0; var shape = this.initializeSurface(face, style, text); var letterSpacingPoints = style.letterSpacing && style.letterSpacing != 'normal' ? this.pointsFromPixels(face, style, style.letterSpacing) : 0; letterSpacingPoints = Math.round(letterSpacingPoints); var chars = text.split(''); var vmlSegments = []; for (var i = 0; i < chars.length; i++) { var char = chars[i]; vmlSegments = this.renderGlyph(shape, face, char, offsetX, style, vmlSegments); offsetX += face.glyphs[char].ha + letterSpacingPoints ; } if (style.textDecoration == 'underline') { var posY = face.underlinePosition - (face.underlineThickness / 2); vmlSegments.push('xm ', 0, ',', posY); vmlSegments.push('l ', offsetX, ',', posY); vmlSegments.push('l ', offsetX, ',', posY + face.underlineThickness); vmlSegments.push('l ', 0, ',', posY + face.underlineThickness); vmlSegments.push('l ', 0, ',', posY); vmlSegments.push('x e'); } // make sure to preserve trailing whitespace shape.path += vmlSegments.join('') + 'm ' + offsetX + ' 0 l ' + offsetX + ' ' + face.ascender; return { element: shape, width: Math.floor(this.pixelsFromPoints(face, style, offsetX, 'horizontal')) }; } } }, setVectorBackend: function(backend) { this.vectorBackend = backend; var backendFunctions = ['renderWord', 'initializeSurface', 'renderGlyph']; for (var i = 0; i < backendFunctions.length; i++) { var backendFunction = backendFunctions[i]; this[backendFunction] = this.vectorBackends[backend]['_' + backendFunction]; } }, initialize: function() { // quit if this function has already been called if (arguments.callee.done) return; // flag this function so we don't do the same thing twice arguments.callee.done = true; // kill the timer if (window._typefaceTimer) clearInterval(_typefaceTimer); this.renderDocument( function(e) { e.style.visibility = 'visible' } ); } }; // IE won't accept real selectors... var typefaceSelectors = ['.typeface-js', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']; if (document.createStyleSheet) { var styleSheet = document.createStyleSheet(); for (var i = 0; i < typefaceSelectors.length; i++) { var selector = typefaceSelectors[i]; styleSheet.addRule(selector, 'visibility: hidden'); } styleSheet.addRule( '.typeface-js-selected-text', '-ms-filter: \ "Chroma(color=black) \ progid:DXImageTransform.Microsoft.MaskFilter(Color=white) \ progid:DXImageTransform.Microsoft.MaskFilter(Color=blue) \ alpha(opacity=30)" !important; \ color: black; \ font-family: Modern; \ position: absolute; \ white-space: pre; \ filter: alpha(opacity=0) !important;' ); styleSheet.addRule( '.typeface-js-vector-container', 'position: relative' ); } else if (document.styleSheets) { if (!document.styleSheets.length) { (function() { // create a stylesheet if we need to var styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(styleSheet); })() } var styleSheet = document.styleSheets[0]; document.styleSheets[0].insertRule(typefaceSelectors.join(',') + ' { visibility: hidden; }', styleSheet.cssRules.length); document.styleSheets[0].insertRule( '.typeface-js-selected-text { \ color: rgba(128, 128, 128, 0); \ opacity: 0.30; \ position: absolute; \ font-family: Arial, sans-serif; \ white-space: pre \ }', styleSheet.cssRules.length ); try { // set selection style for Mozilla / Firefox document.styleSheets[0].insertRule( '.typeface-js-selected-text::-moz-selection { background: blue; }', styleSheet.cssRules.length ); } catch(e) {}; try { // set styles for browsers with CSS3 selectors (Safari, Chrome) document.styleSheets[0].insertRule( '.typeface-js-selected-text::selection { background: blue; }', styleSheet.cssRules.length ); } catch(e) {}; // most unfortunately, sniff for WebKit's quirky selection behavior if (/WebKit/i.test(navigator.userAgent)) { document.styleSheets[0].insertRule( '.typeface-js-vector-container { position: relative }', styleSheet.cssRules.length ); } } var backend = window.CanvasRenderingContext2D || document.createElement('canvas').getContext ? 'canvas' : !!(window.attachEvent && !window.opera) ? 'vml' : null; if (backend == 'vml') { document.namespaces.add("v","urn:schemas-microsoft-com:vml","#default#VML"); var styleSheet = document.createStyleSheet(); styleSheet.addRule('v\\:shape', "display: inline-block;"); } _typeface_js.setVectorBackend(backend); window._typeface_js = _typeface_js; if (/WebKit/i.test(navigator.userAgent)) { var _typefaceTimer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) { _typeface_js.initialize(); } }, 10); } if (document.addEventListener) { window.addEventListener('DOMContentLoaded', function() { _typeface_js.initialize() }, false); } /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload_typeface defer src=//:><\/script>"); var script = document.getElementById("__ie_onload_typeface"); script.onreadystatechange = function() { if (this.readyState == "complete") { _typeface_js.initialize(); } }; /*@end @*/ try { console.log('initializing typeface.js') } catch(e) {}; })();
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ alert("hello");
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ alert("hello"); /* কক কট কত */
JavaScript
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * * The lexer should work on a number of languages including C and friends, * Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles. * It works passably on Ruby, PHP and Awk and a decent subset of Perl, but, * because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or * CAML-like languages. * * If there's a language not mentioned here, then I don't know it, and don't * know whether it works. If it has a C-like, Bash-like, or XML-like syntax * then it should work passably. * * Usage: * 1) include this source file in an html page via * <script type="text/javascript" src="/path/to/prettify.js"></script> * 2) define style rules. See the example page for examples. * 3) mark the <pre> and <code> tags in your source with class=prettyprint. * You can also use the (html deprecated) <xmp> tag, but the pretty printer * needs to do more substantial DOM manipulations to support that, so some * css styles may not be preserved. * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in. * * Change log: * cbeust, 2006/08/22 * Java annotations (start with "@") are now captured as literals ("lit") */ // JSLint declarations /*global console, document, navigator, setTimeout, window */ /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ var PR_SHOULD_USE_CONTINUATION = true; /** the number of characters between tab columns */ var PR_TAB_WIDTH = 8; /** Walks the DOM returning a properly escaped version of innerHTML. * @param {Node} node * @param {Array.<string>} out output buffer that receives chunks of HTML. */ var PR_normalizedHtml; /** Contains functions for creating and registering new language handlers. * @type {Object} */ var PR; /** Pretty print a chunk of code. * * @param {string} sourceCodeHtml code as html * @return {string} code as html, but prettier */ var prettyPrintOne; /** find all the < pre > and < code > tags in the DOM with class=prettyprint * and prettify them. * @param {Function} opt_whenDone if specified, called when the last entry * has been finished. */ var prettyPrint; /** browser detection. @extern */ function _pr_isIE6() { var isIE6 = navigator && navigator.userAgent && /\bMSIE 6\./.test(navigator.userAgent); _pr_isIE6 = function () { return isIE6; }; return isIE6; } (function () { /** Splits input on space and returns an Object mapping each non-empty part to * true. */ function wordSet(words) { words = words.split(/ /g); var set = {}; for (var i = words.length; --i >= 0;) { var w = words[i]; if (w) { set[w] = null; } } return set; } // Keyword lists for various languages. var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while "; var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " + "double enum extern float goto int long register short signed sizeof " + "static struct switch typedef union unsigned void volatile "; var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " + "new operator private protected public this throw true try "; var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " + "concept concept_map const_cast constexpr decltype " + "dynamic_cast explicit export friend inline late_check " + "mutable namespace nullptr reinterpret_cast static_assert static_cast " + "template typeid typename typeof using virtual wchar_t where "; var JAVA_KEYWORDS = COMMON_KEYWORDS + "boolean byte extends final finally implements import instanceof null " + "native package strictfp super synchronized throws transient "; var CSHARP_KEYWORDS = JAVA_KEYWORDS + "as base by checked decimal delegate descending event " + "fixed foreach from group implicit in interface internal into is lock " + "object out override orderby params readonly ref sbyte sealed " + "stackalloc string select uint ulong unchecked unsafe ushort var "; var JSCRIPT_KEYWORDS = COMMON_KEYWORDS + "debugger eval export function get null set undefined var with " + "Infinity NaN "; var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " + "goto if import last local my next no our print package redo require " + "sub undef unless until use wantarray while BEGIN END "; var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " + "elif except exec finally from global import in is lambda " + "nonlocal not or pass print raise try with yield " + "False True None "; var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" + " defined elsif end ensure false in module next nil not or redo rescue " + "retry self super then true undef unless until when yield BEGIN END "; var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " + "function in local set then until "; var ALL_KEYWORDS = ( CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS); // token style names. correspond to css classes /** token style for a string literal */ var PR_STRING = 'str'; /** token style for a keyword */ var PR_KEYWORD = 'kwd'; /** token style for a comment */ var PR_COMMENT = 'com'; /** token style for a type */ var PR_TYPE = 'typ'; /** token style for a literal value. e.g. 1, null, true. */ var PR_LITERAL = 'lit'; /** token style for a punctuation string. */ var PR_PUNCTUATION = 'pun'; /** token style for a punctuation string. */ var PR_PLAIN = 'pln'; /** token style for an sgml tag. */ var PR_TAG = 'tag'; /** token style for a markup declaration such as a DOCTYPE. */ var PR_DECLARATION = 'dec'; /** token style for embedded source. */ var PR_SOURCE = 'src'; /** token style for an sgml attribute name. */ var PR_ATTRIB_NAME = 'atn'; /** token style for an sgml attribute value. */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. */ var PR_NOCODE = 'nocode'; function isWordChar(ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } /** Splice one array into another. * Like the python <code> * container[containerPosition:containerPosition + countReplaced] = inserted * </code> * @param {Array} inserted * @param {Array} container modified in place * @param {Number} containerPosition * @param {Number} countReplaced */ function spliceArrayInto( inserted, container, containerPosition, countReplaced) { inserted.unshift(containerPosition, countReplaced || 0); try { container.splice.apply(container, inserted); } finally { inserted.splice(0, 2); } } /** A set of tokens that can precede a regular expression literal in * javascript. * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full * list, but I've removed ones that might be problematic when seen in * languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * @private */ var REGEXP_PRECEDER_PATTERN = function () { var preceders = [ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=", "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===", ">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^", "^^=", "{", "|", "|=", "||", "||=", "~" /* handles =~ and !~ */, "break", "case", "continue", "delete", "do", "else", "finally", "instanceof", "return", "throw", "try", "typeof" ]; var pattern = '(?:' + '(?:(?:^|[^0-9.])\\.{1,3})|' + // a dot that's not part of a number '(?:(?:^|[^\\+])\\+)|' + // allow + but not ++ '(?:(?:^|[^\\-])-)'; // allow - but not -- for (var i = 0; i < preceders.length; ++i) { var preceder = preceders[i]; if (isWordChar(preceder.charAt(0))) { pattern += '|\\b' + preceder; } else { pattern += '|' + preceder.replace(/([^=<>:&])/g, '\\$1'); } } pattern += '|^)\\s*$'; // matches at end, and matches empty string return new RegExp(pattern); // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not // valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. }(); // Define regexps here so that the interpreter doesn't have to create an // object each time the function containing them is called. // The language spec requires a new object created even if you don't access // the $1 members. var pr_amp = /&/g; var pr_lt = /</g; var pr_gt = />/g; var pr_quot = /\"/g; /** like textToHtml but escapes double quotes to be attribute safe. */ function attribToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;') .replace(pr_quot, '&quot;'); } /** escapest html special characters to html. */ function textToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;'); } var pr_ltEnt = /&lt;/g; var pr_gtEnt = /&gt;/g; var pr_aposEnt = /&apos;/g; var pr_quotEnt = /&quot;/g; var pr_ampEnt = /&amp;/g; var pr_nbspEnt = /&nbsp;/g; /** unescapes html to plain text. */ function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } // Handle numeric entities specially. We can't use functional substitution // since that doesn't work in older versions of Safari. // These should be rare since most browsers convert them to normal chars. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<') .replace(pr_gtEnt, '>') .replace(pr_aposEnt, "'") .replace(pr_quotEnt, '"') .replace(pr_ampEnt, '&') .replace(pr_nbspEnt, ' '); } /** is the given node's innerHTML normally unescaped? */ function isRawContent(node) { return 'XMP' === node.tagName; } function normalizedHtml(node, out) { switch (node.nodeType) { case 1: // an element var name = node.tagName.toLowerCase(); out.push('<', name); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified) { continue; } out.push(' '); normalizedHtml(attr, out); } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 2: // an attribute out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"'); break; case 3: case 4: // text out.push(textToHtml(node.nodeValue)); break; } } var PR_innerHtmlWorks = null; function getInnerHtml(node) { // inner html is hopelessly broken in Safari 2.0.4 when the content is // an html description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild( document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); PR_innerHtmlWorks = !/</.test(testNode.innerHTML); } if (PR_innerHtmlWorks) { var content = node.innerHTML; // XMP tags contain unescaped entities so require special handling. if (isRawContent(node)) { content = textToHtml(content); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } /** returns a function that expand tabs to spaces. This function can be fed * successive chunks of text, and will maintain its own internal state to * keep track of how tabs are expanded. * @return {function (string) : string} a function that takes * plain text and return the text with tabs expanded. * @private */ function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function (plainText) { // walk over each character looking for tabs and newlines. // On tabs, expand them. On newlines, reset charInLine. // Otherwise increment charInLine var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); // calculate how much space we need in front of this part // nSpaces is the amount of padding -- the number of spaces needed // to move us to the next column, where columns occur at factors of // tabWidth. var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; } // The below pattern matches one of the following // (1) /[^<]+/ : A run of characters other than '<' // (2) /<!--.*?-->/: an HTML comment // (3) /<!\[CDATA\[.*?\]\]>/: a cdata section // (3) /<\/?[a-zA-Z][^>]*>/ : A probably tag that should not be highlighted // (4) /</ : A '<' that does not begin a larger chunk. Treated as 1 var pr_chunkPattern = /(?:[^<]+|<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g; var pr_commentPrefix = /^<!--/; var pr_cdataPrefix = /^<\[CDATA\[/; var pr_brPrefix = /^<br\b/i; var pr_tagNameRe = /^<(\/?)([a-zA-Z]+)/; /** split markup into chunks of html tags (style null) and * plain text (style {@link #PR_PLAIN}), converting tags which are * significant for tokenization (<br>) into their textual equivalent. * * @param {string} s html where whitespace is considered significant. * @return {Object} source code and extracted tags. * @private */ function extractTags(s) { // since the pattern has the 'g' modifier and defines no capturing groups, // this will return a list of all chunks which we then classify and wrap as // PR_Tokens var matches = s.match(pr_chunkPattern); var sourceBuf = []; var sourceBufLen = 0; var extractedTags = []; if (matches) { for (var i = 0, n = matches.length; i < n; ++i) { var match = matches[i]; if (match.length > 1 && match.charAt(0) === '<') { if (pr_commentPrefix.test(match)) { continue; } if (pr_cdataPrefix.test(match)) { // strip CDATA prefix and suffix. Don't unescape since it's CDATA sourceBuf.push(match.substring(9, match.length - 3)); sourceBufLen += match.length - 12; } else if (pr_brPrefix.test(match)) { // <br> tags are lexically significant so convert them to text. // This is undone later. sourceBuf.push('\n'); ++sourceBufLen; } else { if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) { // A <span class="nocode"> will start a section that should be // ignored. Continue walking the list until we see a matching end // tag. var name = match.match(pr_tagNameRe)[2]; var depth = 1; end_tag_loop: for (var j = i + 1; j < n; ++j) { var name2 = matches[j].match(pr_tagNameRe); if (name2 && name2[2] === name) { if (name2[1] === '/') { if (--depth === 0) { break end_tag_loop; } } else { ++depth; } } } if (j < n) { extractedTags.push( sourceBufLen, matches.slice(i, j + 1).join('')); i = j; } else { // Ignore unclosed sections. extractedTags.push(sourceBufLen, match); } } else { extractedTags.push(sourceBufLen, match); } } } else { var literalText = htmlToText(match); sourceBuf.push(literalText); sourceBufLen += literalText.length; } } } return { source: sourceBuf.join(''), tags: extractedTags }; } /** True if the given tag contains a class attribute with the nocode class. */ function isNoCodeTag(tag) { return !!tag // First canonicalize the representation of attributes .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' $1="$2$3$4"') // Then look for the attribute we want. .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/); } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, context : RegExp, shortcut : string]. & * Style is a style constant like PR_PLAIN. * * Pattern must only match prefixes, and if it matches a prefix and context * is null or matches the last non-comment token parsed, then that match is * considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (string, number?) : Array.<number|string>} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); for (var i = allPatterns.length; --i >= 0;) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } } })(); var nPatterns = fallthroughStylePatterns.length; var notWs = /\S/; return function (sourceCode, opt_basePos) { opt_basePos = opt_basePos || 0; var decorations = [opt_basePos, PR_PLAIN]; var lastToken = ''; var pos = 0; // index into sourceCode var tail = sourceCode; while (tail.length) { var style; var token = null; var match; var patternParts = shortcuts[tail.charAt(0)]; if (patternParts) { match = tail.match(patternParts[1]); token = match[0]; style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; var contextPattern = patternParts[2]; if (contextPattern && !contextPattern.test(lastToken)) { // rule can't be used continue; } match = tail.match(patternParts[1]); if (match) { token = match[0]; style = patternParts[0]; break; } } if (!token) { // make sure that we make progress style = PR_PLAIN; token = tail.substring(0, 1); } } decorations.push(opt_basePos + pos, style); pos += token.length; tail = tail.substring(token.length); if (style !== PR_COMMENT && notWs.test(token)) { lastToken = token; } } return decorations; }; } var PR_MARKUP_LEXER = createSimpleLexer([], [ [PR_PLAIN, /^[^<]+/, null], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/, null], [PR_COMMENT, /^<!--[\s\S]*?(?:-->|$)/, null], [PR_SOURCE, /^<\?[\s\S]*?(?:\?>|$)/, null], [PR_SOURCE, /^<%[\s\S]*?(?:%>|$)/, null], [PR_SOURCE, // Tags whose content is not escaped, and which contain source code. /^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i, null], [PR_TAG, /^<\/?\w[^<>]*>/, null] ]); // Splits any of the source|style|xmp entries above into a start tag, // source content, and end tag. var PR_SOURCE_CHUNK_PARTS = /^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/; /** split markup on tags, comments, application directives, and other top * level constructs. Tags are returned as a single token - attributes are * not yet broken out. * @private */ function tokenizeMarkup(source) { var decorations = PR_MARKUP_LEXER(source); for (var i = 0; i < decorations.length; i += 2) { if (decorations[i + 1] === PR_SOURCE) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; // Split out start and end script tags as actual tags, and leave the // body with style SCRIPT. var sourceChunk = source.substring(start, end); var match = sourceChunk.match(PR_SOURCE_CHUNK_PARTS); if (match) { decorations.splice( i, 2, start, PR_TAG, // the open chunk start + match[1].length, PR_SOURCE, start + match[1].length + (match[2] || '').length, PR_TAG); } } } return decorations; } var PR_TAG_LEXER = createSimpleLexer([ [PR_ATTRIB_VALUE, /^\'[^\']*(?:\'|$)/, null, "'"], [PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'], [PR_PUNCTUATION, /^[<>\/=]+/, null, '<>/='] ], [ [PR_TAG, /^[\w:\-]+/, /^</], [PR_ATTRIB_VALUE, /^[\w\-]+/, /^=/], [PR_ATTRIB_NAME, /^[\w:\-]+/, null], [PR_PLAIN, /^\s+/, null, ' \t\r\n'] ]); /** split tags attributes and their values out from the tag name, and * recursively lex source chunks. * @private */ function splitTagAttributes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_TAG) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var chunk = source.substring(start, end); var subDecorations = PR_TAG_LEXER(chunk, start); spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (string) : Array.<string|number>} a * decorator that takes sourceCode as plain text and that returns a * decoration list */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options.tripleQuotedStrings) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options.multiLineStrings) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } fallthroughStylePatterns.push( [PR_PLAIN, /^(?:[^\'\"\`\/\#]+)/, null, ' \r\n']); if (options.hashComments) { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } if (options.cStyleComments) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options.regexLiterals) { var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '^/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '(?:/|$)'); fallthroughStylePatterns.push( [PR_STRING, new RegExp(REGEX_LITERAL), REGEXP_PRECEDER_PATTERN]); } var keywords = wordSet(options.keywords); options = null; /** splits the given string into comment, string, and "other" tokens. * @param {string} sourceCode as plain text * @return {Array.<number|string>} a decoration list. * @private */ var splitStringAndCommentTokens = createSimpleLexer( shortcutStylePatterns, fallthroughStylePatterns); var styleLiteralIdentifierPuncRecognizer = createSimpleLexer([], [ [PR_PLAIN, /^\s+/, null, ' \r\n'], // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_PLAIN, /^[a-z_$@][a-z_$@0-9]*/i, null], // A hex number [PR_LITERAL, /^0x[a-f0-9]+[a-z]/i, null], // An octal or decimal number, possibly in scientific notation [PR_LITERAL, /^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i, null, '123456789'], [PR_PUNCTUATION, /^[^\s\w\.$@]+/, null] // Fallback will handle decimal points not adjacent to a digit ]); /** splits plain text tokens into more specific tokens, and then tries to * recognize keywords, and types. * @private */ function splitNonStringNonCommentTokens(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_PLAIN) { var start, end, chunk, subDecs; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; chunk = source.substring(start, end); subDecs = styleLiteralIdentifierPuncRecognizer(chunk, start); for (var j = 0, m = subDecs.length; j < m; j += 2) { var subStyle = subDecs[j + 1]; if (subStyle === PR_PLAIN) { var subStart = subDecs[j]; var subEnd = j + 2 < m ? subDecs[j + 2] : chunk.length; var token = source.substring(subStart, subEnd); if (token === '.') { subDecs[j + 1] = PR_PUNCTUATION; } else if (token in keywords) { subDecs[j + 1] = PR_KEYWORD; } else if (/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(token)) { // classify types and annotations using Java's style conventions subDecs[j + 1] = token.charAt(0) === '@' ? PR_LITERAL : PR_TYPE; } } } spliceArrayInto(subDecs, decorations, i, 2); i += subDecs.length - 2; } } return decorations; } return function (sourceCode) { // Split into strings, comments, and other. // We do this because strings and comments are easily recognizable and can // contain stuff that looks like other tokens, so we want to mark those // early so we don't recurse into them. var decorations = splitStringAndCommentTokens(sourceCode); // Split non comment|string tokens on whitespace and word boundaries decorations = splitNonStringNonCommentTokens(sourceCode, decorations); return decorations; }; } var decorateSource = sourceDecorator({ keywords: ALL_KEYWORDS, hashComments: true, cStyleComments: true, multiLineStrings: true, regexLiterals: true }); /** identify regions of markup that are really source code, and recursivley * lex them. * @private */ function splitSourceNodes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_SOURCE) { // Recurse using the non-markup lexer var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var subDecorations = decorateSource(source.substring(start, end)); for (var j = 0, m = subDecorations.length; j < m; j += 2) { subDecorations[j] += start; } spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } /** identify attribute values that really contain source code and recursively * lex them. * @private */ function splitSourceAttributes(source, decorations) { var nextValueIsSource = false; for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; var start, end; if (style === PR_ATTRIB_NAME) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; nextValueIsSource = /^on|^style$/i.test(source.substring(start, end)); } else if (style === PR_ATTRIB_VALUE) { if (nextValueIsSource) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var attribValue = source.substring(start, end); var attribLen = attribValue.length; var quoted = (attribLen >= 2 && /^[\"\']/.test(attribValue) && attribValue.charAt(0) === attribValue.charAt(attribLen - 1)); var attribSource; var attribSourceStart; var attribSourceEnd; if (quoted) { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue; } else { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue.substring(1, attribValue.length - 1); } var attribSourceDecorations = decorateSource(attribSource); for (var j = 0, m = attribSourceDecorations.length; j < m; j += 2) { attribSourceDecorations[j] += attribSourceStart; } if (quoted) { attribSourceDecorations.push(attribSourceEnd, PR_ATTRIB_VALUE); spliceArrayInto(attribSourceDecorations, decorations, i + 2, 0); } else { spliceArrayInto(attribSourceDecorations, decorations, i, 2); } } nextValueIsSource = false; } } return decorations; } /** returns a decoration list given a string of markup. * * This code recognizes a number of constructs. * <!-- ... --> comment * <!\w ... > declaration * <\w ... > tag * </\w ... > tag * <?...?> embedded source * <%...%> embedded source * &[#\w]...; entity * * It does not recognizes %foo; doctype entities from . * * It will recurse into any <style>, <script>, and on* attributes using * PR_lexSource. */ function decorateMarkup(sourceCode) { // This function works as follows: // 1) Start by splitting the markup into text and tag chunks // Input: string s // Output: List<PR_Token> where style in (PR_PLAIN, null) // 2) Then split the text chunks further into comments, declarations, // tags, etc. // After each split, consider whether the token is the start of an // embedded source section, i.e. is an open <script> tag. If it is, find // the corresponding close token, and don't bother to lex in between. // Input: List<string> // Output: List<PR_Token> with style in // (PR_TAG, PR_PLAIN, PR_SOURCE, null) // 3) Finally go over each tag token and split out attribute names and // values. // Input: List<PR_Token> // Output: List<PR_Token> where style in // (PR_TAG, PR_PLAIN, PR_SOURCE, NAME, VALUE, null) var decorations = tokenizeMarkup(sourceCode); decorations = splitTagAttributes(sourceCode, decorations); decorations = splitSourceNodes(sourceCode, decorations); decorations = splitSourceAttributes(sourceCode, decorations); return decorations; } /** * @param {string} sourceText plain text * @param {Array.<number|string>} extractedTags chunks of raw html preceded * by their position in sourceText in order. * @param {Array.<number|string>} decorations style classes preceded by their * position in sourceText in order. * @return {string} html * @private */ function recombineTagsAndDecorations(sourceText, extractedTags, decorations) { var html = []; // index past the last char in sourceText written to html var outputIdx = 0; var openDecoration = null; var currentDecoration = null; var tagPos = 0; // index into extractedTags var decPos = 0; // index into decorations var tabExpander = makeTabExpander(PR_TAB_WIDTH); var adjacentSpaceRe = /([\r\n ]) /g; var startOrSpaceRe = /(^| ) /gm; var newlineRe = /\r\n?|\n/g; var trailingSpaceRe = /[ \r\n]$/; var lastWasSpace = true; // the last text chunk emitted ended with a space. // A helper function that is responsible for opening sections of decoration // and outputing properly escaped chunks of source function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } // This interacts badly with some wikis which introduces paragraph tags // into pre blocks for some strange reason. // It's necessary for IE though which seems to lose the preformattedness // of <pre> tags when their innerHTML is assigned. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html // and it serves to undo the conversion of <br>s to newlines done in // chunkify. var htmlChunk = textToHtml( tabExpander(sourceText.substring(outputIdx, sourceIdx))) .replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&nbsp;'); // Keep track of whether we need to escape space at the beginning of the // next chunk. lastWasSpace = trailingSpaceRe.test(htmlChunk); html.push(htmlChunk.replace(newlineRe, '<br />')); outputIdx = sourceIdx; } } while (true) { // Determine if we're going to consume a tag this time around. Otherwise // we consume a decoration or exit. var outputTag; if (tagPos < extractedTags.length) { if (decPos < decorations.length) { // Pick one giving preference to extractedTags since we shouldn't open // a new style that we're going to have to immediately close in order // to output a tag. outputTag = extractedTags[tagPos] <= decorations[decPos]; } else { outputTag = true; } } else { outputTag = false; } // Consume either a decoration or a tag or exit. if (outputTag) { emitTextUpTo(extractedTags[tagPos]); if (openDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } html.push(extractedTags[tagPos + 1]); tagPos += 2; } else if (decPos < decorations.length) { emitTextUpTo(decorations[decPos]); currentDecoration = decorations[decPos + 1]; decPos += 2; } else { break; } } emitTextUpTo(sourceText.length); if (openDecoration) { html.push('</span>'); } return html.join(''); } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (string) : Array.<number|string>} handler * a function from source code to a list of decorations. * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if ('console' in window) { console.log('cannot override language handler %s', ext); } } } registerLangHandler(decorateSource, ['default-code']); registerLangHandler(decorateMarkup, ['default-markup', 'html', 'htm', 'xhtml', 'xml', 'xsl']); registerLangHandler(sourceDecorator({ keywords: CPP_KEYWORDS, hashComments: true, cStyleComments: true }), ['c', 'cc', 'cpp', 'cxx', 'cyc']); registerLangHandler(sourceDecorator({ keywords: CSHARP_KEYWORDS, hashComments: true, cStyleComments: true }), ['cs']); registerLangHandler(sourceDecorator({ keywords: JAVA_KEYWORDS, cStyleComments: true }), ['java']); registerLangHandler(sourceDecorator({ keywords: SH_KEYWORDS, hashComments: true, multiLineStrings: true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ keywords: PYTHON_KEYWORDS, hashComments: true, multiLineStrings: true, tripleQuotedStrings: true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ keywords: PERL_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ keywords: RUBY_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['rb']); registerLangHandler(sourceDecorator({ keywords: JSCRIPT_KEYWORDS, cStyleComments: true, regexLiterals: true }), ['js']); function prettyPrintOne(sourceCodeHtml, opt_langExtension) { try { // Extract tags, and convert the source code to plain text. var sourceAndExtractedTags = extractTags(sourceCodeHtml); /** Plain text. @type {string} */ var source = sourceAndExtractedTags.source; /** Even entries are positions in source in ascending order. Odd entries * are tags that were extracted at that position. * @type {Array.<number|string>} */ var extractedTags = sourceAndExtractedTags.tags; // Pick a lexer and apply it. if (!langHandlerRegistry.hasOwnProperty(opt_langExtension)) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. opt_langExtension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = langHandlerRegistry[opt_langExtension].call({}, source); // Integrate the decorations and tags back into the source code to produce // a decorated html string. return recombineTagsAndDecorations(source, extractedTags, decorations); } catch (e) { if ('console' in window) { console.log(e); console.trace(); } return sourceCodeHtml; } } function prettyPrint(opt_whenDone) { var isIE6 = _pr_isIE6(); // fetch a list of nodes to rewrite var codeSegments = [ document.getElementsByTagName('pre'), document.getElementsByTagName('code'), document.getElementsByTagName('xmp') ]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0; j < codeSegments[i].length; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; // the loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; function doWork() { var endTime = (PR_SHOULD_USE_CONTINUATION ? new Date().getTime() + 250 /* ms */ : Infinity); for (; k < elements.length && new Date().getTime() < endTime; k++) { var cs = elements[k]; if (cs.className && cs.className.indexOf('prettyprint') >= 0) { // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler as // passed to PR_registerLangHandler. var langExtension = cs.className.match(/\blang-(\w+)\b/); if (langExtension) { langExtension = langExtension[1]; } // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp') && p.className && p.className.indexOf('prettyprint') >= 0) { nested = true; break; } } if (!nested) { // fetch the content as a snippet of properly escaped HTML. // Firefox adds newlines at the end. var content = getInnerHtml(cs); content = content.replace(/(?:\r\n?|\n)$/, ''); // do the pretty printing var newContent = prettyPrintOne(content, langExtension); // push the prettified html back into the tag. if (!isRawContent(cs)) { // just replace the old html with the new cs.innerHTML = newContent; } else { // we need to change the tag to a <pre> since <xmp>s do not allow // embedded tags such as the span tags used to attach styles to // sections of source code. var pre = document.createElement('PRE'); for (var i = 0; i < cs.attributes.length; ++i) { var a = cs.attributes[i]; if (a.specified) { var aname = a.name.toLowerCase(); if (aname === 'class') { pre.className = a.value; // For IE 6 } else { pre.setAttribute(a.name, a.value); } } } pre.innerHTML = newContent; // remove the old cs.parentNode.replaceChild(pre, cs); cs = pre; } // Replace <br>s with line-feeds so that copying and pasting works // on IE 6. // Doing this on other browsers breaks lots of stuff since \r\n is // treated as two newlines on Firefox, and doing this also slows // down rendering. if (isIE6 && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( document.createTextNode('\r\n'), lineBreak); } } } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } doWork(); } window['PR_normalizedHtml'] = normalizedHtml; window['prettyPrintOne'] = prettyPrintOne; window['prettyPrint'] = prettyPrint; window['PR'] = { 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE }; })();
JavaScript
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * * The lexer should work on a number of languages including C and friends, * Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles. * It works passably on Ruby, PHP and Awk and a decent subset of Perl, but, * because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or * CAML-like languages. * * If there's a language not mentioned here, then I don't know it, and don't * know whether it works. If it has a C-like, Bash-like, or XML-like syntax * then it should work passably. * * Usage: * 1) include this source file in an html page via * <script type="text/javascript" src="/path/to/prettify.js"></script> * 2) define style rules. See the example page for examples. * 3) mark the <pre> and <code> tags in your source with class=prettyprint. * You can also use the (html deprecated) <xmp> tag, but the pretty printer * needs to do more substantial DOM manipulations to support that, so some * css styles may not be preserved. * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in. * * Change log: * cbeust, 2006/08/22 * Java annotations (start with "@") are now captured as literals ("lit") */ // JSLint declarations /*global console, document, navigator, setTimeout, window */ /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ var PR_SHOULD_USE_CONTINUATION = true; /** the number of characters between tab columns */ var PR_TAB_WIDTH = 8; /** Walks the DOM returning a properly escaped version of innerHTML. * @param {Node} node * @param {Array.<string>} out output buffer that receives chunks of HTML. */ var PR_normalizedHtml; /** Contains functions for creating and registering new language handlers. * @type {Object} */ var PR; /** Pretty print a chunk of code. * * @param {string} sourceCodeHtml code as html * @return {string} code as html, but prettier */ var prettyPrintOne; /** find all the < pre > and < code > tags in the DOM with class=prettyprint * and prettify them. * @param {Function} opt_whenDone if specified, called when the last entry * has been finished. */ var prettyPrint; /** browser detection. @extern */ function _pr_isIE6() { var isIE6 = navigator && navigator.userAgent && /\bMSIE 6\./.test(navigator.userAgent); _pr_isIE6 = function () { return isIE6; }; return isIE6; } (function () { /** Splits input on space and returns an Object mapping each non-empty part to * true. */ function wordSet(words) { words = words.split(/ /g); var set = {}; for (var i = words.length; --i >= 0;) { var w = words[i]; if (w) { set[w] = null; } } return set; } // Keyword lists for various languages. var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while "; var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " + "double enum extern float goto int long register short signed sizeof " + "static struct switch typedef union unsigned void volatile "; var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " + "new operator private protected public this throw true try "; var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " + "concept concept_map const_cast constexpr decltype " + "dynamic_cast explicit export friend inline late_check " + "mutable namespace nullptr reinterpret_cast static_assert static_cast " + "template typeid typename typeof using virtual wchar_t where "; var JAVA_KEYWORDS = COMMON_KEYWORDS + "boolean byte extends final finally implements import instanceof null " + "native package strictfp super synchronized throws transient "; var CSHARP_KEYWORDS = JAVA_KEYWORDS + "as base by checked decimal delegate descending event " + "fixed foreach from group implicit in interface internal into is lock " + "object out override orderby params readonly ref sbyte sealed " + "stackalloc string select uint ulong unchecked unsafe ushort var "; var JSCRIPT_KEYWORDS = COMMON_KEYWORDS + "debugger eval export function get null set undefined var with " + "Infinity NaN "; var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " + "goto if import last local my next no our print package redo require " + "sub undef unless until use wantarray while BEGIN END "; var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " + "elif except exec finally from global import in is lambda " + "nonlocal not or pass print raise try with yield " + "False True None "; var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" + " defined elsif end ensure false in module next nil not or redo rescue " + "retry self super then true undef unless until when yield BEGIN END "; var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " + "function in local set then until "; var ALL_KEYWORDS = ( CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS); // token style names. correspond to css classes /** token style for a string literal */ var PR_STRING = 'str'; /** token style for a keyword */ var PR_KEYWORD = 'kwd'; /** token style for a comment */ var PR_COMMENT = 'com'; /** token style for a type */ var PR_TYPE = 'typ'; /** token style for a literal value. e.g. 1, null, true. */ var PR_LITERAL = 'lit'; /** token style for a punctuation string. */ var PR_PUNCTUATION = 'pun'; /** token style for a punctuation string. */ var PR_PLAIN = 'pln'; /** token style for an sgml tag. */ var PR_TAG = 'tag'; /** token style for a markup declaration such as a DOCTYPE. */ var PR_DECLARATION = 'dec'; /** token style for embedded source. */ var PR_SOURCE = 'src'; /** token style for an sgml attribute name. */ var PR_ATTRIB_NAME = 'atn'; /** token style for an sgml attribute value. */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. */ var PR_NOCODE = 'nocode'; function isWordChar(ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } /** Splice one array into another. * Like the python <code> * container[containerPosition:containerPosition + countReplaced] = inserted * </code> * @param {Array} inserted * @param {Array} container modified in place * @param {Number} containerPosition * @param {Number} countReplaced */ function spliceArrayInto( inserted, container, containerPosition, countReplaced) { inserted.unshift(containerPosition, countReplaced || 0); try { container.splice.apply(container, inserted); } finally { inserted.splice(0, 2); } } /** A set of tokens that can precede a regular expression literal in * javascript. * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full * list, but I've removed ones that might be problematic when seen in * languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * @private */ var REGEXP_PRECEDER_PATTERN = function () { var preceders = [ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=", "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===", ">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^", "^^=", "{", "|", "|=", "||", "||=", "~" /* handles =~ and !~ */, "break", "case", "continue", "delete", "do", "else", "finally", "instanceof", "return", "throw", "try", "typeof" ]; var pattern = '(?:' + '(?:(?:^|[^0-9.])\\.{1,3})|' + // a dot that's not part of a number '(?:(?:^|[^\\+])\\+)|' + // allow + but not ++ '(?:(?:^|[^\\-])-)'; // allow - but not -- for (var i = 0; i < preceders.length; ++i) { var preceder = preceders[i]; if (isWordChar(preceder.charAt(0))) { pattern += '|\\b' + preceder; } else { pattern += '|' + preceder.replace(/([^=<>:&])/g, '\\$1'); } } pattern += '|^)\\s*$'; // matches at end, and matches empty string return new RegExp(pattern); // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not // valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. }(); // Define regexps here so that the interpreter doesn't have to create an // object each time the function containing them is called. // The language spec requires a new object created even if you don't access // the $1 members. var pr_amp = /&/g; var pr_lt = /</g; var pr_gt = />/g; var pr_quot = /\"/g; /** like textToHtml but escapes double quotes to be attribute safe. */ function attribToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;') .replace(pr_quot, '&quot;'); } /** escapest html special characters to html. */ function textToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;'); } var pr_ltEnt = /&lt;/g; var pr_gtEnt = /&gt;/g; var pr_aposEnt = /&apos;/g; var pr_quotEnt = /&quot;/g; var pr_ampEnt = /&amp;/g; var pr_nbspEnt = /&nbsp;/g; /** unescapes html to plain text. */ function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } // Handle numeric entities specially. We can't use functional substitution // since that doesn't work in older versions of Safari. // These should be rare since most browsers convert them to normal chars. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<') .replace(pr_gtEnt, '>') .replace(pr_aposEnt, "'") .replace(pr_quotEnt, '"') .replace(pr_ampEnt, '&') .replace(pr_nbspEnt, ' '); } /** is the given node's innerHTML normally unescaped? */ function isRawContent(node) { return 'XMP' === node.tagName; } function normalizedHtml(node, out) { switch (node.nodeType) { case 1: // an element var name = node.tagName.toLowerCase(); out.push('<', name); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified) { continue; } out.push(' '); normalizedHtml(attr, out); } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 2: // an attribute out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"'); break; case 3: case 4: // text out.push(textToHtml(node.nodeValue)); break; } } var PR_innerHtmlWorks = null; function getInnerHtml(node) { // inner html is hopelessly broken in Safari 2.0.4 when the content is // an html description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild( document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); PR_innerHtmlWorks = !/</.test(testNode.innerHTML); } if (PR_innerHtmlWorks) { var content = node.innerHTML; // XMP tags contain unescaped entities so require special handling. if (isRawContent(node)) { content = textToHtml(content); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } /** returns a function that expand tabs to spaces. This function can be fed * successive chunks of text, and will maintain its own internal state to * keep track of how tabs are expanded. * @return {function (string) : string} a function that takes * plain text and return the text with tabs expanded. * @private */ function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function (plainText) { // walk over each character looking for tabs and newlines. // On tabs, expand them. On newlines, reset charInLine. // Otherwise increment charInLine var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); // calculate how much space we need in front of this part // nSpaces is the amount of padding -- the number of spaces needed // to move us to the next column, where columns occur at factors of // tabWidth. var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; } // The below pattern matches one of the following // (1) /[^<]+/ : A run of characters other than '<' // (2) /<!--.*?-->/: an HTML comment // (3) /<!\[CDATA\[.*?\]\]>/: a cdata section // (3) /<\/?[a-zA-Z][^>]*>/ : A probably tag that should not be highlighted // (4) /</ : A '<' that does not begin a larger chunk. Treated as 1 var pr_chunkPattern = /(?:[^<]+|<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g; var pr_commentPrefix = /^<!--/; var pr_cdataPrefix = /^<\[CDATA\[/; var pr_brPrefix = /^<br\b/i; var pr_tagNameRe = /^<(\/?)([a-zA-Z]+)/; /** split markup into chunks of html tags (style null) and * plain text (style {@link #PR_PLAIN}), converting tags which are * significant for tokenization (<br>) into their textual equivalent. * * @param {string} s html where whitespace is considered significant. * @return {Object} source code and extracted tags. * @private */ function extractTags(s) { // since the pattern has the 'g' modifier and defines no capturing groups, // this will return a list of all chunks which we then classify and wrap as // PR_Tokens var matches = s.match(pr_chunkPattern); var sourceBuf = []; var sourceBufLen = 0; var extractedTags = []; if (matches) { for (var i = 0, n = matches.length; i < n; ++i) { var match = matches[i]; if (match.length > 1 && match.charAt(0) === '<') { if (pr_commentPrefix.test(match)) { continue; } if (pr_cdataPrefix.test(match)) { // strip CDATA prefix and suffix. Don't unescape since it's CDATA sourceBuf.push(match.substring(9, match.length - 3)); sourceBufLen += match.length - 12; } else if (pr_brPrefix.test(match)) { // <br> tags are lexically significant so convert them to text. // This is undone later. sourceBuf.push('\n'); ++sourceBufLen; } else { if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) { // A <span class="nocode"> will start a section that should be // ignored. Continue walking the list until we see a matching end // tag. var name = match.match(pr_tagNameRe)[2]; var depth = 1; end_tag_loop: for (var j = i + 1; j < n; ++j) { var name2 = matches[j].match(pr_tagNameRe); if (name2 && name2[2] === name) { if (name2[1] === '/') { if (--depth === 0) { break end_tag_loop; } } else { ++depth; } } } if (j < n) { extractedTags.push( sourceBufLen, matches.slice(i, j + 1).join('')); i = j; } else { // Ignore unclosed sections. extractedTags.push(sourceBufLen, match); } } else { extractedTags.push(sourceBufLen, match); } } } else { var literalText = htmlToText(match); sourceBuf.push(literalText); sourceBufLen += literalText.length; } } } return { source: sourceBuf.join(''), tags: extractedTags }; } /** True if the given tag contains a class attribute with the nocode class. */ function isNoCodeTag(tag) { return !!tag // First canonicalize the representation of attributes .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' $1="$2$3$4"') // Then look for the attribute we want. .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/); } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, context : RegExp, shortcut : string]. & * Style is a style constant like PR_PLAIN. * * Pattern must only match prefixes, and if it matches a prefix and context * is null or matches the last non-comment token parsed, then that match is * considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (string, number?) : Array.<number|string>} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); for (var i = allPatterns.length; --i >= 0;) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } } })(); var nPatterns = fallthroughStylePatterns.length; var notWs = /\S/; return function (sourceCode, opt_basePos) { opt_basePos = opt_basePos || 0; var decorations = [opt_basePos, PR_PLAIN]; var lastToken = ''; var pos = 0; // index into sourceCode var tail = sourceCode; while (tail.length) { var style; var token = null; var match; var patternParts = shortcuts[tail.charAt(0)]; if (patternParts) { match = tail.match(patternParts[1]); token = match[0]; style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; var contextPattern = patternParts[2]; if (contextPattern && !contextPattern.test(lastToken)) { // rule can't be used continue; } match = tail.match(patternParts[1]); if (match) { token = match[0]; style = patternParts[0]; break; } } if (!token) { // make sure that we make progress style = PR_PLAIN; token = tail.substring(0, 1); } } decorations.push(opt_basePos + pos, style); pos += token.length; tail = tail.substring(token.length); if (style !== PR_COMMENT && notWs.test(token)) { lastToken = token; } } return decorations; }; } var PR_MARKUP_LEXER = createSimpleLexer([], [ [PR_PLAIN, /^[^<]+/, null], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/, null], [PR_COMMENT, /^<!--[\s\S]*?(?:-->|$)/, null], [PR_SOURCE, /^<\?[\s\S]*?(?:\?>|$)/, null], [PR_SOURCE, /^<%[\s\S]*?(?:%>|$)/, null], [PR_SOURCE, // Tags whose content is not escaped, and which contain source code. /^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i, null], [PR_TAG, /^<\/?\w[^<>]*>/, null] ]); // Splits any of the source|style|xmp entries above into a start tag, // source content, and end tag. var PR_SOURCE_CHUNK_PARTS = /^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/; /** split markup on tags, comments, application directives, and other top * level constructs. Tags are returned as a single token - attributes are * not yet broken out. * @private */ function tokenizeMarkup(source) { var decorations = PR_MARKUP_LEXER(source); for (var i = 0; i < decorations.length; i += 2) { if (decorations[i + 1] === PR_SOURCE) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; // Split out start and end script tags as actual tags, and leave the // body with style SCRIPT. var sourceChunk = source.substring(start, end); var match = sourceChunk.match(PR_SOURCE_CHUNK_PARTS); if (match) { decorations.splice( i, 2, start, PR_TAG, // the open chunk start + match[1].length, PR_SOURCE, start + match[1].length + (match[2] || '').length, PR_TAG); } } } return decorations; } var PR_TAG_LEXER = createSimpleLexer([ [PR_ATTRIB_VALUE, /^\'[^\']*(?:\'|$)/, null, "'"], [PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'], [PR_PUNCTUATION, /^[<>\/=]+/, null, '<>/='] ], [ [PR_TAG, /^[\w:\-]+/, /^</], [PR_ATTRIB_VALUE, /^[\w\-]+/, /^=/], [PR_ATTRIB_NAME, /^[\w:\-]+/, null], [PR_PLAIN, /^\s+/, null, ' \t\r\n'] ]); /** split tags attributes and their values out from the tag name, and * recursively lex source chunks. * @private */ function splitTagAttributes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_TAG) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var chunk = source.substring(start, end); var subDecorations = PR_TAG_LEXER(chunk, start); spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (string) : Array.<string|number>} a * decorator that takes sourceCode as plain text and that returns a * decoration list */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options.tripleQuotedStrings) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options.multiLineStrings) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } fallthroughStylePatterns.push( [PR_PLAIN, /^(?:[^\'\"\`\/\#]+)/, null, ' \r\n']); if (options.hashComments) { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } if (options.cStyleComments) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options.regexLiterals) { var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '^/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '(?:/|$)'); fallthroughStylePatterns.push( [PR_STRING, new RegExp(REGEX_LITERAL), REGEXP_PRECEDER_PATTERN]); } var keywords = wordSet(options.keywords); options = null; /** splits the given string into comment, string, and "other" tokens. * @param {string} sourceCode as plain text * @return {Array.<number|string>} a decoration list. * @private */ var splitStringAndCommentTokens = createSimpleLexer( shortcutStylePatterns, fallthroughStylePatterns); var styleLiteralIdentifierPuncRecognizer = createSimpleLexer([], [ [PR_PLAIN, /^\s+/, null, ' \r\n'], // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_PLAIN, /^[a-z_$@][a-z_$@0-9]*/i, null], // A hex number [PR_LITERAL, /^0x[a-f0-9]+[a-z]/i, null], // An octal or decimal number, possibly in scientific notation [PR_LITERAL, /^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i, null, '123456789'], [PR_PUNCTUATION, /^[^\s\w\.$@]+/, null] // Fallback will handle decimal points not adjacent to a digit ]); /** splits plain text tokens into more specific tokens, and then tries to * recognize keywords, and types. * @private */ function splitNonStringNonCommentTokens(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_PLAIN) { var start, end, chunk, subDecs; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; chunk = source.substring(start, end); subDecs = styleLiteralIdentifierPuncRecognizer(chunk, start); for (var j = 0, m = subDecs.length; j < m; j += 2) { var subStyle = subDecs[j + 1]; if (subStyle === PR_PLAIN) { var subStart = subDecs[j]; var subEnd = j + 2 < m ? subDecs[j + 2] : chunk.length; var token = source.substring(subStart, subEnd); if (token === '.') { subDecs[j + 1] = PR_PUNCTUATION; } else if (token in keywords) { subDecs[j + 1] = PR_KEYWORD; } else if (/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(token)) { // classify types and annotations using Java's style conventions subDecs[j + 1] = token.charAt(0) === '@' ? PR_LITERAL : PR_TYPE; } } } spliceArrayInto(subDecs, decorations, i, 2); i += subDecs.length - 2; } } return decorations; } return function (sourceCode) { // Split into strings, comments, and other. // We do this because strings and comments are easily recognizable and can // contain stuff that looks like other tokens, so we want to mark those // early so we don't recurse into them. var decorations = splitStringAndCommentTokens(sourceCode); // Split non comment|string tokens on whitespace and word boundaries decorations = splitNonStringNonCommentTokens(sourceCode, decorations); return decorations; }; } var decorateSource = sourceDecorator({ keywords: ALL_KEYWORDS, hashComments: true, cStyleComments: true, multiLineStrings: true, regexLiterals: true }); /** identify regions of markup that are really source code, and recursivley * lex them. * @private */ function splitSourceNodes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_SOURCE) { // Recurse using the non-markup lexer var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var subDecorations = decorateSource(source.substring(start, end)); for (var j = 0, m = subDecorations.length; j < m; j += 2) { subDecorations[j] += start; } spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } /** identify attribute values that really contain source code and recursively * lex them. * @private */ function splitSourceAttributes(source, decorations) { var nextValueIsSource = false; for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; var start, end; if (style === PR_ATTRIB_NAME) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; nextValueIsSource = /^on|^style$/i.test(source.substring(start, end)); } else if (style === PR_ATTRIB_VALUE) { if (nextValueIsSource) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var attribValue = source.substring(start, end); var attribLen = attribValue.length; var quoted = (attribLen >= 2 && /^[\"\']/.test(attribValue) && attribValue.charAt(0) === attribValue.charAt(attribLen - 1)); var attribSource; var attribSourceStart; var attribSourceEnd; if (quoted) { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue; } else { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue.substring(1, attribValue.length - 1); } var attribSourceDecorations = decorateSource(attribSource); for (var j = 0, m = attribSourceDecorations.length; j < m; j += 2) { attribSourceDecorations[j] += attribSourceStart; } if (quoted) { attribSourceDecorations.push(attribSourceEnd, PR_ATTRIB_VALUE); spliceArrayInto(attribSourceDecorations, decorations, i + 2, 0); } else { spliceArrayInto(attribSourceDecorations, decorations, i, 2); } } nextValueIsSource = false; } } return decorations; } /** returns a decoration list given a string of markup. * * This code recognizes a number of constructs. * <!-- ... --> comment * <!\w ... > declaration * <\w ... > tag * </\w ... > tag * <?...?> embedded source * <%...%> embedded source * &[#\w]...; entity * * It does not recognizes %foo; doctype entities from . * * It will recurse into any <style>, <script>, and on* attributes using * PR_lexSource. */ function decorateMarkup(sourceCode) { // This function works as follows: // 1) Start by splitting the markup into text and tag chunks // Input: string s // Output: List<PR_Token> where style in (PR_PLAIN, null) // 2) Then split the text chunks further into comments, declarations, // tags, etc. // After each split, consider whether the token is the start of an // embedded source section, i.e. is an open <script> tag. If it is, find // the corresponding close token, and don't bother to lex in between. // Input: List<string> // Output: List<PR_Token> with style in // (PR_TAG, PR_PLAIN, PR_SOURCE, null) // 3) Finally go over each tag token and split out attribute names and // values. // Input: List<PR_Token> // Output: List<PR_Token> where style in // (PR_TAG, PR_PLAIN, PR_SOURCE, NAME, VALUE, null) var decorations = tokenizeMarkup(sourceCode); decorations = splitTagAttributes(sourceCode, decorations); decorations = splitSourceNodes(sourceCode, decorations); decorations = splitSourceAttributes(sourceCode, decorations); return decorations; } /** * @param {string} sourceText plain text * @param {Array.<number|string>} extractedTags chunks of raw html preceded * by their position in sourceText in order. * @param {Array.<number|string>} decorations style classes preceded by their * position in sourceText in order. * @return {string} html * @private */ function recombineTagsAndDecorations(sourceText, extractedTags, decorations) { var html = []; // index past the last char in sourceText written to html var outputIdx = 0; var openDecoration = null; var currentDecoration = null; var tagPos = 0; // index into extractedTags var decPos = 0; // index into decorations var tabExpander = makeTabExpander(PR_TAB_WIDTH); var adjacentSpaceRe = /([\r\n ]) /g; var startOrSpaceRe = /(^| ) /gm; var newlineRe = /\r\n?|\n/g; var trailingSpaceRe = /[ \r\n]$/; var lastWasSpace = true; // the last text chunk emitted ended with a space. // A helper function that is responsible for opening sections of decoration // and outputing properly escaped chunks of source function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } // This interacts badly with some wikis which introduces paragraph tags // into pre blocks for some strange reason. // It's necessary for IE though which seems to lose the preformattedness // of <pre> tags when their innerHTML is assigned. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html // and it serves to undo the conversion of <br>s to newlines done in // chunkify. var htmlChunk = textToHtml( tabExpander(sourceText.substring(outputIdx, sourceIdx))) .replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&nbsp;'); // Keep track of whether we need to escape space at the beginning of the // next chunk. lastWasSpace = trailingSpaceRe.test(htmlChunk); html.push(htmlChunk.replace(newlineRe, '<br />')); outputIdx = sourceIdx; } } while (true) { // Determine if we're going to consume a tag this time around. Otherwise // we consume a decoration or exit. var outputTag; if (tagPos < extractedTags.length) { if (decPos < decorations.length) { // Pick one giving preference to extractedTags since we shouldn't open // a new style that we're going to have to immediately close in order // to output a tag. outputTag = extractedTags[tagPos] <= decorations[decPos]; } else { outputTag = true; } } else { outputTag = false; } // Consume either a decoration or a tag or exit. if (outputTag) { emitTextUpTo(extractedTags[tagPos]); if (openDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } html.push(extractedTags[tagPos + 1]); tagPos += 2; } else if (decPos < decorations.length) { emitTextUpTo(decorations[decPos]); currentDecoration = decorations[decPos + 1]; decPos += 2; } else { break; } } emitTextUpTo(sourceText.length); if (openDecoration) { html.push('</span>'); } return html.join(''); } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (string) : Array.<number|string>} handler * a function from source code to a list of decorations. * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if ('console' in window) { console.log('cannot override language handler %s', ext); } } } registerLangHandler(decorateSource, ['default-code']); registerLangHandler(decorateMarkup, ['default-markup', 'html', 'htm', 'xhtml', 'xml', 'xsl']); registerLangHandler(sourceDecorator({ keywords: CPP_KEYWORDS, hashComments: true, cStyleComments: true }), ['c', 'cc', 'cpp', 'cxx', 'cyc']); registerLangHandler(sourceDecorator({ keywords: CSHARP_KEYWORDS, hashComments: true, cStyleComments: true }), ['cs']); registerLangHandler(sourceDecorator({ keywords: JAVA_KEYWORDS, cStyleComments: true }), ['java']); registerLangHandler(sourceDecorator({ keywords: SH_KEYWORDS, hashComments: true, multiLineStrings: true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ keywords: PYTHON_KEYWORDS, hashComments: true, multiLineStrings: true, tripleQuotedStrings: true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ keywords: PERL_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ keywords: RUBY_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['rb']); registerLangHandler(sourceDecorator({ keywords: JSCRIPT_KEYWORDS, cStyleComments: true, regexLiterals: true }), ['js']); function prettyPrintOne(sourceCodeHtml, opt_langExtension) { try { // Extract tags, and convert the source code to plain text. var sourceAndExtractedTags = extractTags(sourceCodeHtml); /** Plain text. @type {string} */ var source = sourceAndExtractedTags.source; /** Even entries are positions in source in ascending order. Odd entries * are tags that were extracted at that position. * @type {Array.<number|string>} */ var extractedTags = sourceAndExtractedTags.tags; // Pick a lexer and apply it. if (!langHandlerRegistry.hasOwnProperty(opt_langExtension)) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. opt_langExtension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = langHandlerRegistry[opt_langExtension].call({}, source); // Integrate the decorations and tags back into the source code to produce // a decorated html string. return recombineTagsAndDecorations(source, extractedTags, decorations); } catch (e) { if ('console' in window) { console.log(e); console.trace(); } return sourceCodeHtml; } } function prettyPrint(opt_whenDone) { var isIE6 = _pr_isIE6(); // fetch a list of nodes to rewrite var codeSegments = [ document.getElementsByTagName('pre'), document.getElementsByTagName('code'), document.getElementsByTagName('xmp') ]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0; j < codeSegments[i].length; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; // the loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; function doWork() { var endTime = (PR_SHOULD_USE_CONTINUATION ? new Date().getTime() + 250 /* ms */ : Infinity); for (; k < elements.length && new Date().getTime() < endTime; k++) { var cs = elements[k]; if (cs.className && cs.className.indexOf('prettyprint') >= 0) { // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler as // passed to PR_registerLangHandler. var langExtension = cs.className.match(/\blang-(\w+)\b/); if (langExtension) { langExtension = langExtension[1]; } // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp') && p.className && p.className.indexOf('prettyprint') >= 0) { nested = true; break; } } if (!nested) { // fetch the content as a snippet of properly escaped HTML. // Firefox adds newlines at the end. var content = getInnerHtml(cs); content = content.replace(/(?:\r\n?|\n)$/, ''); // do the pretty printing var newContent = prettyPrintOne(content, langExtension); // push the prettified html back into the tag. if (!isRawContent(cs)) { // just replace the old html with the new cs.innerHTML = newContent; } else { // we need to change the tag to a <pre> since <xmp>s do not allow // embedded tags such as the span tags used to attach styles to // sections of source code. var pre = document.createElement('PRE'); for (var i = 0; i < cs.attributes.length; ++i) { var a = cs.attributes[i]; if (a.specified) { var aname = a.name.toLowerCase(); if (aname === 'class') { pre.className = a.value; // For IE 6 } else { pre.setAttribute(a.name, a.value); } } } pre.innerHTML = newContent; // remove the old cs.parentNode.replaceChild(pre, cs); cs = pre; } // Replace <br>s with line-feeds so that copying and pasting works // on IE 6. // Doing this on other browsers breaks lots of stuff since \r\n is // treated as two newlines on Firefox, and doing this also slows // down rendering. if (isIE6 && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( document.createTextNode('\r\n'), lineBreak); } } } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } doWork(); } window['PR_normalizedHtml'] = normalizedHtml; window['prettyPrintOne'] = prettyPrintOne; window['prettyPrint'] = prettyPrint; window['PR'] = { 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE }; })();
JavaScript
// Copyright (C) 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * * The lexer should work on a number of languages including C and friends, * Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles. * It works passably on Ruby, PHP and Awk and a decent subset of Perl, but, * because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or * CAML-like languages. * * If there's a language not mentioned here, then I don't know it, and don't * know whether it works. If it has a C-like, Bash-like, or XML-like syntax * then it should work passably. * * Usage: * 1) include this source file in an html page via * <script type="text/javascript" src="/path/to/prettify.js"></script> * 2) define style rules. See the example page for examples. * 3) mark the <pre> and <code> tags in your source with class=prettyprint. * You can also use the (html deprecated) <xmp> tag, but the pretty printer * needs to do more substantial DOM manipulations to support that, so some * css styles may not be preserved. * That's it. I wanted to keep the API as simple as possible, so there's no * need to specify which language the code is in. * * Change log: * cbeust, 2006/08/22 * Java annotations (start with "@") are now captured as literals ("lit") */ // JSLint declarations /*global console, document, navigator, setTimeout, window */ /** * Split {@code prettyPrint} into multiple timeouts so as not to interfere with * UI events. * If set to {@code false}, {@code prettyPrint()} is synchronous. */ var PR_SHOULD_USE_CONTINUATION = true; /** the number of characters between tab columns */ var PR_TAB_WIDTH = 8; /** Walks the DOM returning a properly escaped version of innerHTML. * @param {Node} node * @param {Array.<string>} out output buffer that receives chunks of HTML. */ var PR_normalizedHtml; /** Contains functions for creating and registering new language handlers. * @type {Object} */ var PR; /** Pretty print a chunk of code. * * @param {string} sourceCodeHtml code as html * @return {string} code as html, but prettier */ var prettyPrintOne; /** find all the < pre > and < code > tags in the DOM with class=prettyprint * and prettify them. * @param {Function} opt_whenDone if specified, called when the last entry * has been finished. */ var prettyPrint; /** browser detection. @extern */ function _pr_isIE6() { var isIE6 = navigator && navigator.userAgent && /\bMSIE 6\./.test(navigator.userAgent); _pr_isIE6 = function () { return isIE6; }; return isIE6; } (function () { /** Splits input on space and returns an Object mapping each non-empty part to * true. */ function wordSet(words) { words = words.split(/ /g); var set = {}; for (var i = words.length; --i >= 0;) { var w = words[i]; if (w) { set[w] = null; } } return set; } // Keyword lists for various languages. var FLOW_CONTROL_KEYWORDS = "break continue do else for if return while "; var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " + "double enum extern float goto int long register short signed sizeof " + "static struct switch typedef union unsigned void volatile "; var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " + "new operator private protected public this throw true try "; var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " + "concept concept_map const_cast constexpr decltype " + "dynamic_cast explicit export friend inline late_check " + "mutable namespace nullptr reinterpret_cast static_assert static_cast " + "template typeid typename typeof using virtual wchar_t where "; var JAVA_KEYWORDS = COMMON_KEYWORDS + "boolean byte extends final finally implements import instanceof null " + "native package strictfp super synchronized throws transient "; var CSHARP_KEYWORDS = JAVA_KEYWORDS + "as base by checked decimal delegate descending event " + "fixed foreach from group implicit in interface internal into is lock " + "object out override orderby params readonly ref sbyte sealed " + "stackalloc string select uint ulong unchecked unsafe ushort var "; var JSCRIPT_KEYWORDS = COMMON_KEYWORDS + "debugger eval export function get null set undefined var with " + "Infinity NaN "; var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " + "goto if import last local my next no our print package redo require " + "sub undef unless until use wantarray while BEGIN END "; var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " + "elif except exec finally from global import in is lambda " + "nonlocal not or pass print raise try with yield " + "False True None "; var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" + " defined elsif end ensure false in module next nil not or redo rescue " + "retry self super then true undef unless until when yield BEGIN END "; var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " + "function in local set then until "; var ALL_KEYWORDS = ( CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS + PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS); // token style names. correspond to css classes /** token style for a string literal */ var PR_STRING = 'str'; /** token style for a keyword */ var PR_KEYWORD = 'kwd'; /** token style for a comment */ var PR_COMMENT = 'com'; /** token style for a type */ var PR_TYPE = 'typ'; /** token style for a literal value. e.g. 1, null, true. */ var PR_LITERAL = 'lit'; /** token style for a punctuation string. */ var PR_PUNCTUATION = 'pun'; /** token style for a punctuation string. */ var PR_PLAIN = 'pln'; /** token style for an sgml tag. */ var PR_TAG = 'tag'; /** token style for a markup declaration such as a DOCTYPE. */ var PR_DECLARATION = 'dec'; /** token style for embedded source. */ var PR_SOURCE = 'src'; /** token style for an sgml attribute name. */ var PR_ATTRIB_NAME = 'atn'; /** token style for an sgml attribute value. */ var PR_ATTRIB_VALUE = 'atv'; /** * A class that indicates a section of markup that is not code, e.g. to allow * embedding of line numbers within code listings. */ var PR_NOCODE = 'nocode'; function isWordChar(ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } /** Splice one array into another. * Like the python <code> * container[containerPosition:containerPosition + countReplaced] = inserted * </code> * @param {Array} inserted * @param {Array} container modified in place * @param {Number} containerPosition * @param {Number} countReplaced */ function spliceArrayInto( inserted, container, containerPosition, countReplaced) { inserted.unshift(containerPosition, countReplaced || 0); try { container.splice.apply(container, inserted); } finally { inserted.splice(0, 2); } } /** A set of tokens that can precede a regular expression literal in * javascript. * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full * list, but I've removed ones that might be problematic when seen in * languages that don't support regular expression literals. * * <p>Specifically, I've removed any keywords that can't precede a regexp * literal in a syntactically legal javascript program, and I've removed the * "in" keyword since it's not a keyword in many languages, and might be used * as a count of inches. * @private */ var REGEXP_PRECEDER_PATTERN = function () { var preceders = [ "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=", "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=", "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";", "<", "<<", "<<=", "<=", "=", "==", "===", ">", ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[", "^", "^=", "^^", "^^=", "{", "|", "|=", "||", "||=", "~" /* handles =~ and !~ */, "break", "case", "continue", "delete", "do", "else", "finally", "instanceof", "return", "throw", "try", "typeof" ]; var pattern = '(?:' + '(?:(?:^|[^0-9.])\\.{1,3})|' + // a dot that's not part of a number '(?:(?:^|[^\\+])\\+)|' + // allow + but not ++ '(?:(?:^|[^\\-])-)'; // allow - but not -- for (var i = 0; i < preceders.length; ++i) { var preceder = preceders[i]; if (isWordChar(preceder.charAt(0))) { pattern += '|\\b' + preceder; } else { pattern += '|' + preceder.replace(/([^=<>:&])/g, '\\$1'); } } pattern += '|^)\\s*$'; // matches at end, and matches empty string return new RegExp(pattern); // CAVEAT: this does not properly handle the case where a regular // expression immediately follows another since a regular expression may // have flags for case-sensitivity and the like. Having regexp tokens // adjacent is not // valid in any language I'm aware of, so I'm punting. // TODO: maybe style special characters inside a regexp as punctuation. }(); // Define regexps here so that the interpreter doesn't have to create an // object each time the function containing them is called. // The language spec requires a new object created even if you don't access // the $1 members. var pr_amp = /&/g; var pr_lt = /</g; var pr_gt = />/g; var pr_quot = /\"/g; /** like textToHtml but escapes double quotes to be attribute safe. */ function attribToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;') .replace(pr_quot, '&quot;'); } /** escapest html special characters to html. */ function textToHtml(str) { return str.replace(pr_amp, '&amp;') .replace(pr_lt, '&lt;') .replace(pr_gt, '&gt;'); } var pr_ltEnt = /&lt;/g; var pr_gtEnt = /&gt;/g; var pr_aposEnt = /&apos;/g; var pr_quotEnt = /&quot;/g; var pr_ampEnt = /&amp;/g; var pr_nbspEnt = /&nbsp;/g; /** unescapes html to plain text. */ function htmlToText(html) { var pos = html.indexOf('&'); if (pos < 0) { return html; } // Handle numeric entities specially. We can't use functional substitution // since that doesn't work in older versions of Safari. // These should be rare since most browsers convert them to normal chars. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) { var end = html.indexOf(';', pos); if (end >= 0) { var num = html.substring(pos + 3, end); var radix = 10; if (num && num.charAt(0) === 'x') { num = num.substring(1); radix = 16; } var codePoint = parseInt(num, radix); if (!isNaN(codePoint)) { html = (html.substring(0, pos) + String.fromCharCode(codePoint) + html.substring(end + 1)); } } } return html.replace(pr_ltEnt, '<') .replace(pr_gtEnt, '>') .replace(pr_aposEnt, "'") .replace(pr_quotEnt, '"') .replace(pr_ampEnt, '&') .replace(pr_nbspEnt, ' '); } /** is the given node's innerHTML normally unescaped? */ function isRawContent(node) { return 'XMP' === node.tagName; } function normalizedHtml(node, out) { switch (node.nodeType) { case 1: // an element var name = node.tagName.toLowerCase(); out.push('<', name); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified) { continue; } out.push(' '); normalizedHtml(attr, out); } out.push('>'); for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } if (node.firstChild || !/^(?:br|link|img)$/.test(name)) { out.push('<\/', name, '>'); } break; case 2: // an attribute out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"'); break; case 3: case 4: // text out.push(textToHtml(node.nodeValue)); break; } } var PR_innerHtmlWorks = null; function getInnerHtml(node) { // inner html is hopelessly broken in Safari 2.0.4 when the content is // an html description of well formed XML and the containing tag is a PRE // tag, so we detect that case and emulate innerHTML. if (null === PR_innerHtmlWorks) { var testNode = document.createElement('PRE'); testNode.appendChild( document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />')); PR_innerHtmlWorks = !/</.test(testNode.innerHTML); } if (PR_innerHtmlWorks) { var content = node.innerHTML; // XMP tags contain unescaped entities so require special handling. if (isRawContent(node)) { content = textToHtml(content); } return content; } var out = []; for (var child = node.firstChild; child; child = child.nextSibling) { normalizedHtml(child, out); } return out.join(''); } /** returns a function that expand tabs to spaces. This function can be fed * successive chunks of text, and will maintain its own internal state to * keep track of how tabs are expanded. * @return {function (string) : string} a function that takes * plain text and return the text with tabs expanded. * @private */ function makeTabExpander(tabWidth) { var SPACES = ' '; var charInLine = 0; return function (plainText) { // walk over each character looking for tabs and newlines. // On tabs, expand them. On newlines, reset charInLine. // Otherwise increment charInLine var out = null; var pos = 0; for (var i = 0, n = plainText.length; i < n; ++i) { var ch = plainText.charAt(i); switch (ch) { case '\t': if (!out) { out = []; } out.push(plainText.substring(pos, i)); // calculate how much space we need in front of this part // nSpaces is the amount of padding -- the number of spaces needed // to move us to the next column, where columns occur at factors of // tabWidth. var nSpaces = tabWidth - (charInLine % tabWidth); charInLine += nSpaces; for (; nSpaces >= 0; nSpaces -= SPACES.length) { out.push(SPACES.substring(0, nSpaces)); } pos = i + 1; break; case '\n': charInLine = 0; break; default: ++charInLine; } } if (!out) { return plainText; } out.push(plainText.substring(pos)); return out.join(''); }; } // The below pattern matches one of the following // (1) /[^<]+/ : A run of characters other than '<' // (2) /<!--.*?-->/: an HTML comment // (3) /<!\[CDATA\[.*?\]\]>/: a cdata section // (3) /<\/?[a-zA-Z][^>]*>/ : A probably tag that should not be highlighted // (4) /</ : A '<' that does not begin a larger chunk. Treated as 1 var pr_chunkPattern = /(?:[^<]+|<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g; var pr_commentPrefix = /^<!--/; var pr_cdataPrefix = /^<\[CDATA\[/; var pr_brPrefix = /^<br\b/i; var pr_tagNameRe = /^<(\/?)([a-zA-Z]+)/; /** split markup into chunks of html tags (style null) and * plain text (style {@link #PR_PLAIN}), converting tags which are * significant for tokenization (<br>) into their textual equivalent. * * @param {string} s html where whitespace is considered significant. * @return {Object} source code and extracted tags. * @private */ function extractTags(s) { // since the pattern has the 'g' modifier and defines no capturing groups, // this will return a list of all chunks which we then classify and wrap as // PR_Tokens var matches = s.match(pr_chunkPattern); var sourceBuf = []; var sourceBufLen = 0; var extractedTags = []; if (matches) { for (var i = 0, n = matches.length; i < n; ++i) { var match = matches[i]; if (match.length > 1 && match.charAt(0) === '<') { if (pr_commentPrefix.test(match)) { continue; } if (pr_cdataPrefix.test(match)) { // strip CDATA prefix and suffix. Don't unescape since it's CDATA sourceBuf.push(match.substring(9, match.length - 3)); sourceBufLen += match.length - 12; } else if (pr_brPrefix.test(match)) { // <br> tags are lexically significant so convert them to text. // This is undone later. sourceBuf.push('\n'); ++sourceBufLen; } else { if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) { // A <span class="nocode"> will start a section that should be // ignored. Continue walking the list until we see a matching end // tag. var name = match.match(pr_tagNameRe)[2]; var depth = 1; end_tag_loop: for (var j = i + 1; j < n; ++j) { var name2 = matches[j].match(pr_tagNameRe); if (name2 && name2[2] === name) { if (name2[1] === '/') { if (--depth === 0) { break end_tag_loop; } } else { ++depth; } } } if (j < n) { extractedTags.push( sourceBufLen, matches.slice(i, j + 1).join('')); i = j; } else { // Ignore unclosed sections. extractedTags.push(sourceBufLen, match); } } else { extractedTags.push(sourceBufLen, match); } } } else { var literalText = htmlToText(match); sourceBuf.push(literalText); sourceBufLen += literalText.length; } } } return { source: sourceBuf.join(''), tags: extractedTags }; } /** True if the given tag contains a class attribute with the nocode class. */ function isNoCodeTag(tag) { return !!tag // First canonicalize the representation of attributes .replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g, ' $1="$2$3$4"') // Then look for the attribute we want. .match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/); } /** Given triples of [style, pattern, context] returns a lexing function, * The lexing function interprets the patterns to find token boundaries and * returns a decoration list of the form * [index_0, style_0, index_1, style_1, ..., index_n, style_n] * where index_n is an index into the sourceCode, and style_n is a style * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to * all characters in sourceCode[index_n-1:index_n]. * * The stylePatterns is a list whose elements have the form * [style : string, pattern : RegExp, context : RegExp, shortcut : string]. & * Style is a style constant like PR_PLAIN. * * Pattern must only match prefixes, and if it matches a prefix and context * is null or matches the last non-comment token parsed, then that match is * considered a token with the same style. * * Context is applied to the last non-whitespace, non-comment token * recognized. * * Shortcut is an optional string of characters, any of which, if the first * character, gurantee that this pattern and only this pattern matches. * * @param {Array} shortcutStylePatterns patterns that always start with * a known character. Must have a shortcut string. * @param {Array} fallthroughStylePatterns patterns that will be tried in * order if the shortcut ones fail. May have shortcuts. * * @return {function (string, number?) : Array.<number|string>} a * function that takes source code and returns a list of decorations. */ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) { var shortcuts = {}; (function () { var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns); for (var i = allPatterns.length; --i >= 0;) { var patternParts = allPatterns[i]; var shortcutChars = patternParts[3]; if (shortcutChars) { for (var c = shortcutChars.length; --c >= 0;) { shortcuts[shortcutChars.charAt(c)] = patternParts; } } } })(); var nPatterns = fallthroughStylePatterns.length; var notWs = /\S/; return function (sourceCode, opt_basePos) { opt_basePos = opt_basePos || 0; var decorations = [opt_basePos, PR_PLAIN]; var lastToken = ''; var pos = 0; // index into sourceCode var tail = sourceCode; while (tail.length) { var style; var token = null; var match; var patternParts = shortcuts[tail.charAt(0)]; if (patternParts) { match = tail.match(patternParts[1]); token = match[0]; style = patternParts[0]; } else { for (var i = 0; i < nPatterns; ++i) { patternParts = fallthroughStylePatterns[i]; var contextPattern = patternParts[2]; if (contextPattern && !contextPattern.test(lastToken)) { // rule can't be used continue; } match = tail.match(patternParts[1]); if (match) { token = match[0]; style = patternParts[0]; break; } } if (!token) { // make sure that we make progress style = PR_PLAIN; token = tail.substring(0, 1); } } decorations.push(opt_basePos + pos, style); pos += token.length; tail = tail.substring(token.length); if (style !== PR_COMMENT && notWs.test(token)) { lastToken = token; } } return decorations; }; } var PR_MARKUP_LEXER = createSimpleLexer([], [ [PR_PLAIN, /^[^<]+/, null], [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/, null], [PR_COMMENT, /^<!--[\s\S]*?(?:-->|$)/, null], [PR_SOURCE, /^<\?[\s\S]*?(?:\?>|$)/, null], [PR_SOURCE, /^<%[\s\S]*?(?:%>|$)/, null], [PR_SOURCE, // Tags whose content is not escaped, and which contain source code. /^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i, null], [PR_TAG, /^<\/?\w[^<>]*>/, null] ]); // Splits any of the source|style|xmp entries above into a start tag, // source content, and end tag. var PR_SOURCE_CHUNK_PARTS = /^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/; /** split markup on tags, comments, application directives, and other top * level constructs. Tags are returned as a single token - attributes are * not yet broken out. * @private */ function tokenizeMarkup(source) { var decorations = PR_MARKUP_LEXER(source); for (var i = 0; i < decorations.length; i += 2) { if (decorations[i + 1] === PR_SOURCE) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; // Split out start and end script tags as actual tags, and leave the // body with style SCRIPT. var sourceChunk = source.substring(start, end); var match = sourceChunk.match(PR_SOURCE_CHUNK_PARTS); if (match) { decorations.splice( i, 2, start, PR_TAG, // the open chunk start + match[1].length, PR_SOURCE, start + match[1].length + (match[2] || '').length, PR_TAG); } } } return decorations; } var PR_TAG_LEXER = createSimpleLexer([ [PR_ATTRIB_VALUE, /^\'[^\']*(?:\'|$)/, null, "'"], [PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'], [PR_PUNCTUATION, /^[<>\/=]+/, null, '<>/='] ], [ [PR_TAG, /^[\w:\-]+/, /^</], [PR_ATTRIB_VALUE, /^[\w\-]+/, /^=/], [PR_ATTRIB_NAME, /^[\w:\-]+/, null], [PR_PLAIN, /^\s+/, null, ' \t\r\n'] ]); /** split tags attributes and their values out from the tag name, and * recursively lex source chunks. * @private */ function splitTagAttributes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_TAG) { var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var chunk = source.substring(start, end); var subDecorations = PR_TAG_LEXER(chunk, start); spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } /** returns a function that produces a list of decorations from source text. * * This code treats ", ', and ` as string delimiters, and \ as a string * escape. It does not recognize perl's qq() style strings. * It has no special handling for double delimiter escapes as in basic, or * the tripled delimiters used in python, but should work on those regardless * although in those cases a single string literal may be broken up into * multiple adjacent string literals. * * It recognizes C, C++, and shell style comments. * * @param {Object} options a set of optional parameters. * @return {function (string) : Array.<string|number>} a * decorator that takes sourceCode as plain text and that returns a * decoration list */ function sourceDecorator(options) { var shortcutStylePatterns = [], fallthroughStylePatterns = []; if (options.tripleQuotedStrings) { // '''multi-line-string''', 'single-line-string', and double-quoted shortcutStylePatterns.push( [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null, '\'"']); } else if (options.multiLineStrings) { // 'multi-line-string', "multi-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, null, '\'"`']); } else { // 'single-line-string', "single-line-string" shortcutStylePatterns.push( [PR_STRING, /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"\'']); } fallthroughStylePatterns.push( [PR_PLAIN, /^(?:[^\'\"\`\/\#]+)/, null, ' \r\n']); if (options.hashComments) { shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']); } if (options.cStyleComments) { fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]); fallthroughStylePatterns.push( [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); } if (options.regexLiterals) { var REGEX_LITERAL = ( // A regular expression literal starts with a slash that is // not followed by * or / so that it is not confused with // comments. '^/(?=[^/*])' // and then contains any number of raw characters, + '(?:[^/\\x5B\\x5C]' // escape sequences (\x5C), + '|\\x5C[\\s\\S]' // or non-nesting character sets (\x5B\x5D); + '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+' // finally closed by a /. + '(?:/|$)'); fallthroughStylePatterns.push( [PR_STRING, new RegExp(REGEX_LITERAL), REGEXP_PRECEDER_PATTERN]); } var keywords = wordSet(options.keywords); options = null; /** splits the given string into comment, string, and "other" tokens. * @param {string} sourceCode as plain text * @return {Array.<number|string>} a decoration list. * @private */ var splitStringAndCommentTokens = createSimpleLexer( shortcutStylePatterns, fallthroughStylePatterns); var styleLiteralIdentifierPuncRecognizer = createSimpleLexer([], [ [PR_PLAIN, /^\s+/, null, ' \r\n'], // TODO(mikesamuel): recognize non-latin letters and numerals in idents [PR_PLAIN, /^[a-z_$@][a-z_$@0-9]*/i, null], // A hex number [PR_LITERAL, /^0x[a-f0-9]+[a-z]/i, null], // An octal or decimal number, possibly in scientific notation [PR_LITERAL, /^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i, null, '123456789'], [PR_PUNCTUATION, /^[^\s\w\.$@]+/, null] // Fallback will handle decimal points not adjacent to a digit ]); /** splits plain text tokens into more specific tokens, and then tries to * recognize keywords, and types. * @private */ function splitNonStringNonCommentTokens(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_PLAIN) { var start, end, chunk, subDecs; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; chunk = source.substring(start, end); subDecs = styleLiteralIdentifierPuncRecognizer(chunk, start); for (var j = 0, m = subDecs.length; j < m; j += 2) { var subStyle = subDecs[j + 1]; if (subStyle === PR_PLAIN) { var subStart = subDecs[j]; var subEnd = j + 2 < m ? subDecs[j + 2] : chunk.length; var token = source.substring(subStart, subEnd); if (token === '.') { subDecs[j + 1] = PR_PUNCTUATION; } else if (token in keywords) { subDecs[j + 1] = PR_KEYWORD; } else if (/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(token)) { // classify types and annotations using Java's style conventions subDecs[j + 1] = token.charAt(0) === '@' ? PR_LITERAL : PR_TYPE; } } } spliceArrayInto(subDecs, decorations, i, 2); i += subDecs.length - 2; } } return decorations; } return function (sourceCode) { // Split into strings, comments, and other. // We do this because strings and comments are easily recognizable and can // contain stuff that looks like other tokens, so we want to mark those // early so we don't recurse into them. var decorations = splitStringAndCommentTokens(sourceCode); // Split non comment|string tokens on whitespace and word boundaries decorations = splitNonStringNonCommentTokens(sourceCode, decorations); return decorations; }; } var decorateSource = sourceDecorator({ keywords: ALL_KEYWORDS, hashComments: true, cStyleComments: true, multiLineStrings: true, regexLiterals: true }); /** identify regions of markup that are really source code, and recursivley * lex them. * @private */ function splitSourceNodes(source, decorations) { for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; if (style === PR_SOURCE) { // Recurse using the non-markup lexer var start, end; start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var subDecorations = decorateSource(source.substring(start, end)); for (var j = 0, m = subDecorations.length; j < m; j += 2) { subDecorations[j] += start; } spliceArrayInto(subDecorations, decorations, i, 2); i += subDecorations.length - 2; } } return decorations; } /** identify attribute values that really contain source code and recursively * lex them. * @private */ function splitSourceAttributes(source, decorations) { var nextValueIsSource = false; for (var i = 0; i < decorations.length; i += 2) { var style = decorations[i + 1]; var start, end; if (style === PR_ATTRIB_NAME) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; nextValueIsSource = /^on|^style$/i.test(source.substring(start, end)); } else if (style === PR_ATTRIB_VALUE) { if (nextValueIsSource) { start = decorations[i]; end = i + 2 < decorations.length ? decorations[i + 2] : source.length; var attribValue = source.substring(start, end); var attribLen = attribValue.length; var quoted = (attribLen >= 2 && /^[\"\']/.test(attribValue) && attribValue.charAt(0) === attribValue.charAt(attribLen - 1)); var attribSource; var attribSourceStart; var attribSourceEnd; if (quoted) { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue; } else { attribSourceStart = start + 1; attribSourceEnd = end - 1; attribSource = attribValue.substring(1, attribValue.length - 1); } var attribSourceDecorations = decorateSource(attribSource); for (var j = 0, m = attribSourceDecorations.length; j < m; j += 2) { attribSourceDecorations[j] += attribSourceStart; } if (quoted) { attribSourceDecorations.push(attribSourceEnd, PR_ATTRIB_VALUE); spliceArrayInto(attribSourceDecorations, decorations, i + 2, 0); } else { spliceArrayInto(attribSourceDecorations, decorations, i, 2); } } nextValueIsSource = false; } } return decorations; } /** returns a decoration list given a string of markup. * * This code recognizes a number of constructs. * <!-- ... --> comment * <!\w ... > declaration * <\w ... > tag * </\w ... > tag * <?...?> embedded source * <%...%> embedded source * &[#\w]...; entity * * It does not recognizes %foo; doctype entities from . * * It will recurse into any <style>, <script>, and on* attributes using * PR_lexSource. */ function decorateMarkup(sourceCode) { // This function works as follows: // 1) Start by splitting the markup into text and tag chunks // Input: string s // Output: List<PR_Token> where style in (PR_PLAIN, null) // 2) Then split the text chunks further into comments, declarations, // tags, etc. // After each split, consider whether the token is the start of an // embedded source section, i.e. is an open <script> tag. If it is, find // the corresponding close token, and don't bother to lex in between. // Input: List<string> // Output: List<PR_Token> with style in // (PR_TAG, PR_PLAIN, PR_SOURCE, null) // 3) Finally go over each tag token and split out attribute names and // values. // Input: List<PR_Token> // Output: List<PR_Token> where style in // (PR_TAG, PR_PLAIN, PR_SOURCE, NAME, VALUE, null) var decorations = tokenizeMarkup(sourceCode); decorations = splitTagAttributes(sourceCode, decorations); decorations = splitSourceNodes(sourceCode, decorations); decorations = splitSourceAttributes(sourceCode, decorations); return decorations; } /** * @param {string} sourceText plain text * @param {Array.<number|string>} extractedTags chunks of raw html preceded * by their position in sourceText in order. * @param {Array.<number|string>} decorations style classes preceded by their * position in sourceText in order. * @return {string} html * @private */ function recombineTagsAndDecorations(sourceText, extractedTags, decorations) { var html = []; // index past the last char in sourceText written to html var outputIdx = 0; var openDecoration = null; var currentDecoration = null; var tagPos = 0; // index into extractedTags var decPos = 0; // index into decorations var tabExpander = makeTabExpander(PR_TAB_WIDTH); var adjacentSpaceRe = /([\r\n ]) /g; var startOrSpaceRe = /(^| ) /gm; var newlineRe = /\r\n?|\n/g; var trailingSpaceRe = /[ \r\n]$/; var lastWasSpace = true; // the last text chunk emitted ended with a space. // A helper function that is responsible for opening sections of decoration // and outputing properly escaped chunks of source function emitTextUpTo(sourceIdx) { if (sourceIdx > outputIdx) { if (openDecoration && openDecoration !== currentDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } if (!openDecoration && currentDecoration) { openDecoration = currentDecoration; html.push('<span class="', openDecoration, '">'); } // This interacts badly with some wikis which introduces paragraph tags // into pre blocks for some strange reason. // It's necessary for IE though which seems to lose the preformattedness // of <pre> tags when their innerHTML is assigned. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html // and it serves to undo the conversion of <br>s to newlines done in // chunkify. var htmlChunk = textToHtml( tabExpander(sourceText.substring(outputIdx, sourceIdx))) .replace(lastWasSpace ? startOrSpaceRe : adjacentSpaceRe, '$1&nbsp;'); // Keep track of whether we need to escape space at the beginning of the // next chunk. lastWasSpace = trailingSpaceRe.test(htmlChunk); html.push(htmlChunk.replace(newlineRe, '<br />')); outputIdx = sourceIdx; } } while (true) { // Determine if we're going to consume a tag this time around. Otherwise // we consume a decoration or exit. var outputTag; if (tagPos < extractedTags.length) { if (decPos < decorations.length) { // Pick one giving preference to extractedTags since we shouldn't open // a new style that we're going to have to immediately close in order // to output a tag. outputTag = extractedTags[tagPos] <= decorations[decPos]; } else { outputTag = true; } } else { outputTag = false; } // Consume either a decoration or a tag or exit. if (outputTag) { emitTextUpTo(extractedTags[tagPos]); if (openDecoration) { // Close the current decoration html.push('</span>'); openDecoration = null; } html.push(extractedTags[tagPos + 1]); tagPos += 2; } else if (decPos < decorations.length) { emitTextUpTo(decorations[decPos]); currentDecoration = decorations[decPos + 1]; decPos += 2; } else { break; } } emitTextUpTo(sourceText.length); if (openDecoration) { html.push('</span>'); } return html.join(''); } /** Maps language-specific file extensions to handlers. */ var langHandlerRegistry = {}; /** Register a language handler for the given file extensions. * @param {function (string) : Array.<number|string>} handler * a function from source code to a list of decorations. * @param {Array.<string>} fileExtensions */ function registerLangHandler(handler, fileExtensions) { for (var i = fileExtensions.length; --i >= 0;) { var ext = fileExtensions[i]; if (!langHandlerRegistry.hasOwnProperty(ext)) { langHandlerRegistry[ext] = handler; } else if ('console' in window) { console.log('cannot override language handler %s', ext); } } } registerLangHandler(decorateSource, ['default-code']); registerLangHandler(decorateMarkup, ['default-markup', 'html', 'htm', 'xhtml', 'xml', 'xsl']); registerLangHandler(sourceDecorator({ keywords: CPP_KEYWORDS, hashComments: true, cStyleComments: true }), ['c', 'cc', 'cpp', 'cxx', 'cyc']); registerLangHandler(sourceDecorator({ keywords: CSHARP_KEYWORDS, hashComments: true, cStyleComments: true }), ['cs']); registerLangHandler(sourceDecorator({ keywords: JAVA_KEYWORDS, cStyleComments: true }), ['java']); registerLangHandler(sourceDecorator({ keywords: SH_KEYWORDS, hashComments: true, multiLineStrings: true }), ['bsh', 'csh', 'sh']); registerLangHandler(sourceDecorator({ keywords: PYTHON_KEYWORDS, hashComments: true, multiLineStrings: true, tripleQuotedStrings: true }), ['cv', 'py']); registerLangHandler(sourceDecorator({ keywords: PERL_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['perl', 'pl', 'pm']); registerLangHandler(sourceDecorator({ keywords: RUBY_KEYWORDS, hashComments: true, multiLineStrings: true, regexLiterals: true }), ['rb']); registerLangHandler(sourceDecorator({ keywords: JSCRIPT_KEYWORDS, cStyleComments: true, regexLiterals: true }), ['js']); function prettyPrintOne(sourceCodeHtml, opt_langExtension) { try { // Extract tags, and convert the source code to plain text. var sourceAndExtractedTags = extractTags(sourceCodeHtml); /** Plain text. @type {string} */ var source = sourceAndExtractedTags.source; /** Even entries are positions in source in ascending order. Odd entries * are tags that were extracted at that position. * @type {Array.<number|string>} */ var extractedTags = sourceAndExtractedTags.tags; // Pick a lexer and apply it. if (!langHandlerRegistry.hasOwnProperty(opt_langExtension)) { // Treat it as markup if the first non whitespace character is a < and // the last non-whitespace character is a >. opt_langExtension = /^\s*</.test(source) ? 'default-markup' : 'default-code'; } /** Even entries are positions in source in ascending order. Odd enties * are style markers (e.g., PR_COMMENT) that run from that position until * the end. * @type {Array.<number|string>} */ var decorations = langHandlerRegistry[opt_langExtension].call({}, source); // Integrate the decorations and tags back into the source code to produce // a decorated html string. return recombineTagsAndDecorations(source, extractedTags, decorations); } catch (e) { if ('console' in window) { console.log(e); console.trace(); } return sourceCodeHtml; } } function prettyPrint(opt_whenDone) { var isIE6 = _pr_isIE6(); // fetch a list of nodes to rewrite var codeSegments = [ document.getElementsByTagName('pre'), document.getElementsByTagName('code'), document.getElementsByTagName('xmp') ]; var elements = []; for (var i = 0; i < codeSegments.length; ++i) { for (var j = 0; j < codeSegments[i].length; ++j) { elements.push(codeSegments[i][j]); } } codeSegments = null; // the loop is broken into a series of continuations to make sure that we // don't make the browser unresponsive when rewriting a large page. var k = 0; function doWork() { var endTime = (PR_SHOULD_USE_CONTINUATION ? new Date().getTime() + 250 /* ms */ : Infinity); for (; k < elements.length && new Date().getTime() < endTime; k++) { var cs = elements[k]; if (cs.className && cs.className.indexOf('prettyprint') >= 0) { // If the classes includes a language extensions, use it. // Language extensions can be specified like // <pre class="prettyprint lang-cpp"> // the language extension "cpp" is used to find a language handler as // passed to PR_registerLangHandler. var langExtension = cs.className.match(/\blang-(\w+)\b/); if (langExtension) { langExtension = langExtension[1]; } // make sure this is not nested in an already prettified element var nested = false; for (var p = cs.parentNode; p; p = p.parentNode) { if ((p.tagName === 'pre' || p.tagName === 'code' || p.tagName === 'xmp') && p.className && p.className.indexOf('prettyprint') >= 0) { nested = true; break; } } if (!nested) { // fetch the content as a snippet of properly escaped HTML. // Firefox adds newlines at the end. var content = getInnerHtml(cs); content = content.replace(/(?:\r\n?|\n)$/, ''); // do the pretty printing var newContent = prettyPrintOne(content, langExtension); // push the prettified html back into the tag. if (!isRawContent(cs)) { // just replace the old html with the new cs.innerHTML = newContent; } else { // we need to change the tag to a <pre> since <xmp>s do not allow // embedded tags such as the span tags used to attach styles to // sections of source code. var pre = document.createElement('PRE'); for (var i = 0; i < cs.attributes.length; ++i) { var a = cs.attributes[i]; if (a.specified) { var aname = a.name.toLowerCase(); if (aname === 'class') { pre.className = a.value; // For IE 6 } else { pre.setAttribute(a.name, a.value); } } } pre.innerHTML = newContent; // remove the old cs.parentNode.replaceChild(pre, cs); cs = pre; } // Replace <br>s with line-feeds so that copying and pasting works // on IE 6. // Doing this on other browsers breaks lots of stuff since \r\n is // treated as two newlines on Firefox, and doing this also slows // down rendering. if (isIE6 && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( document.createTextNode('\r\n'), lineBreak); } } } } } if (k < elements.length) { // finish up in a continuation setTimeout(doWork, 250); } else if (opt_whenDone) { opt_whenDone(); } } doWork(); } window['PR_normalizedHtml'] = normalizedHtml; window['prettyPrintOne'] = prettyPrintOne; window['prettyPrint'] = prettyPrint; window['PR'] = { 'createSimpleLexer': createSimpleLexer, 'registerLangHandler': registerLangHandler, 'sourceDecorator': sourceDecorator, 'PR_ATTRIB_NAME': PR_ATTRIB_NAME, 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE, 'PR_COMMENT': PR_COMMENT, 'PR_DECLARATION': PR_DECLARATION, 'PR_KEYWORD': PR_KEYWORD, 'PR_LITERAL': PR_LITERAL, 'PR_NOCODE': PR_NOCODE, 'PR_PLAIN': PR_PLAIN, 'PR_PUNCTUATION': PR_PUNCTUATION, 'PR_SOURCE': PR_SOURCE, 'PR_STRING': PR_STRING, 'PR_TAG': PR_TAG, 'PR_TYPE': PR_TYPE }; })();
JavaScript
// JavaScript Document function transformData(startPoint) { var branchLength = eval("Menu" + startPoint + "[3]"); for (var i=1; i <= branchLength; i++) { currentName = eval("Menu" + startPoint + "_" + i + "[0]"); currentNameId = currentName + "@" + startPoint + "_" + i; currentUrl = eval("Menu" + startPoint + "_" + i + "[1]"); parentName = (startPoint!=1) ? eval("Menu" + startPoint + "[0]") + "@" + startPoint : "TopLevel"; eval("topicsArray[\"" + currentNameId + "\"] = new topicElement(\"" + currentNameId + "\",\"" + currentUrl + "\",\"" + parentName + "\"); topicList[k++] = \"" + currentNameId + "\";"); if (eval('Menu' + startPoint + "_" + i + '[3]') != 0) transformData(startPoint + "_" + i); } } //transformData('1'); function revealTree(currentEntry) { if (currentEntry != document.title) { document.getElementById("aBeautifulCherryTree").insertBefore(document.getElementById(currentEntry+"Link").cloneNode(true), document.getElementById("aBeautifulCherryTree").firstChild); document.getElementById("aBeautifulCherryTree").innerHTML = "&nbsp;&gt;&nbsp;" + document.getElementById("aBeautifulCherryTree").innerHTML; document.getElementById("abbreviatedTree").insertBefore(document.getElementById(currentEntry+"Link").cloneNode(true), document.getElementById("abbreviatedTree").firstChild); document.getElementById("abbreviatedTree").innerHTML = "&nbsp; | &nbsp;" + document.getElementById("abbreviatedTree").innerHTML; } if(topicsArray[currentEntry].parentString != "TopLevel") { toggleCategory(topicsArray[currentEntry].parentString); revealTree(topicsArray[topicsArray[currentEntry].parentString].topic); } } function displaySubArticles(thisCategory) { if (document.getElementById(thisCategory+"MenuGroup")) { document.getElementById("categoryArticles").style.display = "block"; document.getElementById("categoryIdentifier").innerHTML = document.title; for(i=0; i<document.getElementById(thisCategory+"MenuGroup").childNodes.length; i++) { clonedNode = document.getElementById(thisCategory+"MenuGroup").childNodes[i].childNodes[0].cloneNode(true); clonedNode.id += "Copied"; cloneDaddy = document.createElement("li"); cloneDaddy.appendChild(clonedNode); document.getElementById("theSoundOfRunningWater").appendChild(cloneDaddy); } } else { document.getElementById("bufferDiv").appendChild(document.getElementById("categoryAlert")); } //alert(document.getElementById("theSoundOfRunningWater").firstChild.id); } function toggleCategory(thisCategory) { document.getElementById(thisCategory).lastChild.style.display = (document.getElementById(thisCategory).lastChild.style.display == "block") ? "none" : "block"; document.getElementById(thisCategory+"Toggler").style.backgroundImage = (document.getElementById(thisCategory+"Toggler").style.backgroundImage == "url(images/minus.gif)") ? "url(images/plus.gif)" : "url(images/minus.gif)"; //alert(document.getElementById(thisCategory).lastChild.id+" has children: "+document.getElementById(thisCategory).lastChild.firstChild.id); } function createListEntry(thisEntry) { listItemForThisEntry = document.createElement("div"); listItemForThisEntry.id = thisEntry.topic; dotForThisEntry = document.createElement("span"); dotForThisEntry.className = "menuEntryDotStyle"; linkForThisEntry = document.createElement("a"); linkForThisEntry.href = thisEntry.linkString; linkForThisEntry.id = thisEntry.topic+"Link"; pureString = thisEntry.topic.split("@"); textForTheLink = document.createTextNode(pureString[0]); linkForThisEntry.appendChild(textForTheLink); listItemForThisEntry.appendChild(linkForThisEntry); listItemForThisEntry.appendChild(dotForThisEntry); return listItemForThisEntry; } function createGroup(thisCategory) { if (thisCategory != "TopLevel") document.getElementById("bufferDiv").appendChild(document.getElementById(thisCategory).childNodes[1]); groupContainer = document.createElement("div"); groupContainer.id = thisCategory+"MenuGroup"; return groupContainer; } function createToggler(thisCategory) { groupToggler = document.createElement("span"); groupToggler.className = "plusSign"; groupToggler.style.backgroundImage = "url(images/plus.gif)"; groupToggler.id = thisCategory+"Toggler"; groupToggler.onclick = function(){toggleCategory(thisCategory)}; return groupToggler; } function minimizeToggle() { document.getElementById("TopLevel").style.display = (document.getElementById("TopLevel").style.display == "none") ? "block" : "none"; document.getElementById("dragMenuContainer").style.backgroundImage = (document.getElementById("dragMenuContainer").style.backgroundImage == "url(images/openmenu.gif)") ? "url(images/closemenu.gif)" : "url(images/openmenu.gif)"; } function assembleTheList() { for (i=0; i<topicList.length; i++) { parentElement = topicsArray[topicList[i]].parentString; processThisItem = (document.getElementById(topicsArray[topicList[i]].topic)) ? document.getElementById(topicsArray[topicList[i]].topic) : createListEntry(topicsArray[topicList[i]]); if(!document.getElementById(parentElement)) document.getElementById("bufferDiv").appendChild(createListEntry(topicsArray[parentElement])); if(!document.getElementById(parentElement+"MenuGroup")) { if (parentElement != "TopLevel") document.getElementById(parentElement).appendChild(createToggler(parentElement)); document.getElementById(parentElement).appendChild(createGroup(parentElement)); if (parentElement != "TopLevel") document.getElementById(parentElement+"MenuGroup").style.display = "none"; } document.getElementById(parentElement+"MenuGroup").appendChild(processThisItem); } currentNodeRef = (window.pageId) ? pageId+"@"+result : document.title; if (document.title != "The Warcraft Encyclopedia") { revealTree(currentNodeRef); document.getElementById(currentNodeRef+"Link").className = "currentArticleMenuStyle"; document.getElementById(currentNodeRef+"Link").style.color = "#ff6600"; } } function initializationSequence() { document.getElementById("headLine").innerHTML = document.title; document.getElementById("TopLevel").style.display = "none"; document.getElementById("dragMenuContainer").style.backgroundImage = "url(images/openmenu.gif)"; document.getElementById("avatarImageContainer").style.backgroundImage = "url(images/icons/"+topicsArray[topicsArray[document.title].parentString].linkString.split(".xml")[0]+".jpg)"; assembleTheList(); replaceText(); displaySubArticles(document.title); if(!document.getElementsByTagName("p")[0]) { document.getElementById("articleContentContainer").style.visibility = "hidden"; document.getElementById("categoryAlert").style.display = "none"; } }
JavaScript
/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. * CXS-Portal Usage: md5hash(input,output) * Recommend: input = password input field; output = hidden field */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function core_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the HMAC-MD5, of a key and some data */ function core_hmac_md5(key, data) { var bkey = str2binl(key); if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); var ipad = Array(16), opad = Array(16); for(var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); return core_md5(opad.concat(hash), 512 + 128); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ function str2binl(str) { var bin = new Array(); var mask = (1 << chrsz) - 1; for(var i = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); return bin; } /* * Convert an array of little-endian words to a string */ function binl2str(bin) { var str = ""; var mask = (1 << chrsz) - 1; for(var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); return str; } /* * Convert an array of little-endian words to a hex string. */ function binl2hex(binarray) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; } /* * Convert an array of little-endian words to a base-64 string */ function binl2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; for(var i = 0; i < binarray.length * 4; i += 3) { var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); for(var j = 0; j < 4; j++) { if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } return str; } function str_to_ent(str) { var result = ''; var i; for (i = 0; i < str.length; i++) { var c = str.charCodeAt(i); var tmp = ''; if (c > 255) { while (c >= 1) { tmp = "0123456789" . charAt(c % 10) + tmp; c = c / 10; } if (tmp == '') { tmp = "0"; } tmp = "#" + tmp; tmp = "&" + tmp; tmp = tmp + ";"; result += tmp; } else { result += str.charAt(i); } } return result; } function trim(s) { while (s.substring(0, 1) == ' ') { s = s.substring(1, s.length); } while (s.substring(s.length-1, s.length) == ' ') { s = s.substring(0, s.length-1); } return s; } function md5hash(input, output_html, output_utf, skip_empty) { if (navigator.userAgent.indexOf("Mozilla/") == 0 && parseInt(navigator.appVersion) >= 4) { var md5string = hex_md5(str_to_ent(trim(input.value))); output_html.value = md5string; if (output_utf) { md5string = hex_md5(trim(input.value)); output_utf.value = md5string; } if (!skip_empty) { // implemented like this to make sure un-updated templates behave as before input.value = ''; } } return true; }
JavaScript
function hideMenu(menuNum){ document.getElementById("menuContainer"+menuNum).style.display="none"; } function showMenu(menuNum){ document.getElementById("menuContainer"+menuNum).style.display="block"; } function newsCollapse(newsPost) { var obj; obj = document.getElementById(newsPost); if (obj.style.display != "block") obj.style.display = "block"; else obj.style.display = "none"; } function getexpirydate(nodays){ var UTCstring; Today = new Date(); nomilli=Date.parse(Today); Today.setTime(nomilli+nodays*24*60*60*1000); UTCstring = Today.toUTCString(); return UTCstring; } function getcookie(cookiename) { var cookiestring=""+document.cookie; var index1=cookiestring.indexOf(cookiename); if (index1==-1 || cookiename=="") return ""; var index2=cookiestring.indexOf(';',index1); if (index2==-1) index2=cookiestring.length; return unescape(cookiestring.substring(index1+cookiename.length+1,index2)); } function setcookie(name,value){ cookiestring=name+"="+escape(value)+";EXPIRES="+ getexpirydate(365)+";PATH="+SITE_PATH; document.cookie=cookiestring; } function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else expires = ""; document.cookie = name+"="+value+expires+"; path="+SITE_PATH; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function initTheme(e) { var cookie = readCookie("style"); var title = cookie ? cookie : getPreferredStyleSheet(); setActiveStyleSheet(title); } function setCookie (name, value, expires, path, domain, secure) { var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "/") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); document.cookie = curCookie; } function getCookie (name) { var prefix = name + '='; var c = document.cookie; var nullstring = ''; var cookieStartIndex = c.indexOf(prefix); if (cookieStartIndex == -1) return nullstring; var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length); if (cookieEndIndex == -1) cookieEndIndex = c.length; return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex)); } function deleteCookie (name, path, domain) { if (getCookie(name)) document.cookie = name + "=" + ((path) ? "; path=" + path : "/") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } function fixDate (date) { var base = new Date(0); var skew = base.getTime(); if (skew > 0) date.setTime(date.getTime() - skew); } function rememberMe (f) { var now = new Date(); fixDate(now); now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000); setCookie('mtcmtauth', f.author.value, now, '', HOST, ''); setCookie('mtcmtmail', f.email.value, now, '', HOST, ''); setCookie('mtcmthome', f.url.value, now, '', HOST, ''); } function forgetMe (f) { deleteCookie('mtcmtmail', '', HOST); deleteCookie('mtcmthome', '', HOST); deleteCookie('mtcmtauth', '', HOST); f.email.value = ''; f.author.value = ''; f.url.value = ''; } var menuCookie; var tempString; if(!(tempString = getcookie("menuCookie"))){ setcookie('menuCookie', '1 1 0 0 0 1 0 0'); menuCookie = [1, 1, 0, 0, 0, 1, 0, 0]; } else { menuCookie = tempString.split(" "); } var menuNames = ["menunews", "menuaccount", "menugameguide", "menuinteractive", "menumedia", "menuforums", "menucommunity", "menusupport"]; function toggleNewMenu(menuID) { var menuNum = parseInt(menuID)+1; var toggleState = menuCookie[menuID]; var menuName = menuNames[menuID]+ "-inner"; var collapseLink = menuNames[menuID]+ "-collapse"; var menuVisual = menuNames[menuID]+ "-icon"; var menuHeader = menuNames[menuID]+ "-header"; var menuButton = menuNames[menuID]+ "-button"; if (toggleState == 0) { try{showMenu(menuNum);}catch(err){} document.getElementById(menuName).style.visibility = "visible"; document.getElementById(menuName).style.display = "block"; document.getElementById(menuButton).className = "menu-button-on"; document.getElementById(collapseLink).className = "leftmenu-minuslink"; document.getElementById(menuVisual).className = menuNames[menuID]+ "-icon-on"; document.getElementById(menuHeader).className = menuNames[menuID]+ "-header-on"; menuCookie[menuID] = 1; } else { try{hidewMenu(menuNum);}catch(err){} document.getElementById(menuName).style.visibility = "hidden"; document.getElementById(menuName).style.display = "none"; document.getElementById(menuButton).className = "menu-button-off"; document.getElementById(collapseLink).className = "leftmenu-pluslink"; document.getElementById(menuVisual).className = menuNames[menuID]+ "-icon-off"; document.getElementById(menuHeader).className = menuNames[menuID]+ "-header-off"; menuCookie[menuID] = 0; } var theString = menuCookie[0] + " " +menuCookie[1]+ " " +menuCookie[2]+ " " +menuCookie[3]+ " " +menuCookie[4]+ " " +menuCookie[5] + " " +menuCookie[6] + " " +menuCookie[7]; setcookie('menuCookie', theString); } function dummyFunction(){} function toggleEntry(newsID,alt) { var newsEntry = "news"+newsID; var collapseLink = "plus"+newsID; if (document.getElementById(newsEntry).className == 'news-expand') { document.getElementById(newsEntry).className = "news-collapse"+alt; setcookie(newsEntry, "0"); } else { document.getElementById(newsEntry).className = "news-expand"; setcookie(newsEntry, "1"); } } function clearFiller(menuNum) { document.getElementById("menuFiller" + menuNum).style.visibility="hidden"; } bgTimeout = null; function changeNavBgPos() { var n, e; e = n = document.getElementById("nav"); y = 0; x = 0; if (e.offsetParent) { while (e.offsetParent) { y += e.offsetTop; x += e.offsetLeft; e = e.offsetParent; } } else if (e.x && e.y) { y += e.y; x += e.x; } n.style.backgroundPosition = (x*-1) + "px " + (y*-1) + "px"; } function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent) { var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } }
JavaScript
window.onload = function fixActiveX () { if(navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf('Opera') == -1) { var changeElements = new Array(3); changeElements[0] = "applet"; changeElements[1] = "embed"; changeElements[2] = "object"; //mooooooo! offScreenBuffer = document.createElement("div"); for (i = 0; i < changeElements.length; i++) { thisTypeElements = document.getElementsByTagName(changeElements[i]); elementsLength = thisTypeElements.length; for (j = 0; j < elementsLength; j++ ) { totalString = ""; eatMe(thisTypeElements[j]); newContainer = document.createElement("div"); oldElement = thisTypeElements[j]; newContainer.innerHTML = totalString; oldElement.parentNode.insertBefore(newContainer,oldElement); offScreenBuffer.appendChild(oldElement); } } clearBuffer = window.setInterval("biteMe()", 500); } } function biteMe() { while(offScreenBuffer.hasChildNodes()) { offScreenBuffer.removeChild(offScreenBuffer.firstChild); } window.clearInterval(clearBuffer); } function eatMe(thisElement) { if(thisElement.childNodes.length>0) { totalString = "<"+thisElement.nodeName; parentAttributesLength = thisElement.attributes.length; for (k=0; k<parentAttributesLength; k++) { if(thisElement.attributes[k].nodeValue != null && thisElement.attributes[k].nodeValue != "") totalString += " "+ thisElement.attributes[k].nodeName +" = "+ thisElement.attributes[k].nodeValue; } totalString += ">"; parentLength = thisElement.childNodes.length; for(k=0; k<parentLength; k++) { eatMe(thisElement.childNodes[k]); } totalString += "</"+thisElement.nodeName+">"; } else processElement(thisElement); } function processElement(thisElement) { subElementString = "<"+thisElement.nodeName; attributesLength = thisElement.attributes.length; for (l=0; l<attributesLength; l++) { if(thisElement.attributes[l].nodeValue != null && thisElement.attributes[l].nodeValue != "") subElementString += " "+ thisElement.attributes[l].nodeName +" = "+ thisElement.attributes[l].nodeValue; } subElementString += "></"+thisElement.nodeName+">"; totalString += subElementString; }
JavaScript
/* ------------------------------------------------ PVII Equal CSS Columns scripts -Version 2 Copyright (c) 2005 Project Seven Development www.projectseven.com Version: 2.1.0 ------------------------------------------------ */ function P7_colH2(){ //v2.1.0 by PVII-www.projectseven.com var i,oh,h=0,tg,el,np,dA=document.p7eqc,an=document.p7eqa;if(dA&&dA.length){ for(i=1;i<dA.length;i+=2){dA[i+1].style.paddingBottom='';}for(i=1;i<dA.length;i+=2){ oh=dA[i].offsetHeight;h=(oh>h)?oh:h;}for(i=1;i<dA.length;i+=2){oh=dA[i].offsetHeight; if(oh<h){np=h-oh;if(!an&&dA[0]==1){P7_eqA2(dA[i+1].id,0,np);}else{ dA[i+1].style.paddingBottom=np+"px";}}}document.p7eqa=1; document.p7eqth=document.body.offsetHeight; document.p7eqtw=document.body.offsetWidth;} } function P7_eqT2(){ //v2.1.0 by PVII-www.projectseven.com if(document.p7eqth!=document.body.offsetHeight||document.p7eqtw!=document.body.offsetWidth){P7_colH2();} } function P7_equalCols2(){ //v2.1.0 by PVII-www.projectseven.com var c,e,el;if(document.getElementById){document.p7eqc=new Array(); document.p7eqc[0]=arguments[0];for(i=1;i<arguments.length;i+=2){el=null; c=document.getElementById(arguments[i]);if(c){e=c.getElementsByTagName(arguments[i+1]); if(e){el=e[e.length-1];if(!el.id){el.id="p7eq"+i;}}}if(c&&el){ document.p7eqc[document.p7eqc.length]=c;document.p7eqc[document.p7eqc.length]=el}} setInterval("P7_eqT2()",10);} } function P7_eqA2(el,p,pt){ //v2.1.0 by PVII-www.projectseven.com var sp=10,inc=20,g=document.getElementById(el);np=(p>=pt)?pt:p; g.style.paddingBottom=np+"px";if(np<pt){np+=inc; setTimeout("P7_eqA2('"+el+"',"+np+","+pt+")",sp);} }
JavaScript
var agt=navigator.userAgent.toLowerCase(); var appVer = navigator.appVersion.toLowerCase(); // *** BROWSER VERSION *** var is_minor = parseFloat(appVer); var is_major = parseInt(is_minor); // Note: On IE, start of appVersion return 3 or 4 // which supposedly is the version of Netscape it is compatible with. // So we look for the real version further on in the string var iePos = appVer.indexOf('msie'); if (iePos !=-1) { is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos))) is_major = parseInt(is_minor); } var is_getElementById = (document.getElementById) ? "true" : "false"; // 001121-abk var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false"; // 001127-abk var is_documentElement = (document.documentElement) ? "true" : "false"; // 001121-abk var is_gecko = ((navigator.product)&&(navigator.product.toLowerCase()=="gecko"))?true:false; var is_gver = 0; if (is_gecko) is_gver=navigator.productSub; var is_moz = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1) && (is_gecko) && ((navigator.vendor=="")||(navigator.vendor=="Mozilla"))); if (is_moz) { var is_moz_ver = (navigator.vendorSub)?navigator.vendorSub:0; if(!(is_moz_ver)) { is_moz_ver = agt.indexOf('rv:'); is_moz_ver = agt.substring(is_moz_ver+3); is_paren = is_moz_ver.indexOf(')'); is_moz_ver = is_moz_ver.substring(0,is_paren); } is_minor = is_moz_ver; is_major = parseInt(is_moz_ver); } var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1) && (!(is_moz))); // Netscape6 is mozilla/5 + Netscape6/6.0!!! // Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20001108 Netscape6/6.0 // Changed this to use navigator.vendor/vendorSub - dmr 060502 // var nav6Pos = agt.indexOf('netscape6'); // if (nav6Pos !=-1) { if ((navigator.vendor)&& ((navigator.vendor=="Netscape6")||(navigator.vendor=="Netscape"))&& (is_nav)) { is_major = parseInt(navigator.vendorSub); // here we need is_minor as a valid float for testing. We'll // revert to the actual content before printing the result. is_minor = parseFloat(navigator.vendorSub); } var is_opera = (agt.indexOf("opera") != -1); /* var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1); var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1); var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1); var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1); var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1); // new 020128- abk */ var is_opera7 = (agt.indexOf("opera 7") != -1 || agt.indexOf("opera/7") != -1); // new 021205- dmr /* var is_opera5up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4); var is_opera6up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5); // new020128 var is_opera7up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5 && !is_opera6); // new021205 -- dmr */ var is_nav2 = (is_nav && (is_major == 2)); var is_nav3 = (is_nav && (is_major == 3)); var is_nav4 = (is_nav && (is_major == 4)); var is_nav4up = (is_nav && is_minor >= 4); // changed to is_minor for // consistency - dmr, 011001 var is_navonly = (is_nav && ((agt.indexOf(";nav") != -1) || (agt.indexOf("; nav") != -1)) ); var is_nav6 = (is_nav && is_major==6); // new 010118 mhp var is_nav6up = (is_nav && is_minor >= 6) // new 010118 mhp var is_nav5 = (is_nav && is_major == 5 && !is_nav6); // checked for ns6 var is_nav5up = (is_nav && is_minor >= 5); var is_nav7 = (is_nav && is_major == 7); var is_nav7up = (is_nav && is_minor >= 7); var is_ie = ((iePos!=-1) && (!is_opera)); var is_ie3 = (is_ie && (is_major < 4)); // var is_ie4 = (is_ie && is_major == 4); var is_ie4up = (is_ie && is_minor >= 4); var is_ie5 = (is_ie && is_major == 5); var is_ie5up = (is_ie && is_minor >= 5); var is_ie5_5 = (is_ie && (agt.indexOf("msie 5.5") !=-1)); // 020128 new - abk var is_ie5_5up =(is_ie && is_minor >= 5.5); // 020128 new - abk var is_ie6 = (is_ie && is_major == 6); var is_ie6up = (is_ie && is_minor >= 6); // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser // or if this is the first browser window opened. Thus the // variables is_aol, is_aol3, and is_aol4 aren't 100% reliable. /* var is_aol = (agt.indexOf("aol") != -1); var is_aol3 = (is_aol && is_ie3); var is_aol4 = (is_aol && is_ie4); var is_aol5 = (agt.indexOf("aol 5") != -1); var is_aol6 = (agt.indexOf("aol 6") != -1); var is_aol7 = ((agt.indexOf("aol 7")!=-1) || (agt.indexOf("aol7")!=-1)); var is_aol8 = ((agt.indexOf("aol 8")!=-1) || (agt.indexOf("aol8")!=-1)); var is_webtv = (agt.indexOf("webtv") != -1); */ // new 020128 - abk /* var is_TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1)); var is_AOLTV = is_TVNavigator; */ /* var is_hotjava = (agt.indexOf("hotjava") != -1); var is_hotjava3 = (is_hotjava && (is_major == 3)); var is_hotjava3up = (is_hotjava && (is_major >= 3)); */ // end new // *** JAVASCRIPT VERSION CHECK *** // Useful to workaround Nav3 bug in which Nav3 // loads <SCRIPT LANGUAGE="JavaScript1.2">. // updated 020131 by dragle var is_js; if (is_nav2 || is_ie3) is_js = 1.0; else if (is_nav3) is_js = 1.1; // else if (is_opera5up) is_js = 1.3; // 020214 - dmr else if (is_opera) is_js = 1.1; /* else if ((is_nav4 && (is_minor <= 4.05)) || is_ie4) is_js = 1.2; else if ((is_nav4 && (is_minor > 4.05)) || is_ie5) is_js = 1.3; else if (is_nav5 && !(is_nav6)) is_js = 1.4; else if (is_hotjava3up) is_js = 1.4; // new 020128 - abk else if (is_nav6up) is_js = 1.5; */ // NOTE: In the future, update this code when newer versions of JS // are released. For now, we try to provide some upward compatibility // so that future versions of Nav and IE will show they are at // *least* JS 1.x capable. Always check for JS version compatibility // with > or >=. else if (is_nav && (is_major > 5)) is_js = 1.4; else if (is_ie && (is_major > 5)) is_js = 1.3; else if (is_moz) is_js = 1.5; // what about ie6 and ie6up for js version? abk // HACK: no idea for other browsers; always check for JS version // with > or >= else is_js = 0.0; // HACK FOR IE5 MAC = js vers = 1.4 (if put inside if/else jumps out at 1.3) if ((agt.indexOf("mac")!=-1) && is_ie5up) is_js = 1.4; // 020128 - abk // Done with is_minor testing; revert to real for N6/7 if (is_nav6up) { is_minor = navigator.vendorSub; } // *** PLATFORM *** var is_win = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) ); // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all // Win32, so you can't distinguish between Win95 and WinNT. // var is_win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1)); // is this a 16 bit compiled version? /*var is_win16 = ((agt.indexOf("win16")!=-1) || (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("windows 16-bit")!=-1) ); var is_win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) || (agt.indexOf("windows 16-bit")!=-1));*/ /*var is_winme = ((agt.indexOf("win 9x 4.90")!=-1)); // new 020128 - abk var is_win2k = ((agt.indexOf("windows nt 5.0")!=-1) || (agt.indexOf("windows 2000")!=-1)); // 020214 - dmr var is_winxp = ((agt.indexOf("windows nt 5.1")!=-1) || (agt.indexOf("windows xp")!=-1)); // 020214 - dmr*/ // NOTE: Reliable detection of Win98 may not be possible. It appears that: // - On Nav 4.x and before you'll get plain "Windows" in userAgent. // - On Mercury client, the 32-bit version will return "Win98", but // the 16-bit version running on Win98 will still return "Win95". /* var is_win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1)); var is_winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1)); var is_win32 = (is_win95 || is_winnt || is_win98 || ((is_major >= 4) && (navigator.platform == "Win32")) || (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1)); var is_os2 = ((agt.indexOf("os/2")!=-1) || (navigator.appVersion.indexOf("OS/2")!=-1) || (agt.indexOf("ibm-webexplorer")!=-1)); */ var is_mac = (agt.indexOf("mac")!=-1); if (is_mac) { is_win = !is_mac; } // dmr - 06/20/2002 var is_mac68k = (is_mac && ((agt.indexOf("68k")!=-1) || (agt.indexOf("68000")!=-1))); var is_macppc = (is_mac && ((agt.indexOf("ppc")!=-1) || (agt.indexOf("powerpc")!=-1))); var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false; /* var is_sun = (agt.indexOf("sunos")!=-1); var is_sun4 = (agt.indexOf("sunos 4")!=-1); var is_sun5 = (agt.indexOf("sunos 5")!=-1); var is_suni86= (is_sun && (agt.indexOf("i86")!=-1)); var is_irix = (agt.indexOf("irix") !=-1); // SGI var is_irix5 = (agt.indexOf("irix 5") !=-1); var is_irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1)); var is_hpux = (agt.indexOf("hp-ux")!=-1); var is_hpux9 = (is_hpux && (agt.indexOf("09.")!=-1)); var is_hpux10= (is_hpux && (agt.indexOf("10.")!=-1)); var is_aix = (agt.indexOf("aix") !=-1); // IBM var is_aix1 = (agt.indexOf("aix 1") !=-1); var is_aix2 = (agt.indexOf("aix 2") !=-1); var is_aix3 = (agt.indexOf("aix 3") !=-1); var is_aix4 = (agt.indexOf("aix 4") !=-1); var is_linux = (agt.indexOf("inux")!=-1); var is_sco = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1); var is_unixware = (agt.indexOf("unix_system_v")!=-1); var is_mpras = (agt.indexOf("ncr")!=-1); var is_reliant = (agt.indexOf("reliantunix")!=-1); var is_dec = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) || (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) || (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1)); var is_sinix = (agt.indexOf("sinix")!=-1); var is_freebsd = (agt.indexOf("freebsd")!=-1); var is_bsd = (agt.indexOf("bsd")!=-1); var is_unix = ((agt.indexOf("x11")!=-1) || is_sun || is_irix || is_hpux || is_sco ||is_unixware || is_mpras || is_reliant || is_dec || is_sinix || is_aix || is_linux || is_bsd || is_freebsd); var is_vms = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1)); */// additional checks, abk var is_anchors = (document.anchors) ? "true":"false"; var is_regexp = (window.RegExp) ? "true":"false"; var is_option = (window.Option) ? "true":"false"; var is_all = (document.all) ? "true":"false"; // cookies - 990624 - abk document.cookie = "cookies=true"; var is_cookie = (document.cookie) ? "true" : "false"; var is_images = (document.images) ? "true":"false"; var is_layers = (document.layers) ? "true":"false"; // gecko m7 bug? // new doc obj tests 990624-abk var is_forms = (document.forms) ? "true" : "false"; var is_links = (document.links) ? "true" : "false"; var is_frames = (window.frames) ? "true" : "false"; var is_screen = (window.screen) ? "true" : "false"; // java var is_java = (navigator.javaEnabled()); // Flash checking code based adapted from Doc JavaScript information; // see http://webref.com/js/column84/2.html var is_Flash = false; var is_FlashVersion = 0; if ((is_nav||is_opera||is_moz)|| (is_mac&&is_ie5up)) { var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0; if (plugin) { is_Flash = true; is_FlashVersion = parseInt(plugin.description.substring(plugin.description.indexOf(".")-1)); } } /* if (is_win&&is_ie4up) { document.write( '<scr' + 'ipt language=VBScript>' + '\n' + 'Dim hasPlayer, playerversion' + '\n' + 'hasPlayer = false' + '\n' + 'playerversion = 10' + '\n' + 'Do While playerversion > 0' + '\n' + 'On Error Resume Next' + '\n' + 'hasPlayer = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & playerversion)))' + '\n' + 'If hasPlayer = true Then Exit Do' + '\n' + 'playerversion = playerversion - 1' + '\n' + 'Loop' + '\n' + 'is_FlashVersion = playerversion' + '\n' + 'is_Flash = hasPlayer' + '\n' + '<\/sc' + 'ript>' ); } */
JavaScript
function topicElement(topic, linkString, parentString, synonymsArray) { this.topic = topic; this.linkString = linkString; this.parentString = parentString; this.synonymsArray = synonymsArray; } //topicsArray[""] = new topicElement("","",""); topicList[k++] = ""; topicsArray = new Object(); topicList = new Array(); k = 0; topicsArray["Alleria Windrunner"] = new topicElement("Alleria Windrunner","315.xml","High Elves and Blood Elves",new Array("Alleria")); topicList[k++] = "Alleria Windrunner"; topicsArray["Anasterian Sunstrider"] = new topicElement("Anasterian Sunstrider","319.xml","High Elves and Blood Elves"); topicList[k++] = "Anasterian Sunstrider"; topicsArray["Azeroth"] = new topicElement("Azeroth","327.xml","The Warcraft Universe"); topicList[k++] = "Azeroth"; topicsArray["Azshara"] = new topicElement("Azshara","330.xml","Demigods"); topicList[k++] = "Azshara"; topicsArray["Blood Elves"] = new topicElement("Blood Elves","338.xml","High Elves and Blood Elves",new Array("blood elf")); topicList[k++] = "Blood Elves"; topicsArray["Burning Legion"] = new topicElement("Burning Legion","346.xml","Factions"); topicList[k++] = "Burning Legion"; topicsArray["Cenarion Circle"] = new topicElement("Cenarion Circle","349.xml","Factions"); topicList[k++] = "Cenarion Circle"; topicsArray["Cenarius"] = new topicElement("Cenarius","350.xml","Demigods"); topicList[k++] = "Cenarius"; topicsArray["Darnassian"] = new topicElement("Darnassian","361.xml","Languages"); topicList[k++] = "Darnassian"; topicsArray["Dath'Remar Sunstrider"] = new topicElement("Dath'Remar Sunstrider","363.xml","High Elves and Blood Elves"); topicList[k++] = "Dath'Remar Sunstrider"; topicsArray["Dejahna"] = new topicElement("Dejahna","367.xml","Night Elves"); topicList[k++] = "Dejahna"; topicsArray["Demigods"] = new topicElement("Demigods","369.xml","Immortals",new Array("demigod")); topicList[k++] = "Demigods"; topicsArray["Demons"] = new topicElement("Demons","371.xml","Immortals",new Array("demon")); topicList[k++] = "Demons"; topicsArray["Desdel Stareye"] = new topicElement("Desdel Stareye","785.xml","Night Elves"); topicList[k++] = "Desdel Stareye"; topicsArray["Druid"] = new topicElement("Druid","381.xml","Vocations",new Array("druids","druidism")); topicList[k++] = "Druid"; topicsArray["Elune"] = new topicElement("Elune","392.xml","Gods"); topicList[k++] = "Elune"; topicsArray["Emerald Dream"] = new topicElement("Emerald Dream","394.xml","The Warcraft Universe"); topicList[k++] = "Emerald Dream"; topicsArray["Factions"] = new topicElement("Factions","400.xml","TopLevel"); topicList[k++] = "Factions"; topicsArray["Fandral Staghelm"] = new topicElement("Fandral Staghelm","401.xml","Night Elves"); topicList[k++] = "Fandral Staghelm"; topicsArray["Farstriders"] = new topicElement("Farstriders","402.xml","Factions"); topicList[k++] = "Farstriders"; topicsArray["Gods"] = new topicElement("Gods","417.xml","Immortals",new Array("goddess")); topicList[k++] = "Gods"; topicsArray["High Elves"] = new topicElement("High Elves","429.xml","High Elves and Blood Elves",new Array("high elf")); topicList[k++] = "High Elves"; topicsArray["High Elves and Blood Elves"] = new topicElement("High Elves and Blood Elves","339.xml","Mortal Races"); topicList[k++] = "High Elves and Blood Elves"; topicsArray["Highborne"] = new topicElement("Highborne","430.xml","Factions"); topicList[k++] = "Highborne"; topicsArray["Illidan Stormrage"] = new topicElement("Illidan Stormrage","441.xml","Demons"); topicList[k++] = "Illidan Stormrage"; topicsArray["Immortals"] = new topicElement("Immortals","442.xml","TopLevel",new Array("immortal","immortality")); topicList[k++] = "Immortals"; topicsArray["Jarod Shadowsong"] = new topicElement("Jarod Shadowsong","449.xml","Night Elves",new Array("Jarod")); topicList[k++] = "Jarod Shadowsong"; topicsArray["Kael'thas Sunstrider"] = new topicElement("Kael'thas Sunstrider","451.xml","High Elves and Blood Elves"); topicList[k++] = "Kael'thas Sunstrider"; topicsArray["Kur'talos Ravencrest"] = new topicElement("Kur'talos Ravencrest","463.xml","Night Elves"); topicList[k++] = "Kur'talos Ravencrest"; topicsArray["Languages"] = new topicElement("Languages","577.xml","TopLevel"); topicList[k++] = "Languages"; topicsArray["Latosius"] = new topicElement("Latosius","464.xml","Night Elves"); topicList[k++] = "Latosius"; topicsArray["Maiev Shadowsong"] = new topicElement("Maiev Shadowsong","472.xml","Night Elves",new Array("Maiev")); topicList[k++] = "Maiev Shadowsong"; topicsArray["Malfurion Stormrage"] = new topicElement("Malfurion Stormrage","474.xml","Night Elves",new Array("Malfurion")); topicList[k++] = "Malfurion Stormrage"; topicsArray["Malorne"] = new topicElement("Malorne","475.xml","Demigods"); topicList[k++] = "Malorne"; topicsArray["Moon Guard"] = new topicElement("Moon Guard","481.xml","Factions"); topicList[k++] = "Moon Guard"; topicsArray["Mortal Races"] = new topicElement("Mortal Races","545.xml","TopLevel"); topicList[k++] = "Mortal Races"; topicsArray["Naga"] = new topicElement("Naga","487.xml","Mortal Races"); topicList[k++] = "Naga"; topicsArray["Night Elves"] = new topicElement("Night Elves","508.xml","Mortal Races",new Array("night elf")); topicList[k++] = "Night Elves"; topicsArray["Satyrs"] = new topicElement("Satyrs","540.xml","Demons",new Array("satyr")); topicList[k++] = "Satyrs"; topicsArray["Sentinels"] = new topicElement("Sentinels","546.xml","Factions"); topicList[k++] = "Sentinels"; topicsArray["Sisterhood of Elune"] = new topicElement("Sisterhood of Elune","554.xml","Factions",new Array("sisters of elune")); topicList[k++] = "Sisterhood of Elune"; topicsArray["Thalassian"] = new topicElement("Thalassian","576.xml","Languages"); topicList[k++] = "Thalassian"; topicsArray["The Warcraft Universe"] = new topicElement("The Warcraft Universe","580.xml","TopLevel"); topicList[k++] = "The Warcraft Universe"; topicsArray["Twisting Nether"] = new topicElement("Twisting Nether","594.xml","The Warcraft Universe"); topicList[k++] = "Twisting Nether"; topicsArray["Tyrande Whisperwind"] = new topicElement("Tyrande Whisperwind","598.xml","Night Elves"); topicList[k++] = "Tyrande Whisperwind"; topicsArray["Valstann Staghelm"] = new topicElement("Valstann Staghelm","608.xml","Night Elves"); topicList[k++] = "Valstann Staghelm"; topicsArray["Vashj"] = new topicElement("Vashj","610.xml","Naga"); topicList[k++] = "Vashj"; topicsArray["Vereesa Windrunner"] = new topicElement("Vereesa Windrunner","611.xml","High Elves and Blood Elves",new Array("Vereesa")); topicList[k++] = "Vereesa Windrunner"; topicsArray["Vocations"] = new topicElement("Vocations","612.xml","TopLevel"); topicList[k++] = "Vocations"; topicsArray["Watchers"] = new topicElement("Watchers","624.xml","Factions"); topicList[k++] = "Watchers"; topicsArray["Xavius"] = new topicElement("Xavius","634.xml","Demons"); topicList[k++] = "Xavius"; topicsArray["TopLevel"] = new topicElement("TopLevel","index.xml","TopLevel");
JavaScript
var global_nav_lang, opt; function buildtopnav(){ global_nav_lang = (global_nav_lang) ? global_nav_lang.toLowerCase() : ""; linkarray = new Array(); outstring = ""; link1 = new Object(); link2 = new Object(); link3 = new Object(); switch(global_nav_lang){ case "de_de": link2.text = "Das Arsenal" link3.text = "Foren" break; case "ru_ru": link2.text = "Оружейная" link3.text = "Форумы" break; case "fr_fr": link2.text = "l'Armurerie" link3.text = "Forums" break; default: link2.text = "Armory" link3.text = "Forums" break; } link1.text = site_name; link1.href = site_link; link2.href = armory_link; link3.href = forum_link; // linkarray.push(link1) linkarray.push(link2) linkarray.push(link3) for(i=0; i<linkarray.length; i++) { div = (i<linkarray.length-1) ? "<img src='templates/WotLK/images/topnav/topnav_div.gif'/>":"" outstring += "<a href='"+linkarray[i].href+ "'>"+ linkarray[i].text +"</a>"+div; } topnavguts = ""; topnavguts += "<div class='topnav'><div class='tn_interior'>"; topnavguts += outstring; topnavguts += "</div></div><div class='tn_push'></div>"; if(document.location.href) hrefString = document.location.href; else hrefString = document.location; divclass = (hrefString.indexOf("forums")>=0)?"tn_forums":(hrefString.indexOf("armory")>=0)?"tn_armory":"tn_wow"; targ = document.getElementById("shared_topnav"); if(targ != null) { targ.innerHTML = topnavguts; if(!targ.className || targ.className == ""){targ.className = divclass;} if(targ.className.indexOf("tn_armory")>=0){ if (!is_opera) {document.body.style.backgroundPosition = "50% 26px"; }} if(targ.className.indexOf("tn_forums")>=0){ document.body.style.backgroundPosition = "100% 26px"; } } } buildtopnav();
JavaScript
/* +-------------------------------------------------------------------+ | J S - T O O L T I P (v1.2) | | | | Copyright Gerd Tentler www.gerd-tentler.de/tools | | Created: Feb. 15, 2005 Last modified: Apr. 15, 2005 | +-------------------------------------------------------------------+ | This program may be used and hosted free of charge by anyone for | | personal purpose as long as this copyright notice remains intact. | | | | Obtain permission before selling the code for this program or | | hosting this software on a commercial website or redistributing | | this software over the Internet or in any other medium. In all | | cases copyright must remain intact. | +-------------------------------------------------------------------+ ====================================================================================================== This script was tested with the following systems and browsers: - Windows XP: IE 6, NN 4, NN 7, Opera 7, Firefox 1 - Mac OS X: IE 5, Safari 1 If you use another browser or system, this script may not work for you - sorry. ------------------------------------------------------------------------------------------------------ USAGE: Use the toolTip-function with mouse-over and mouse-out events (see example below). - To show a tooltip, use this syntax: toolTip(text, width in pixels, opacity in percent) Note: width and opacity are optional - To hide a tooltip, use this syntax: toolTip() ------------------------------------------------------------------------------------------------------ EXAMPLE: <a href="#" onMouseOver="toolTip('Just a test', 150)" onMouseOut="toolTip()">some text here</a> ====================================================================================================== */ function TOOLTIP() { //---------------------------------------------------------------------------------------------------- // Configuration //---------------------------------------------------------------------------------------------------- this.width = 250; // width (pixels) this.bgColor = '#F5F5F5'; // background color this.textColor = '#000000'; // text color this.borderColor = '#666666'; // border color this.opacity = 90; // opacity (percent) - doesn't work with all browsers this.cursorDistance = 15; // distance from cursor (pixels) // don't change this.text = ''; this.obj = 0; this.sobj = 0; this.active = false; // ------------------------------------------------------------------------------------------------------- // Functions // ------------------------------------------------------------------------------------------------------- this.create = function() { if(!this.sobj) this.init(); var t = '<div class=tooltip><div>' + this.text + '</div></div>'; if(document.layers) { t = '<table border=0 cellspacing=0 cellpadding=1><tr><td bgcolor=' + this.borderColor + '>' + t + '</td></tr></table>'; this.sobj.document.write(t); this.sobj.document.close(); } else { this.sobj.border = '1px solid ' + this.borderColor; this.setOpacity(); if(document.getElementById) document.getElementById('ToolTip').innerHTML = t; else document.all.ToolTip.innerHTML = t; } this.show(); } this.init = function() { if(document.getElementById) { this.obj = document.getElementById('ToolTip'); this.sobj = this.obj.style; } else if(document.all) { this.obj = document.all.ToolTip; this.sobj = this.obj.style; } else if(document.layers) { this.obj = document.ToolTip; this.sobj = this.obj; } } this.show = function() { var ext = (document.layers ? '' : 'px'); var left = mouseX; if(left + this.width + this.cursorDistance > winX) left += this.cursorDistance;// if(left + this.width + this.cursorDistance > winX) left -= this.width + this.cursorDistance; else left += this.cursorDistance; this.sobj.left = left + ext; this.sobj.top = mouseY + this.cursorDistance + ext; if(!this.active) { this.sobj.visibility = 'visible'; this.active = true; } } this.hide = function() { if(this.sobj) this.sobj.visibility = 'hidden'; this.active = false; } this.setOpacity = function() { this.sobj.filter = 'alpha(opacity=' + this.opacity + ')'; this.sobj.mozOpacity = '.1'; if(this.obj.filters) this.obj.filters.alpha.opacity = this.opacity; if(!document.all && this.sobj.setProperty) this.sobj.setProperty('-moz-opacity', this.opacity / 100, ''); } } //---------------------------------------------------------------------------------------------------- // Build layer, get mouse coordinates and window width, create tooltip-object //---------------------------------------------------------------------------------------------------- var tooltip = mouseX = mouseY = winX = 0; if(document.layers) { document.write('<layer id="ToolTip"></layer>'); document.captureEvents(Event.MOUSEMOVE); } else document.write('<div id="ToolTip" style="position:absolute;z-index:99"></div>'); document.onmousemove = getMouseXY; function getMouseXY(e) { if(document.all) { mouseX = event.clientX + document.body.scrollLeft; mouseY = event.clientY + document.body.scrollTop; } else { mouseX = e.pageX; mouseY = e.pageY; } if(mouseX < 0) mouseX = 0; if(mouseY < 0) mouseY = 0; if(document.body && document.body.offsetWidth) winX = document.body.offsetWidth - 25; else if(window.innerWidth) winX = window.innerWidth - 25; else winX = screen.width - 25; if(tooltip && tooltip.active) tooltip.show(); } function toolTip(text, width, opacity) { if(text) { tooltip = new TOOLTIP(); tooltip.text = text; if(width) tooltip.width = width; if(opacity) tooltip.opacity = opacity; tooltip.create(); } else if(tooltip) tooltip.hide(); }
JavaScript
/* This notice must be untouched at all times. wz_tooltip.js v. 3.45 The latest version is available at http://www.walterzorn.com or http://www.devira.com or http://www.walterzorn.de Copyright (c) 2002-2005 Walter Zorn. All rights reserved. Created 1. 12. 2002 by Walter Zorn (Web: http://www.walterzorn.com ) Last modified: 17. 2. 2007 Cross-browser tooltips working even in Opera 5 and 6, as well as in NN 4, Gecko-Browsers, IE4+, Opera 7+ and Konqueror. No onmouseouts required. Appearance of tooltips can be individually configured via commands within the onmouseovers. LICENSE: LGPL This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For more details on the GNU Lesser General Public License, see http://www.gnu.org/copyleft/lesser.html */ //////////////// GLOBAL TOOPTIP CONFIGURATION ///////////////////// var ttAbove = false; // tooltip above mousepointer? Alternative: true var ttBgColor = "#9999FF"; var ttBgImg = ""; // path to background image; var ttBorderColor = "#000066"; var ttBorderWidth = 1; var ttClickClose = false; var ttDelay = 100; // time span until tooltip shows up [milliseconds] var ttFontColor = "#000066"; var ttFontFace = "arial,helvetica,sans-serif"; var ttFontSize = "11px"; var ttFontWeight = "normal"; // alternative: "bold"; var ttLeft = false; // tooltip on the left of the mouse? Alternative: true var ttOffsetX = 12; // horizontal offset of left-top corner from mousepointer var ttOffsetY = 15; // vertical offset " var ttOpacity = 100; // opacity of tooltip in percent (must be integer between 0 and 100) var ttPadding = 3; // spacing between border and content var ttShadowColor = ""; var ttShadowWidth = 0; var ttStatic = false; // tooltip NOT move with the mouse? Alternative: true var ttSticky = false; // do NOT hide tooltip on mouseout? Alternative: true var ttTemp = 0; // time span after which the tooltip disappears; 0 (zero) means "infinite timespan" var ttTextAlign = "left"; var ttTitleColor = "#ffffff"; // color of caption text var ttWidth = 100; //////////////////// END OF TOOLTIP CONFIG //////////////////////// ////////////// TAGS WITH TOOLTIP FUNCTIONALITY //////////////////// // List may be extended or shortened: var tt_tags = new Array("a","area","b","big","caption","center","code","dd","div","dl","dt","em","h1","h2","h3","h4","h5","h6","i","img","input","li","map","ol","p","pre","s", "select", "small","span","strike","strong","sub","sup","table","td","textarea","th","tr","tt","u","var","ul","layer"); ///////////////////////////////////////////////////////////////////// ///////// DON'T CHANGE ANYTHING BELOW THIS LINE ///////////////////// var tt_obj = null, // current tooltip tt_ifrm = null, // iframe to cover windowed controls in IE tt_objW = 0, tt_objH = 0, // width and height of tt_obj tt_objX = 0, tt_objY = 0, tt_offX = 0, tt_offY = 0, xlim = 0, ylim = 0, // right and bottom borders of visible client area tt_sup = false, // true if T_ABOVE cmd tt_sticky = false, // tt_obj sticky? tt_wait = false, tt_act = false, // tooltip visibility flag tt_sub = false, // true while tooltip below mousepointer tt_u = "undefined", tt_mf = null, // stores previous mousemove evthandler // Opera: disable href when hovering <a> tt_tag = null; // stores hovered dom node, href and previous statusbar txt var tt_db = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body? document.body : null, tt_n = navigator.userAgent.toLowerCase(), tt_nv = navigator.appVersion; // Browser flags var tt_op = !!(window.opera && document.getElementById), tt_op6 = tt_op && !document.defaultView, tt_op7 = tt_op && !tt_op6, tt_ie = tt_n.indexOf("msie") != -1 && document.all && tt_db && !tt_op, tt_ie7 = tt_ie && typeof document.body.style.maxHeight != tt_u, tt_ie6 = tt_ie && !tt_ie7 && parseFloat(tt_nv.substring(tt_nv.indexOf("MSIE")+5)) >= 5.5, tt_n4 = (document.layers && typeof document.classes != tt_u), tt_n6 = (!tt_op && document.defaultView && typeof document.defaultView.getComputedStyle != tt_u), tt_w3c = !tt_ie && !tt_n6 && !tt_op && document.getElementById, tt_ce = document.captureEvents && !tt_n6; function tt_Int(t_x) { var t_y; return isNaN(t_y = parseInt(t_x))? 0 : t_y; } function wzReplace(t_x, t_y) { var t_ret = "", t_str = this, t_xI; while((t_xI = t_str.indexOf(t_x)) != -1) { t_ret += t_str.substring(0, t_xI) + t_y; t_str = t_str.substring(t_xI + t_x.length); } return t_ret+t_str; } String.prototype.wzReplace = wzReplace; function tt_N4Tags(tagtyp, t_d, t_y) { t_d = t_d || document; t_y = t_y || new Array(); var t_x = (tagtyp=="a")? t_d.links : t_d.layers; for(var z = t_x.length; z--;) t_y[t_y.length] = t_x[z]; for(z = t_d.layers.length; z--;) t_y = tt_N4Tags(tagtyp, t_d.layers[z].document, t_y); return t_y; } function tt_Htm(tt, t_id, txt) { var t_bgc = (typeof tt.T_BGCOLOR != tt_u)? tt.T_BGCOLOR : ttBgColor, t_bgimg = (typeof tt.T_BGIMG != tt_u)? tt.T_BGIMG : ttBgImg, t_bc = (typeof tt.T_BORDERCOLOR != tt_u)? tt.T_BORDERCOLOR : ttBorderColor, t_bw = (typeof tt.T_BORDERWIDTH != tt_u)? tt.T_BORDERWIDTH : ttBorderWidth, t_ff = (typeof tt.T_FONTFACE != tt_u)? tt.T_FONTFACE : ttFontFace, t_fc = (typeof tt.T_FONTCOLOR != tt_u)? tt.T_FONTCOLOR : ttFontColor, t_fsz = (typeof tt.T_FONTSIZE != tt_u)? tt.T_FONTSIZE : ttFontSize, t_fwght = (typeof tt.T_FONTWEIGHT != tt_u)? tt.T_FONTWEIGHT : ttFontWeight, t_opa = (typeof tt.T_OPACITY != tt_u)? tt.T_OPACITY : ttOpacity, t_padd = (typeof tt.T_PADDING != tt_u)? tt.T_PADDING : ttPadding, t_shc = (typeof tt.T_SHADOWCOLOR != tt_u)? tt.T_SHADOWCOLOR : (ttShadowColor || 0), t_shw = (typeof tt.T_SHADOWWIDTH != tt_u)? tt.T_SHADOWWIDTH : (ttShadowWidth || 0), t_algn = (typeof tt.T_TEXTALIGN != tt_u)? tt.T_TEXTALIGN : ttTextAlign, t_tit = (typeof tt.T_TITLE != tt_u)? tt.T_TITLE : "", t_titc = (typeof tt.T_TITLECOLOR != tt_u)? tt.T_TITLECOLOR : ttTitleColor, t_w = (typeof tt.T_WIDTH != tt_u)? tt.T_WIDTH : ttWidth; if(t_shc || t_shw) { t_shc = t_shc || "#c0c0c0"; t_shw = t_shw || 5; } if(tt_n4 && (t_fsz == "10px" || t_fsz == "11px")) t_fsz = "12px"; var t_optx = (tt_n4? '' : tt_n6? ('-moz-opacity:'+(t_opa/100.0)) : tt_ie? ('filter:Alpha(opacity='+t_opa+')') : ('opacity:'+(t_opa/100.0))) + ';'; var t_y = '<div id="'+t_id+'" style="position:absolute;z-index:1010;'; t_y += 'left:0px;top:0px;width:'+(t_w+t_shw)+'px;visibility:'+(tt_n4? 'hide' : 'hidden')+';'+t_optx+'">' + '<table border="0" cellpadding="0" cellspacing="0"'+(t_bc? (' bgcolor="'+t_bc+'" style="background:'+t_bc+';"') : '')+' width="'+t_w+'">'; if(t_tit) { t_y += '<tr><td style="padding-left:3px;padding-right:3px;" align="'+t_algn+'"><font color="'+t_titc+'" face="'+t_ff+'" ' + 'style="color:'+t_titc+';font-family:'+t_ff+';font-size:'+t_fsz+';"><b>' + (tt_n4? '&nbsp;' : '')+t_tit+'</b></font></td></tr>'; } t_y += '<tr><td><table border="0" cellpadding="'+t_padd+'" cellspacing="'+t_bw+'" width="100%">' + '<tr><td'+(t_bgc? (' bgcolor="'+t_bgc+'"') : '')+(t_bgimg? ' background="'+t_bgimg+'"' : '')+' style="text-align:'+t_algn+';'; if(tt_n6) t_y += 'padding:'+t_padd+'px;'; t_y += '" align="'+t_algn+'"><font color="'+t_fc+'" face="'+t_ff+'"' + ' style="color:'+t_fc+';font-family:'+t_ff+';font-size:'+t_fsz+';font-weight:'+t_fwght+';">'; if(t_fwght == 'bold') t_y += '<b>'; t_y += txt; if(t_fwght == 'bold') t_y += '</b>'; t_y += '</font></td></tr></table></td></tr></table>'; if(t_shw) { var t_spct = Math.round(t_shw*1.3); if(tt_n4) { t_y += '<layer bgcolor="'+t_shc+'" left="'+t_w+'" top="'+t_spct+'" width="'+t_shw+'" height="0"></layer>' + '<layer bgcolor="'+t_shc+'" left="'+t_spct+'" align="bottom" width="'+(t_w-t_spct)+'" height="'+t_shw+'"></layer>'; } else { t_optx = tt_n6? '-moz-opacity:0.85;' : tt_ie? 'filter:Alpha(opacity=85);' : 'opacity:0.85;'; t_y += '<div id="'+t_id+'R" style="position:absolute;background:'+t_shc+';left:'+t_w+'px;top:'+t_spct+'px;width:'+t_shw+'px;height:1px;overflow:hidden;'+t_optx+'"></div>' + '<div style="position:relative;background:'+t_shc+';left:'+t_spct+'px;top:0px;width:'+(t_w-t_spct)+'px;height:'+t_shw+'px;overflow:hidden;'+t_optx+'"></div>'; } } return(t_y+'</div>'); } function tt_EvX(t_e) { var t_y = tt_Int(t_e.pageX || t_e.clientX || 0) + tt_Int(tt_ie? tt_db.scrollLeft : 0) + tt_offX; if(t_y > xlim) t_y = xlim; var t_scr = tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0); if(t_y < t_scr) t_y = t_scr; return t_y; } function tt_EvY(t_e) { var t_y2; var t_y = tt_Int(t_e.pageY || t_e.clientY || 0) + tt_Int(tt_ie? tt_db.scrollTop : 0); if(tt_sup && (t_y2 = t_y - (tt_objH + tt_offY - 15)) >= tt_Int(window.pageYOffset || (tt_db? tt_db.scrollTop : 0) || 0)) t_y -= (tt_objH + tt_offY - 15); else if(t_y > ylim || !tt_sub && t_y > ylim-24) { t_y -= (tt_objH + 5); tt_sub = false; } else { t_y += tt_offY; tt_sub = true; } return t_y; } function tt_ReleasMov() { if(document.onmousemove == tt_Move) { if(!tt_mf && tt_ce) document.releaseEvents(Event.MOUSEMOVE); document.onmousemove = tt_mf; } } function tt_ShowIfrm(t_x) { if(!tt_obj || !tt_ifrm) return; if(t_x) { tt_ifrm.style.width = tt_objW+'px'; tt_ifrm.style.height = tt_objH+'px'; tt_ifrm.style.display = "block"; } else tt_ifrm.style.display = "none"; } function tt_GetDiv(t_id) { return( tt_n4? (document.layers[t_id] || null) : tt_ie? (document.all[t_id] || null) : (document.getElementById(t_id) || null) ); } function tt_GetDivW() { return tt_Int( tt_n4? tt_obj.clip.width : (tt_obj.offsetWidth || tt_obj.style.pixelWidth) ); } function tt_GetDivH() { return tt_Int( tt_n4? tt_obj.clip.height : (tt_obj.offsetHeight || tt_obj.style.pixelHeight) ); } // Compat with DragDrop Lib: Ensure that z-index of tooltip is lifted beyond toplevel dragdrop element function tt_SetDivZ() { var t_i = tt_obj.style || tt_obj; if(t_i) { if(window.dd && dd.z) t_i.zIndex = Math.max(dd.z+1, t_i.zIndex); if(tt_ifrm) tt_ifrm.style.zIndex = t_i.zIndex-1; } } function tt_SetDivPos(t_x, t_y) { var t_i = tt_obj.style || tt_obj; var t_px = (tt_op6 || tt_n4)? '' : 'px'; t_i.left = (tt_objX = t_x) + t_px; t_i.top = (tt_objY = t_y) + t_px; // window... to circumvent the FireFox Alzheimer Bug if(window.tt_ifrm) { tt_ifrm.style.left = t_i.left; tt_ifrm.style.top = t_i.top; } } function tt_ShowDiv(t_x) { tt_ShowIfrm(t_x); if(tt_n4) tt_obj.visibility = t_x? 'show' : 'hide'; else tt_obj.style.visibility = t_x? 'visible' : 'hidden'; tt_act = t_x; } function tt_DeAlt(t_tag) { if(t_tag) { if(t_tag.alt) t_tag.alt = ""; if(t_tag.title) t_tag.title = ""; var t_c = t_tag.children || t_tag.childNodes || null; if(t_c) { for(var t_i = t_c.length; t_i; ) tt_DeAlt(t_c[--t_i]); } } } function tt_OpDeHref(t_e) { var t_tag; if(t_e) { t_tag = t_e.target; while(t_tag) { if(t_tag.hasAttribute("href")) { tt_tag = t_tag tt_tag.t_href = tt_tag.getAttribute("href"); tt_tag.removeAttribute("href"); tt_tag.style.cursor = "hand"; tt_tag.onmousedown = tt_OpReHref; tt_tag.stats = window.status; window.status = tt_tag.t_href; break; } t_tag = t_tag.parentElement; } } } function tt_OpReHref() { if(tt_tag) { tt_tag.setAttribute("href", tt_tag.t_href); window.status = tt_tag.stats; tt_tag = null; } } function tt_Show(t_e, t_id, t_sup, t_clk, t_delay, t_fix, t_left, t_offx, t_offy, t_static, t_sticky, t_temp) { if(tt_obj) tt_Hide(); tt_mf = document.onmousemove || null; if(window.dd && (window.DRAG && tt_mf == DRAG || window.RESIZE && tt_mf == RESIZE)) return; var t_sh, t_h; tt_obj = tt_GetDiv(t_id); if(tt_obj) { t_e = t_e || window.event; tt_sub = !(tt_sup = t_sup); tt_sticky = t_sticky; tt_objW = tt_GetDivW(); tt_objH = tt_GetDivH(); tt_offX = t_left? -(tt_objW+t_offx) : t_offx; tt_offY = t_offy; if(tt_op7) tt_OpDeHref(t_e); if(tt_n4) { if(tt_obj.document.layers.length) { t_sh = tt_obj.document.layers[0]; t_sh.clip.height = tt_objH - Math.round(t_sh.clip.width*1.3); } } else { t_sh = tt_GetDiv(t_id+'R'); if(t_sh) { t_h = tt_objH - tt_Int(t_sh.style.pixelTop || t_sh.style.top || 0); if(typeof t_sh.style.pixelHeight != tt_u) t_sh.style.pixelHeight = t_h; else t_sh.style.height = t_h+'px'; } } xlim = tt_Int((tt_db && tt_db.clientWidth)? tt_db.clientWidth : window.innerWidth) + tt_Int(window.pageXOffset || (tt_db? tt_db.scrollLeft : 0) || 0) - tt_objW - (tt_n4? 21 : 0); ylim = tt_Int(window.innerHeight || tt_db.clientHeight) + tt_Int(window.pageYOffset || (tt_db? tt_db.scrollTop : 0) || 0) - tt_objH - tt_offY; tt_SetDivZ(); if(t_fix) tt_SetDivPos(tt_Int((t_fix = t_fix.split(','))[0]), tt_Int(t_fix[1])); else tt_SetDivPos(tt_EvX(t_e), tt_EvY(t_e)); var t_txt = 'tt_ShowDiv(\'true\');'; if(t_sticky) t_txt += '{'+ 'tt_ReleasMov();'+ (t_clk? ('window.tt_upFunc = document.onmouseup || null;'+ 'if(tt_ce) document.captureEvents(Event.MOUSEUP);'+ 'document.onmouseup = new Function("window.setTimeout(\'tt_Hide();\', 10);");') : '')+ '}'; else if(t_static) t_txt += 'tt_ReleasMov();'; if(t_temp > 0) t_txt += 'window.tt_rtm = window.setTimeout(\'tt_sticky = false; tt_Hide();\','+t_temp+');'; window.tt_rdl = window.setTimeout(t_txt, t_delay); if(!t_fix) { if(tt_ce) document.captureEvents(Event.MOUSEMOVE); document.onmousemove = tt_Move; } } } var tt_area = false; function tt_Move(t_ev) { if(!tt_obj) return; if(tt_n6 || tt_w3c) { if(tt_wait) return; tt_wait = true; setTimeout('tt_wait = false;', 5); } var t_e = t_ev || window.event; tt_SetDivPos(tt_EvX(t_e), tt_EvY(t_e)); if(window.tt_op6) { if(tt_area && t_e.target.tagName != 'AREA') tt_Hide(); else if(t_e.target.tagName == 'AREA') tt_area = true; } } function tt_Hide() { if(window.tt_obj) { if(window.tt_rdl) window.clearTimeout(tt_rdl); if(!tt_sticky || !tt_act) { if(window.tt_rtm) window.clearTimeout(tt_rtm); tt_ShowDiv(false); tt_SetDivPos(-tt_objW, -tt_objH); tt_obj = null; if(typeof window.tt_upFunc != tt_u) document.onmouseup = window.tt_upFunc; } tt_sticky = false; if(tt_op6 && tt_area) tt_area = false; tt_ReleasMov(); if(tt_op7) tt_OpReHref(); } } function tt_Init() { if(!(tt_op || tt_n4 || tt_n6 || tt_ie || tt_w3c)) return; var htm = tt_n4? '<div style="position:absolute;"></div>' : '', tags, t_tj, over, t_b, esc = 'return escape('; for(var i = tt_tags.length; i;) {--i; tags = tt_ie? (document.all.tags(tt_tags[i]) || 1) : document.getElementsByTagName? (document.getElementsByTagName(tt_tags[i]) || 1) : (!tt_n4 && tt_tags[i]=="a")? document.links : 1; if(tt_n4 && (tt_tags[i] == "a" || tt_tags[i] == "layer")) tags = tt_N4Tags(tt_tags[i]); for(var j = tags.length; j;) {--j; if(typeof (t_tj = tags[j]).onmouseover == "function" && t_tj.onmouseover.toString().indexOf(esc) != -1 && !tt_n6 || tt_n6 && (over = t_tj.getAttribute("onmouseover")) && over.indexOf(esc) != -1) { if(over) t_tj.onmouseover = new Function(over); var txt = unescape(t_tj.onmouseover()); htm += tt_Htm( t_tj, "tOoLtIp"+i+""+j, txt.wzReplace("& ","&") ); // window. to circumvent the FF Alzheimer Bug t_tj.onmouseover = new Function('e', 'if(window.tt_Show && tt_Show) tt_Show(e,'+ '"tOoLtIp' +i+''+j+ '",'+ ((typeof t_tj.T_ABOVE != tt_u)? t_tj.T_ABOVE : ttAbove)+','+ ((typeof t_tj.T_CLICKCLOSE != tt_u)? t_tj.T_CLICKCLOSE : ttClickClose)+','+ ((typeof t_tj.T_DELAY != tt_u)? t_tj.T_DELAY : ttDelay)+','+ ((typeof t_tj.T_FIX != tt_u)? '"'+t_tj.T_FIX+'"' : '""')+','+ ((typeof t_tj.T_LEFT != tt_u)? t_tj.T_LEFT : ttLeft)+','+ ((typeof t_tj.T_OFFSETX != tt_u)? t_tj.T_OFFSETX : ttOffsetX)+','+ ((typeof t_tj.T_OFFSETY != tt_u)? t_tj.T_OFFSETY : ttOffsetY)+','+ ((typeof t_tj.T_STATIC != tt_u)? t_tj.T_STATIC : ttStatic)+','+ ((typeof t_tj.T_STICKY != tt_u)? t_tj.T_STICKY : ttSticky)+','+ ((typeof t_tj.T_TEMP != tt_u)? t_tj.T_TEMP : ttTemp)+ ');' ); t_tj.onmouseout = tt_Hide; tt_DeAlt(t_tj); } } } if(tt_ie6) htm += '<iframe id="TTiEiFrM" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"></iframe>'; t_b = document.getElementsByTagName? document.getElementsByTagName("body")[0] : tt_db; if(t_b && t_b.insertAdjacentHTML) t_b.insertAdjacentHTML("AfterBegin", htm); else if(t_b && typeof t_b.innerHTML != tt_u && document.createElement && t_b.appendChild) { var t_el = document.createElement("div"); t_b.appendChild(t_el); t_el.innerHTML = htm; } else document.write(htm); if(document.getElementById) tt_ifrm = document.getElementById("TTiEiFrM"); } tt_Init();
JavaScript
function show(target){target.style.display="";return true;} function showBlock(target){target.style.display="block";return true;} function hide(target){target.style.display="none";return true;} function getNodeClass(obj){var result=false;if(obj.getAttributeNode("class")){result=obj.attributes.getNamedItem("class").value;}return result;} function createCookie(name,value,days){ if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires="; expires="+date.toGMTString();} else expires="";var domainName="";if(DOMAIN_PATH!=""){domainName="domain="+DOMAIN_PATH;} document.cookie=name+"="+value+expires+"; path="+SITE_PATH+"; "+domainName; } function readCookie(name){ var nameEQ=name+"="; var ca=document.cookie.split(';'); for(var i=0;i<ca.length;i++){ var c=ca[i];while(c.charAt(0)==' ')c=c.substring(1,c.length); if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length); } return null; } function expandCollapse(){ for(var i=0;i<expandCollapse.arguments.length;i++){ var element=document.getElementById(expandCollapse.arguments[i]);element.style.display=(element.style.display=="none")?"block":"none"; } } var timerID; function ShowLayer(id){document.getElementById().style.display="block";} function HideTimedLayer(id){clearTimeout(timerID);document.getElementById(id).style.display="none";} function timedLayer(id){setTimeout("HideTimedLayer(\""+id+"\")",5000);} function popup_ask(mess){ return confirm(mess); } function selectedText(input){ var startPos = input.selectionStart; var endPos = input.selectionEnd; var doc = document.selection; if(doc && doc.createRange().text.length != 0){ return doc.createRange().text; }else if (!doc && input.value.substring(startPos,endPos).length != 0){ return input.value.substring(startPos,endPos); } } function insertAtCursor(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } }
JavaScript
/* tip_followscroll.js v. 1.1 The latest version is available at http://www.walterzorn.com or http://www.devira.com or http://www.walterzorn.de Initial author: Walter Zorn Last modified: 21.6.2007 Extension for the tooltip library wz_tooltip.js. Lets a "sticky" tooltip keep its position inside the clientarea if the window is scrolled. */ // Here we define new global configuration variable(s) (as members of the // predefined "config." class). // From each of these config variables, wz_tooltip.js will automatically derive // a command which can be passed to Tip() or TagToTip() in order to customize // tooltips individually. These command names are just the config variable // name(s) translated to uppercase, // e.g. from config. FollowScroll a command FOLLOWSCROLL will automatically be // created. //=================== GLOBAL TOOPTIP CONFIGURATION ======================// config. FollowScroll = false // true or false - set to true if you want this to be the default behaviour //======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW ==============// // Create a new tt_Extension object (make sure that the name of that object, // here fscrl, is unique amongst the extensions available for // wz_tooltips.js): var fscrl = new tt_Extension(); // Implement extension eventhandlers on which our extension should react fscrl.OnShow = function() { if(tt_aV[FOLLOWSCROLL]) { // Permit FOLLOWSCROLL only if the tooltip is sticky if(tt_aV[STICKY]) { var x = tt_x - tt_GetScrollX(), y = tt_y - tt_GetScrollY(); if(tt_ie) { fscrl.MoveOnScrl.offX = x; fscrl.MoveOnScrl.offY = y; fscrl.AddRemEvtFncs(tt_AddEvtFnc); } else { tt_SetTipPos(x, y); tt_aElt[0].style.position = "fixed"; } return true; } tt_aV[FOLLOWSCROLL] = false; } return false; }; fscrl.OnHide = function() { if(tt_aV[FOLLOWSCROLL]) { if(tt_ie) fscrl.AddRemEvtFncs(tt_RemEvtFnc); else tt_aElt[0].style.position = "absolute"; } }; // Helper functions (encapsulate in the class to avoid conflicts with other // extensions) fscrl.MoveOnScrl = function() { tt_SetTipPos(fscrl.MoveOnScrl.offX + tt_GetScrollX(), fscrl.MoveOnScrl.offY + tt_GetScrollY()); }; fscrl.AddRemEvtFncs = function(PAddRem) { PAddRem(window, "resize", fscrl.MoveOnScrl); PAddRem(window, "scroll", fscrl.MoveOnScrl); };
JavaScript
/* tip_centerwindow.js v. 1.2 The latest version is available at http://www.walterzorn.com or http://www.devira.com or http://www.walterzorn.de Initial author: Walter Zorn Last modified: 23.6.2007 Extension for the tooltip library wz_tooltip.js. Centers a sticky tooltip in the window's visible clientarea, optionally even if the window is being scrolled or resized. */ // Here we define new global configuration variable(s) (as members of the // predefined "config." class). // From each of these config variables, wz_tooltip.js will automatically derive // a command which can be passed to Tip() or TagToTip() in order to customize // tooltips individually. These command names are just the config variable // name(s) translated to uppercase, // e.g. from config. CenterWindow a command CENTERWINDOW will automatically be // created. //=================== GLOBAL TOOPTIP CONFIGURATION =========================// config. CenterWindow = false // true or false - set to true if you want this to be the default behaviour config. CenterAlways = false // true or false - recenter if window is resized or scrolled //======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW ==============// // Create a new tt_Extension object (make sure that the name of that object, // here ctrwnd, is unique amongst the extensions available for // wz_tooltips.js): var ctrwnd = new tt_Extension(); // Implement extension eventhandlers on which our extension should react ctrwnd.OnLoadConfig = function() { if(tt_aV[CENTERWINDOW]) { // Permit CENTERWINDOW only if the tooltip is sticky if(tt_aV[STICKY]) { if(tt_aV[CENTERALWAYS]) { // IE doesn't support style.position "fixed" if(tt_ie) tt_AddEvtFnc(window, "scroll", Ctrwnd_DoCenter); else tt_aElt[0].style.position = "fixed"; tt_AddEvtFnc(window, "resize", Ctrwnd_DoCenter); } return true; } tt_aV[CENTERWINDOW] = false; } return false; }; // We react on the first OnMouseMove event to center the tip on that occasion ctrwnd.OnMoveBefore = Ctrwnd_DoCenter; ctrwnd.OnKill = function() { if(tt_aV[CENTERWINDOW] && tt_aV[CENTERALWAYS]) { tt_RemEvtFnc(window, "resize", Ctrwnd_DoCenter); if(tt_ie) tt_RemEvtFnc(window, "scroll", Ctrwnd_DoCenter); else tt_aElt[0].style.position = "absolute"; } return false; }; // Helper function function Ctrwnd_DoCenter() { if(tt_aV[CENTERWINDOW]) { var x, y, dx, dy; // Here we use some functions and variables (tt_w, tt_h) which the // extension API of wz_tooltip.js provides for us if(tt_ie || !tt_aV[CENTERALWAYS]) { dx = tt_GetScrollX(); dy = tt_GetScrollY(); } else { dx = 0; dy = 0; } // Position the tip, offset from the center by OFFSETX and OFFSETY x = (tt_GetClientW() - tt_w) / 2 + dx + tt_aV[OFFSETX]; y = (tt_GetClientH() - tt_h) / 2 + dy + tt_aV[OFFSETY]; tt_SetTipPos(x, y); return true; } return false; }
JavaScript
var uagent = navigator.userAgent.toLowerCase(); var is_safari = ( (uagent.indexOf('safari') != -1) || (navigator.vendor == "Apple Computer, Inc.") ); var is_opera = (uagent.indexOf('opera') != -1); var is_webtv = (uagent.indexOf('webtv') != -1); var is_ie = ( (uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) && (!is_webtv) ); var is_ie4 = ( (is_ie) && (uagent.indexOf("msie 4.") != -1) ); var is_moz = ( (navigator.product == 'Gecko') && (!is_opera) && (!is_webtv) && (!is_safari) ); var is_ns = ( (uagent.indexOf('compatible') == -1) && (uagent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_safari) ); var is_ns4 = ( (is_ns) && (parseInt(navigator.appVersion) == 4) ); var is_kon = (uagent.indexOf('konqueror') != -1); var is_win = ( (uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1) ); var is_mac = ( (uagent.indexOf("mac") != -1) || (navigator.vendor == "Apple Computer, Inc.") ); var ua_vers = parseInt(navigator.appVersion); // IE bug fix var ie_range_cache = ''; var imgres; function myshow(el) { obj = document.getElementById(el); obj.style.visibility='visible'; obj.style.display = ''; } function myhide(el) { obj = document.getElementById(el); obj.style.visibility='hidden'; obj.style.display = 'none'; } function myhide_timed(el){ setTimeout("myhide(\""+el+"\")",1000) } function mytoggleview(el) { obj = document.getElementById(el); if (obj.style.visibility == 'hidden') { obj.style.visibility = 'visible'; obj.style.display = ''; } else { obj.style.visibility = 'hidden'; obj.style.display = 'none'; } } function popup_ask(mess){ return confirm(mess); } function clear_innerHTML(el) { document.getElementById(el).innerHTML = ''; } function addlink(el) { url = prompt('Insert link:', 'http://'); if ( (ua_vers >= 4) && is_ie && is_win ) { sel = document.selection; rng = ie_range_cache ? ie_range_cache : sel.createRange(); rng.colapse; if(rng.text.length < 1){ name = prompt('Enter link name:', ''); if(!name){name = url;} }else{ name = ''; } }else{ if(document.getElementById(el).selectionEnd-document.getElementById(el).selectionStart<1){ name = prompt('Insert link name:', ''); if(!name){name = url;} }else{ name = ''; } } if(url){ wrap_tags('[url='+url+']'+name+'','[/url]',el); } } function addemail(el) { url = prompt('Insert email', ''); if ( (ua_vers >= 4) && is_ie && is_win ) { sel = document.selection; rng = ie_range_cache ? ie_range_cache : sel.createRange(); rng.colapse; if(rng.text.length < 1){ name = prompt('Insert addressee:', ''); if(!name){name = url;} }else{ name = ''; } }else{ if(document.getElementById(el).selectionEnd-document.getElementById(el).selectionStart<1){ name = prompt('Insert addressee:', ''); if(!name){name = url;} }else{ name = ''; } } if(url){ wrap_tags('[url=mailto:'+url+']'+name+'','[/url]',el); } } function addimage(el) { url = prompt('Insert image url:', 'http://'); wrap_tags('[img]'+url,'[/img]',el); } function wrap_tags(opentext, closetext, tofield, issingle) { postfieldobj = document.getElementById(tofield); var has_closed = false; if ( ! issingle ) { issingle = false; } //---------------------------------------- // It's IE! //---------------------------------------- if ( (ua_vers >= 4) && is_ie && is_win ) { if ( postfieldobj.isTextEdit ) { //postfieldobj.focus(); var sel = document.selection; var rng = ie_range_cache ? ie_range_cache : sel.createRange(); rng.colapse; if ( (sel.type == "Text" || sel.type == "None") && rng != null && rng.text ) { if (closetext != "" && rng.text.length > 0) { opentext += rng.text + closetext; } else if ( issingle ) { has_closed = true; } rng.text = opentext; } else { postfieldobj.value += opentext + closetext; has_closed = true; } } else { postfieldobj.value += opentext + closetext; has_closed = true; } ie_range_cache = null; rng.select(); } //---------------------------------------- // It's MOZZY! //---------------------------------------- else if ( postfieldobj.selectionEnd ) { var ss = postfieldobj.selectionStart; var st = postfieldobj.scrollTop; var es = postfieldobj.selectionEnd; if (es <= 0) { es = postfieldobj.textLength; } var start = (postfieldobj.value).substring(0, ss); var middle = (postfieldobj.value).substring(ss, es); var end = (postfieldobj.value).substring(es, postfieldobj.textLength); //----------------------------------- // text range? //----------------------------------- if ( postfieldobj.selectionEnd - postfieldobj.selectionStart > 0 ) { middle = opentext + middle + closetext; } else { middle = ' ' + opentext + middle + closetext + ' '; if ( issingle ) { has_closed = true; } } postfieldobj.value = start + middle + end; var cpos = ss + (middle.length); postfieldobj.selectionStart = cpos; postfieldobj.selectionEnd = cpos; postfieldobj.scrollTop = st; } //---------------------------------------- // It's CRAPPY! //---------------------------------------- else { if ( issingle ) { has_closed = false; } postfieldobj.value += opentext + ' ' + closetext; } postfieldobj.focus(); return has_closed; } function setColor(color,tofield) { var parentCommand = parent.command; if ( parentCommand == "hilitecolor" ) { if ( wrap_tags("[background=" +color+ "]", "[/background]", 'textarea', true ) ) { //toggle_button( "background" ); //pushstack(bbtags, "background"); } } else { if ( wrap_tags("[color=" +color+ "]", "[/color]", tofield, true ) ) { //toggle_button( "color" ); //pushstack(bbtags, "color"); } } document.getElementById('cp').style.visibility = "hidden"; document.getElementById('cp').style.display = "none"; }
JavaScript
// JavaScript Document function transformData(startPoint) { var branchLength = eval("Menu" + startPoint + "[3]"); for (var i=1; i <= branchLength; i++) { currentName = eval("Menu" + startPoint + "_" + i + "[0]"); currentNameId = currentName + "@" + startPoint + "_" + i; currentUrl = eval("Menu" + startPoint + "_" + i + "[1]"); parentName = (startPoint!=1) ? eval("Menu" + startPoint + "[0]") + "@" + startPoint : "TopLevel"; eval("topicsArray[\"" + currentNameId + "\"] = new topicElement(\"" + currentNameId + "\",\"" + currentUrl + "\",\"" + parentName + "\"); topicList[k++] = \"" + currentNameId + "\";"); if (eval('Menu' + startPoint + "_" + i + '[3]') != 0) transformData(startPoint + "_" + i); } } //transformData('1'); function revealTree(currentEntry) { if (currentEntry != document.title) { document.getElementById("aBeautifulCherryTree").insertBefore(document.getElementById(currentEntry+"Link").cloneNode(true), document.getElementById("aBeautifulCherryTree").firstChild); document.getElementById("aBeautifulCherryTree").innerHTML = "&nbsp;&gt;&nbsp;" + document.getElementById("aBeautifulCherryTree").innerHTML; document.getElementById("abbreviatedTree").insertBefore(document.getElementById(currentEntry+"Link").cloneNode(true), document.getElementById("abbreviatedTree").firstChild); document.getElementById("abbreviatedTree").innerHTML = "&nbsp; | &nbsp;" + document.getElementById("abbreviatedTree").innerHTML; } if(topicsArray[currentEntry].parentString != "TopLevel") { toggleCategory(topicsArray[currentEntry].parentString); revealTree(topicsArray[topicsArray[currentEntry].parentString].topic); } } function displaySubArticles(thisCategory) { if (document.getElementById(thisCategory+"MenuGroup")) { document.getElementById("categoryArticles").style.display = "block"; document.getElementById("categoryIdentifier").innerHTML = document.title; for(i=0; i<document.getElementById(thisCategory+"MenuGroup").childNodes.length; i++) { clonedNode = document.getElementById(thisCategory+"MenuGroup").childNodes[i].childNodes[0].cloneNode(true); clonedNode.id += "Copied"; cloneDaddy = document.createElement("li"); cloneDaddy.appendChild(clonedNode); document.getElementById("theSoundOfRunningWater").appendChild(cloneDaddy); } } else { document.getElementById("bufferDiv").appendChild(document.getElementById("categoryAlert")); } //alert(document.getElementById("theSoundOfRunningWater").firstChild.id); } function toggleCategory(thisCategory) { document.getElementById(thisCategory).lastChild.style.display = (document.getElementById(thisCategory).lastChild.style.display == "block") ? "none" : "block"; document.getElementById(thisCategory+"Toggler").style.backgroundImage = (document.getElementById(thisCategory+"Toggler").style.backgroundImage == "url(images/minus.gif)") ? "url(images/plus.gif)" : "url(images/minus.gif)"; //alert(document.getElementById(thisCategory).lastChild.id+" has children: "+document.getElementById(thisCategory).lastChild.firstChild.id); } function createListEntry(thisEntry) { listItemForThisEntry = document.createElement("div"); listItemForThisEntry.id = thisEntry.topic; dotForThisEntry = document.createElement("span"); dotForThisEntry.className = "menuEntryDotStyle"; linkForThisEntry = document.createElement("a"); linkForThisEntry.href = thisEntry.linkString; linkForThisEntry.id = thisEntry.topic+"Link"; pureString = thisEntry.topic.split("@"); textForTheLink = document.createTextNode(pureString[0]); linkForThisEntry.appendChild(textForTheLink); listItemForThisEntry.appendChild(linkForThisEntry); listItemForThisEntry.appendChild(dotForThisEntry); return listItemForThisEntry; } function createGroup(thisCategory) { if (thisCategory != "TopLevel") document.getElementById("bufferDiv").appendChild(document.getElementById(thisCategory).childNodes[1]); groupContainer = document.createElement("div"); groupContainer.id = thisCategory+"MenuGroup"; return groupContainer; } function createToggler(thisCategory) { groupToggler = document.createElement("span"); groupToggler.className = "plusSign"; groupToggler.style.backgroundImage = "url(images/plus.gif)"; groupToggler.id = thisCategory+"Toggler"; groupToggler.onclick = function(){toggleCategory(thisCategory)}; return groupToggler; } function minimizeToggle() { document.getElementById("TopLevel").style.display = (document.getElementById("TopLevel").style.display == "none") ? "block" : "none"; document.getElementById("dragMenuContainer").style.backgroundImage = (document.getElementById("dragMenuContainer").style.backgroundImage == "url(images/openmenu.gif)") ? "url(images/closemenu.gif)" : "url(images/openmenu.gif)"; } function assembleTheList() { for (i=0; i<topicList.length; i++) { parentElement = topicsArray[topicList[i]].parentString; processThisItem = (document.getElementById(topicsArray[topicList[i]].topic)) ? document.getElementById(topicsArray[topicList[i]].topic) : createListEntry(topicsArray[topicList[i]]); if(!document.getElementById(parentElement)) document.getElementById("bufferDiv").appendChild(createListEntry(topicsArray[parentElement])); if(!document.getElementById(parentElement+"MenuGroup")) { if (parentElement != "TopLevel") document.getElementById(parentElement).appendChild(createToggler(parentElement)); document.getElementById(parentElement).appendChild(createGroup(parentElement)); if (parentElement != "TopLevel") document.getElementById(parentElement+"MenuGroup").style.display = "none"; } document.getElementById(parentElement+"MenuGroup").appendChild(processThisItem); } currentNodeRef = (window.pageId) ? pageId+"@"+result : document.title; if (document.title != "The Warcraft Encyclopedia") { revealTree(currentNodeRef); document.getElementById(currentNodeRef+"Link").className = "currentArticleMenuStyle"; document.getElementById(currentNodeRef+"Link").style.color = "#ff6600"; } } function initializationSequence() { document.getElementById("headLine").innerHTML = document.title; document.getElementById("TopLevel").style.display = "none"; document.getElementById("dragMenuContainer").style.backgroundImage = "url(images/openmenu.gif)"; document.getElementById("avatarImageContainer").style.backgroundImage = "url(images/icons/"+topicsArray[topicsArray[document.title].parentString].linkString.split(".xml")[0]+".jpg)"; assembleTheList(); replaceText(); displaySubArticles(document.title); if(!document.getElementsByTagName("p")[0]) { document.getElementById("articleContentContainer").style.visibility = "hidden"; document.getElementById("categoryAlert").style.display = "none"; } }
JavaScript
/* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. * CXS-Portal Usage: md5hash(input,output) * Recommend: input = password input field; output = hidden field */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function core_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for(var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i+10], 17, -42063); b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the HMAC-MD5, of a key and some data */ function core_hmac_md5(key, data) { var bkey = str2binl(key); if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); var ipad = Array(16), opad = Array(16); for(var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); return core_md5(opad.concat(hash), 512 + 128); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ function str2binl(str) { var bin = new Array(); var mask = (1 << chrsz) - 1; for(var i = 0; i < str.length * chrsz; i += chrsz) bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); return bin; } /* * Convert an array of little-endian words to a string */ function binl2str(bin) { var str = ""; var mask = (1 << chrsz) - 1; for(var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); return str; } /* * Convert an array of little-endian words to a hex string. */ function binl2hex(binarray) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var str = ""; for(var i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); } return str; } /* * Convert an array of little-endian words to a base-64 string */ function binl2b64(binarray) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var str = ""; for(var i = 0; i < binarray.length * 4; i += 3) { var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); for(var j = 0; j < 4; j++) { if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); } } return str; } function str_to_ent(str) { var result = ''; var i; for (i = 0; i < str.length; i++) { var c = str.charCodeAt(i); var tmp = ''; if (c > 255) { while (c >= 1) { tmp = "0123456789" . charAt(c % 10) + tmp; c = c / 10; } if (tmp == '') { tmp = "0"; } tmp = "#" + tmp; tmp = "&" + tmp; tmp = tmp + ";"; result += tmp; } else { result += str.charAt(i); } } return result; } function trim(s) { while (s.substring(0, 1) == ' ') { s = s.substring(1, s.length); } while (s.substring(s.length-1, s.length) == ' ') { s = s.substring(0, s.length-1); } return s; } function md5hash(input, output_html, output_utf, skip_empty) { if (navigator.userAgent.indexOf("Mozilla/") == 0 && parseInt(navigator.appVersion) >= 4) { var md5string = hex_md5(str_to_ent(trim(input.value))); output_html.value = md5string; if (output_utf) { md5string = hex_md5(trim(input.value)); output_utf.value = md5string; } if (!skip_empty) { // implemented like this to make sure un-updated templates behave as before input.value = ''; } } return true; }
JavaScript
function hideMenu(menuNum){ document.getElementById("menuContainer"+menuNum).style.display="none"; } function showMenu(menuNum){ document.getElementById("menuContainer"+menuNum).style.display="block"; } function newsCollapse(newsPost) { var obj; obj = document.getElementById(newsPost); if (obj.style.display != "block") obj.style.display = "block"; else obj.style.display = "none"; } function getexpirydate(nodays){ var UTCstring; Today = new Date(); nomilli=Date.parse(Today); Today.setTime(nomilli+nodays*24*60*60*1000); UTCstring = Today.toUTCString(); return UTCstring; } function getcookie(cookiename) { var cookiestring=""+document.cookie; var index1=cookiestring.indexOf(cookiename); if (index1==-1 || cookiename=="") return ""; var index2=cookiestring.indexOf(';',index1); if (index2==-1) index2=cookiestring.length; return unescape(cookiestring.substring(index1+cookiename.length+1,index2)); } function setcookie(name,value){ cookiestring=name+"="+escape(value)+";EXPIRES="+ getexpirydate(365)+";PATH="+SITE_PATH; document.cookie=cookiestring; } function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else expires = ""; document.cookie = name+"="+value+expires+"; path="+SITE_PATH; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function initTheme(e) { var cookie = readCookie("style"); var title = cookie ? cookie : getPreferredStyleSheet(); setActiveStyleSheet(title); } function setCookie (name, value, expires, path, domain, secure) { var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "/") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); document.cookie = curCookie; } function getCookie (name) { var prefix = name + '='; var c = document.cookie; var nullstring = ''; var cookieStartIndex = c.indexOf(prefix); if (cookieStartIndex == -1) return nullstring; var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length); if (cookieEndIndex == -1) cookieEndIndex = c.length; return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex)); } function deleteCookie (name, path, domain) { if (getCookie(name)) document.cookie = name + "=" + ((path) ? "; path=" + path : "/") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } function fixDate (date) { var base = new Date(0); var skew = base.getTime(); if (skew > 0) date.setTime(date.getTime() - skew); } function rememberMe (f) { var now = new Date(); fixDate(now); now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000); setCookie('mtcmtauth', f.author.value, now, '', HOST, ''); setCookie('mtcmtmail', f.email.value, now, '', HOST, ''); setCookie('mtcmthome', f.url.value, now, '', HOST, ''); } function forgetMe (f) { deleteCookie('mtcmtmail', '', HOST); deleteCookie('mtcmthome', '', HOST); deleteCookie('mtcmtauth', '', HOST); f.email.value = ''; f.author.value = ''; f.url.value = ''; } var menuCookie; var tempString; if(!(tempString = getcookie("menuCookie"))){ setcookie('menuCookie', '1 1 0 0 0 1 0 0'); menuCookie = [1, 1, 0, 0, 0, 1, 0, 0]; } else { menuCookie = tempString.split(" "); } var menuNames = ["menunews", "menuaccount", "menugameguide", "menuinteractive", "menumedia", "menuforums", "menucommunity", "menusupport"]; function toggleNewMenu(menuID) { var menuNum = parseInt(menuID)+1; var toggleState = menuCookie[menuID]; var menuName = menuNames[menuID]+ "-inner"; var collapseLink = menuNames[menuID]+ "-collapse"; var menuVisual = menuNames[menuID]+ "-icon"; var menuHeader = menuNames[menuID]+ "-header"; var menuButton = menuNames[menuID]+ "-button"; if (toggleState == 0) { try{showMenu(menuNum);}catch(err){} document.getElementById(menuName).style.visibility = "visible"; document.getElementById(menuName).style.display = "block"; document.getElementById(menuButton).className = "menu-button-on"; document.getElementById(collapseLink).className = "leftmenu-minuslink"; document.getElementById(menuVisual).className = menuNames[menuID]+ "-icon-on"; document.getElementById(menuHeader).className = menuNames[menuID]+ "-header-on"; menuCookie[menuID] = 1; } else { try{hidewMenu(menuNum);}catch(err){} document.getElementById(menuName).style.visibility = "hidden"; document.getElementById(menuName).style.display = "none"; document.getElementById(menuButton).className = "menu-button-off"; document.getElementById(collapseLink).className = "leftmenu-pluslink"; document.getElementById(menuVisual).className = menuNames[menuID]+ "-icon-off"; document.getElementById(menuHeader).className = menuNames[menuID]+ "-header-off"; menuCookie[menuID] = 0; } var theString = menuCookie[0] + " " +menuCookie[1]+ " " +menuCookie[2]+ " " +menuCookie[3]+ " " +menuCookie[4]+ " " +menuCookie[5] + " " +menuCookie[6] + " " +menuCookie[7]; setcookie('menuCookie', theString); } function dummyFunction(){} function toggleEntry(newsID,alt) { var newsEntry = "news"+newsID; var collapseLink = "plus"+newsID; if (document.getElementById(newsEntry).className == 'news-expand') { document.getElementById(newsEntry).className = "news-collapse"+alt; setcookie(newsEntry, "0"); } else { document.getElementById(newsEntry).className = "news-expand"; setcookie(newsEntry, "1"); } } function clearFiller(menuNum) { document.getElementById("menuFiller" + menuNum).style.visibility="hidden"; } bgTimeout = null; function changeNavBgPos() { var n, e; e = n = document.getElementById("nav"); y = 0; x = 0; if (e.offsetParent) { while (e.offsetParent) { y += e.offsetTop; x += e.offsetLeft; e = e.offsetParent; } } else if (e.x && e.y) { y += e.y; x += e.x; } n.style.backgroundPosition = (x*-1) + "px " + (y*-1) + "px"; } function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent) { var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } }
JavaScript
window.onload = function fixActiveX () { if(navigator.appName == "Microsoft Internet Explorer" && navigator.userAgent.indexOf('Opera') == -1) { var changeElements = new Array(3); changeElements[0] = "applet"; changeElements[1] = "embed"; changeElements[2] = "object"; //mooooooo! offScreenBuffer = document.createElement("div"); for (i = 0; i < changeElements.length; i++) { thisTypeElements = document.getElementsByTagName(changeElements[i]); elementsLength = thisTypeElements.length; for (j = 0; j < elementsLength; j++ ) { totalString = ""; eatMe(thisTypeElements[j]); newContainer = document.createElement("div"); oldElement = thisTypeElements[j]; newContainer.innerHTML = totalString; oldElement.parentNode.insertBefore(newContainer,oldElement); offScreenBuffer.appendChild(oldElement); } } clearBuffer = window.setInterval("biteMe()", 500); } } function biteMe() { while(offScreenBuffer.hasChildNodes()) { offScreenBuffer.removeChild(offScreenBuffer.firstChild); } window.clearInterval(clearBuffer); } function eatMe(thisElement) { if(thisElement.childNodes.length>0) { totalString = "<"+thisElement.nodeName; parentAttributesLength = thisElement.attributes.length; for (k=0; k<parentAttributesLength; k++) { if(thisElement.attributes[k].nodeValue != null && thisElement.attributes[k].nodeValue != "") totalString += " "+ thisElement.attributes[k].nodeName +" = "+ thisElement.attributes[k].nodeValue; } totalString += ">"; parentLength = thisElement.childNodes.length; for(k=0; k<parentLength; k++) { eatMe(thisElement.childNodes[k]); } totalString += "</"+thisElement.nodeName+">"; } else processElement(thisElement); } function processElement(thisElement) { subElementString = "<"+thisElement.nodeName; attributesLength = thisElement.attributes.length; for (l=0; l<attributesLength; l++) { if(thisElement.attributes[l].nodeValue != null && thisElement.attributes[l].nodeValue != "") subElementString += " "+ thisElement.attributes[l].nodeName +" = "+ thisElement.attributes[l].nodeValue; } subElementString += "></"+thisElement.nodeName+">"; totalString += subElementString; }
JavaScript
/* ------------------------------------------------ PVII Equal CSS Columns scripts -Version 2 Copyright (c) 2005 Project Seven Development www.projectseven.com Version: 2.1.0 ------------------------------------------------ */ function P7_colH2(){ //v2.1.0 by PVII-www.projectseven.com var i,oh,h=0,tg,el,np,dA=document.p7eqc,an=document.p7eqa;if(dA&&dA.length){ for(i=1;i<dA.length;i+=2){dA[i+1].style.paddingBottom='';}for(i=1;i<dA.length;i+=2){ oh=dA[i].offsetHeight;h=(oh>h)?oh:h;}for(i=1;i<dA.length;i+=2){oh=dA[i].offsetHeight; if(oh<h){np=h-oh;if(!an&&dA[0]==1){P7_eqA2(dA[i+1].id,0,np);}else{ dA[i+1].style.paddingBottom=np+"px";}}}document.p7eqa=1; document.p7eqth=document.body.offsetHeight; document.p7eqtw=document.body.offsetWidth;} } function P7_eqT2(){ //v2.1.0 by PVII-www.projectseven.com if(document.p7eqth!=document.body.offsetHeight||document.p7eqtw!=document.body.offsetWidth){P7_colH2();} } function P7_equalCols2(){ //v2.1.0 by PVII-www.projectseven.com var c,e,el;if(document.getElementById){document.p7eqc=new Array(); document.p7eqc[0]=arguments[0];for(i=1;i<arguments.length;i+=2){el=null; c=document.getElementById(arguments[i]);if(c){e=c.getElementsByTagName(arguments[i+1]); if(e){el=e[e.length-1];if(!el.id){el.id="p7eq"+i;}}}if(c&&el){ document.p7eqc[document.p7eqc.length]=c;document.p7eqc[document.p7eqc.length]=el}} setInterval("P7_eqT2()",10);} } function P7_eqA2(el,p,pt){ //v2.1.0 by PVII-www.projectseven.com var sp=10,inc=20,g=document.getElementById(el);np=(p>=pt)?pt:p; g.style.paddingBottom=np+"px";if(np<pt){np+=inc; setTimeout("P7_eqA2('"+el+"',"+np+","+pt+")",sp);} }
JavaScript
var agt=navigator.userAgent.toLowerCase(); var appVer = navigator.appVersion.toLowerCase(); // *** BROWSER VERSION *** var is_minor = parseFloat(appVer); var is_major = parseInt(is_minor); // Note: On IE, start of appVersion return 3 or 4 // which supposedly is the version of Netscape it is compatible with. // So we look for the real version further on in the string var iePos = appVer.indexOf('msie'); if (iePos !=-1) { is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos))) is_major = parseInt(is_minor); } var is_getElementById = (document.getElementById) ? "true" : "false"; // 001121-abk var is_getElementsByTagName = (document.getElementsByTagName) ? "true" : "false"; // 001127-abk var is_documentElement = (document.documentElement) ? "true" : "false"; // 001121-abk var is_gecko = ((navigator.product)&&(navigator.product.toLowerCase()=="gecko"))?true:false; var is_gver = 0; if (is_gecko) is_gver=navigator.productSub; var is_moz = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1) && (is_gecko) && ((navigator.vendor=="")||(navigator.vendor=="Mozilla"))); if (is_moz) { var is_moz_ver = (navigator.vendorSub)?navigator.vendorSub:0; if(!(is_moz_ver)) { is_moz_ver = agt.indexOf('rv:'); is_moz_ver = agt.substring(is_moz_ver+3); is_paren = is_moz_ver.indexOf(')'); is_moz_ver = is_moz_ver.substring(0,is_paren); } is_minor = is_moz_ver; is_major = parseInt(is_moz_ver); } var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1) && (!(is_moz))); // Netscape6 is mozilla/5 + Netscape6/6.0!!! // Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20001108 Netscape6/6.0 // Changed this to use navigator.vendor/vendorSub - dmr 060502 // var nav6Pos = agt.indexOf('netscape6'); // if (nav6Pos !=-1) { if ((navigator.vendor)&& ((navigator.vendor=="Netscape6")||(navigator.vendor=="Netscape"))&& (is_nav)) { is_major = parseInt(navigator.vendorSub); // here we need is_minor as a valid float for testing. We'll // revert to the actual content before printing the result. is_minor = parseFloat(navigator.vendorSub); } var is_opera = (agt.indexOf("opera") != -1); /* var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1); var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1); var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1); var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1); var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1); // new 020128- abk */ var is_opera7 = (agt.indexOf("opera 7") != -1 || agt.indexOf("opera/7") != -1); // new 021205- dmr /* var is_opera5up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4); var is_opera6up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5); // new020128 var is_opera7up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5 && !is_opera6); // new021205 -- dmr */ var is_nav2 = (is_nav && (is_major == 2)); var is_nav3 = (is_nav && (is_major == 3)); var is_nav4 = (is_nav && (is_major == 4)); var is_nav4up = (is_nav && is_minor >= 4); // changed to is_minor for // consistency - dmr, 011001 var is_navonly = (is_nav && ((agt.indexOf(";nav") != -1) || (agt.indexOf("; nav") != -1)) ); var is_nav6 = (is_nav && is_major==6); // new 010118 mhp var is_nav6up = (is_nav && is_minor >= 6) // new 010118 mhp var is_nav5 = (is_nav && is_major == 5 && !is_nav6); // checked for ns6 var is_nav5up = (is_nav && is_minor >= 5); var is_nav7 = (is_nav && is_major == 7); var is_nav7up = (is_nav && is_minor >= 7); var is_ie = ((iePos!=-1) && (!is_opera)); var is_ie3 = (is_ie && (is_major < 4)); // var is_ie4 = (is_ie && is_major == 4); var is_ie4up = (is_ie && is_minor >= 4); var is_ie5 = (is_ie && is_major == 5); var is_ie5up = (is_ie && is_minor >= 5); var is_ie5_5 = (is_ie && (agt.indexOf("msie 5.5") !=-1)); // 020128 new - abk var is_ie5_5up =(is_ie && is_minor >= 5.5); // 020128 new - abk var is_ie6 = (is_ie && is_major == 6); var is_ie6up = (is_ie && is_minor >= 6); // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser // or if this is the first browser window opened. Thus the // variables is_aol, is_aol3, and is_aol4 aren't 100% reliable. /* var is_aol = (agt.indexOf("aol") != -1); var is_aol3 = (is_aol && is_ie3); var is_aol4 = (is_aol && is_ie4); var is_aol5 = (agt.indexOf("aol 5") != -1); var is_aol6 = (agt.indexOf("aol 6") != -1); var is_aol7 = ((agt.indexOf("aol 7")!=-1) || (agt.indexOf("aol7")!=-1)); var is_aol8 = ((agt.indexOf("aol 8")!=-1) || (agt.indexOf("aol8")!=-1)); var is_webtv = (agt.indexOf("webtv") != -1); */ // new 020128 - abk /* var is_TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1)); var is_AOLTV = is_TVNavigator; */ /* var is_hotjava = (agt.indexOf("hotjava") != -1); var is_hotjava3 = (is_hotjava && (is_major == 3)); var is_hotjava3up = (is_hotjava && (is_major >= 3)); */ // end new // *** JAVASCRIPT VERSION CHECK *** // Useful to workaround Nav3 bug in which Nav3 // loads <SCRIPT LANGUAGE="JavaScript1.2">. // updated 020131 by dragle var is_js; if (is_nav2 || is_ie3) is_js = 1.0; else if (is_nav3) is_js = 1.1; // else if (is_opera5up) is_js = 1.3; // 020214 - dmr else if (is_opera) is_js = 1.1; /* else if ((is_nav4 && (is_minor <= 4.05)) || is_ie4) is_js = 1.2; else if ((is_nav4 && (is_minor > 4.05)) || is_ie5) is_js = 1.3; else if (is_nav5 && !(is_nav6)) is_js = 1.4; else if (is_hotjava3up) is_js = 1.4; // new 020128 - abk else if (is_nav6up) is_js = 1.5; */ // NOTE: In the future, update this code when newer versions of JS // are released. For now, we try to provide some upward compatibility // so that future versions of Nav and IE will show they are at // *least* JS 1.x capable. Always check for JS version compatibility // with > or >=. else if (is_nav && (is_major > 5)) is_js = 1.4; else if (is_ie && (is_major > 5)) is_js = 1.3; else if (is_moz) is_js = 1.5; // what about ie6 and ie6up for js version? abk // HACK: no idea for other browsers; always check for JS version // with > or >= else is_js = 0.0; // HACK FOR IE5 MAC = js vers = 1.4 (if put inside if/else jumps out at 1.3) if ((agt.indexOf("mac")!=-1) && is_ie5up) is_js = 1.4; // 020128 - abk // Done with is_minor testing; revert to real for N6/7 if (is_nav6up) { is_minor = navigator.vendorSub; } // *** PLATFORM *** var is_win = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) ); // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all // Win32, so you can't distinguish between Win95 and WinNT. // var is_win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1)); // is this a 16 bit compiled version? /*var is_win16 = ((agt.indexOf("win16")!=-1) || (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("windows 16-bit")!=-1) ); var is_win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) || (agt.indexOf("windows 16-bit")!=-1));*/ /*var is_winme = ((agt.indexOf("win 9x 4.90")!=-1)); // new 020128 - abk var is_win2k = ((agt.indexOf("windows nt 5.0")!=-1) || (agt.indexOf("windows 2000")!=-1)); // 020214 - dmr var is_winxp = ((agt.indexOf("windows nt 5.1")!=-1) || (agt.indexOf("windows xp")!=-1)); // 020214 - dmr*/ // NOTE: Reliable detection of Win98 may not be possible. It appears that: // - On Nav 4.x and before you'll get plain "Windows" in userAgent. // - On Mercury client, the 32-bit version will return "Win98", but // the 16-bit version running on Win98 will still return "Win95". /* var is_win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1)); var is_winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1)); var is_win32 = (is_win95 || is_winnt || is_win98 || ((is_major >= 4) && (navigator.platform == "Win32")) || (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1)); var is_os2 = ((agt.indexOf("os/2")!=-1) || (navigator.appVersion.indexOf("OS/2")!=-1) || (agt.indexOf("ibm-webexplorer")!=-1)); */ var is_mac = (agt.indexOf("mac")!=-1); if (is_mac) { is_win = !is_mac; } // dmr - 06/20/2002 var is_mac68k = (is_mac && ((agt.indexOf("68k")!=-1) || (agt.indexOf("68000")!=-1))); var is_macppc = (is_mac && ((agt.indexOf("ppc")!=-1) || (agt.indexOf("powerpc")!=-1))); var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false; /* var is_sun = (agt.indexOf("sunos")!=-1); var is_sun4 = (agt.indexOf("sunos 4")!=-1); var is_sun5 = (agt.indexOf("sunos 5")!=-1); var is_suni86= (is_sun && (agt.indexOf("i86")!=-1)); var is_irix = (agt.indexOf("irix") !=-1); // SGI var is_irix5 = (agt.indexOf("irix 5") !=-1); var is_irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1)); var is_hpux = (agt.indexOf("hp-ux")!=-1); var is_hpux9 = (is_hpux && (agt.indexOf("09.")!=-1)); var is_hpux10= (is_hpux && (agt.indexOf("10.")!=-1)); var is_aix = (agt.indexOf("aix") !=-1); // IBM var is_aix1 = (agt.indexOf("aix 1") !=-1); var is_aix2 = (agt.indexOf("aix 2") !=-1); var is_aix3 = (agt.indexOf("aix 3") !=-1); var is_aix4 = (agt.indexOf("aix 4") !=-1); var is_linux = (agt.indexOf("inux")!=-1); var is_sco = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1); var is_unixware = (agt.indexOf("unix_system_v")!=-1); var is_mpras = (agt.indexOf("ncr")!=-1); var is_reliant = (agt.indexOf("reliantunix")!=-1); var is_dec = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) || (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) || (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1)); var is_sinix = (agt.indexOf("sinix")!=-1); var is_freebsd = (agt.indexOf("freebsd")!=-1); var is_bsd = (agt.indexOf("bsd")!=-1); var is_unix = ((agt.indexOf("x11")!=-1) || is_sun || is_irix || is_hpux || is_sco ||is_unixware || is_mpras || is_reliant || is_dec || is_sinix || is_aix || is_linux || is_bsd || is_freebsd); var is_vms = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1)); */// additional checks, abk var is_anchors = (document.anchors) ? "true":"false"; var is_regexp = (window.RegExp) ? "true":"false"; var is_option = (window.Option) ? "true":"false"; var is_all = (document.all) ? "true":"false"; // cookies - 990624 - abk document.cookie = "cookies=true"; var is_cookie = (document.cookie) ? "true" : "false"; var is_images = (document.images) ? "true":"false"; var is_layers = (document.layers) ? "true":"false"; // gecko m7 bug? // new doc obj tests 990624-abk var is_forms = (document.forms) ? "true" : "false"; var is_links = (document.links) ? "true" : "false"; var is_frames = (window.frames) ? "true" : "false"; var is_screen = (window.screen) ? "true" : "false"; // java var is_java = (navigator.javaEnabled()); // Flash checking code based adapted from Doc JavaScript information; // see http://webref.com/js/column84/2.html var is_Flash = false; var is_FlashVersion = 0; if ((is_nav||is_opera||is_moz)|| (is_mac&&is_ie5up)) { var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0; if (plugin) { is_Flash = true; is_FlashVersion = parseInt(plugin.description.substring(plugin.description.indexOf(".")-1)); } } /* if (is_win&&is_ie4up) { document.write( '<scr' + 'ipt language=VBScript>' + '\n' + 'Dim hasPlayer, playerversion' + '\n' + 'hasPlayer = false' + '\n' + 'playerversion = 10' + '\n' + 'Do While playerversion > 0' + '\n' + 'On Error Resume Next' + '\n' + 'hasPlayer = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & playerversion)))' + '\n' + 'If hasPlayer = true Then Exit Do' + '\n' + 'playerversion = playerversion - 1' + '\n' + 'Loop' + '\n' + 'is_FlashVersion = playerversion' + '\n' + 'is_Flash = hasPlayer' + '\n' + '<\/sc' + 'ript>' ); } */
JavaScript
function topicElement(topic, linkString, parentString, synonymsArray) { this.topic = topic; this.linkString = linkString; this.parentString = parentString; this.synonymsArray = synonymsArray; } //topicsArray[""] = new topicElement("","",""); topicList[k++] = ""; topicsArray = new Object(); topicList = new Array(); k = 0; topicsArray["Alleria Windrunner"] = new topicElement("Alleria Windrunner","315.xml","High Elves and Blood Elves",new Array("Alleria")); topicList[k++] = "Alleria Windrunner"; topicsArray["Anasterian Sunstrider"] = new topicElement("Anasterian Sunstrider","319.xml","High Elves and Blood Elves"); topicList[k++] = "Anasterian Sunstrider"; topicsArray["Azeroth"] = new topicElement("Azeroth","327.xml","The Warcraft Universe"); topicList[k++] = "Azeroth"; topicsArray["Azshara"] = new topicElement("Azshara","330.xml","Demigods"); topicList[k++] = "Azshara"; topicsArray["Blood Elves"] = new topicElement("Blood Elves","338.xml","High Elves and Blood Elves",new Array("blood elf")); topicList[k++] = "Blood Elves"; topicsArray["Burning Legion"] = new topicElement("Burning Legion","346.xml","Factions"); topicList[k++] = "Burning Legion"; topicsArray["Cenarion Circle"] = new topicElement("Cenarion Circle","349.xml","Factions"); topicList[k++] = "Cenarion Circle"; topicsArray["Cenarius"] = new topicElement("Cenarius","350.xml","Demigods"); topicList[k++] = "Cenarius"; topicsArray["Darnassian"] = new topicElement("Darnassian","361.xml","Languages"); topicList[k++] = "Darnassian"; topicsArray["Dath'Remar Sunstrider"] = new topicElement("Dath'Remar Sunstrider","363.xml","High Elves and Blood Elves"); topicList[k++] = "Dath'Remar Sunstrider"; topicsArray["Dejahna"] = new topicElement("Dejahna","367.xml","Night Elves"); topicList[k++] = "Dejahna"; topicsArray["Demigods"] = new topicElement("Demigods","369.xml","Immortals",new Array("demigod")); topicList[k++] = "Demigods"; topicsArray["Demons"] = new topicElement("Demons","371.xml","Immortals",new Array("demon")); topicList[k++] = "Demons"; topicsArray["Desdel Stareye"] = new topicElement("Desdel Stareye","785.xml","Night Elves"); topicList[k++] = "Desdel Stareye"; topicsArray["Druid"] = new topicElement("Druid","381.xml","Vocations",new Array("druids","druidism")); topicList[k++] = "Druid"; topicsArray["Elune"] = new topicElement("Elune","392.xml","Gods"); topicList[k++] = "Elune"; topicsArray["Emerald Dream"] = new topicElement("Emerald Dream","394.xml","The Warcraft Universe"); topicList[k++] = "Emerald Dream"; topicsArray["Factions"] = new topicElement("Factions","400.xml","TopLevel"); topicList[k++] = "Factions"; topicsArray["Fandral Staghelm"] = new topicElement("Fandral Staghelm","401.xml","Night Elves"); topicList[k++] = "Fandral Staghelm"; topicsArray["Farstriders"] = new topicElement("Farstriders","402.xml","Factions"); topicList[k++] = "Farstriders"; topicsArray["Gods"] = new topicElement("Gods","417.xml","Immortals",new Array("goddess")); topicList[k++] = "Gods"; topicsArray["High Elves"] = new topicElement("High Elves","429.xml","High Elves and Blood Elves",new Array("high elf")); topicList[k++] = "High Elves"; topicsArray["High Elves and Blood Elves"] = new topicElement("High Elves and Blood Elves","339.xml","Mortal Races"); topicList[k++] = "High Elves and Blood Elves"; topicsArray["Highborne"] = new topicElement("Highborne","430.xml","Factions"); topicList[k++] = "Highborne"; topicsArray["Illidan Stormrage"] = new topicElement("Illidan Stormrage","441.xml","Demons"); topicList[k++] = "Illidan Stormrage"; topicsArray["Immortals"] = new topicElement("Immortals","442.xml","TopLevel",new Array("immortal","immortality")); topicList[k++] = "Immortals"; topicsArray["Jarod Shadowsong"] = new topicElement("Jarod Shadowsong","449.xml","Night Elves",new Array("Jarod")); topicList[k++] = "Jarod Shadowsong"; topicsArray["Kael'thas Sunstrider"] = new topicElement("Kael'thas Sunstrider","451.xml","High Elves and Blood Elves"); topicList[k++] = "Kael'thas Sunstrider"; topicsArray["Kur'talos Ravencrest"] = new topicElement("Kur'talos Ravencrest","463.xml","Night Elves"); topicList[k++] = "Kur'talos Ravencrest"; topicsArray["Languages"] = new topicElement("Languages","577.xml","TopLevel"); topicList[k++] = "Languages"; topicsArray["Latosius"] = new topicElement("Latosius","464.xml","Night Elves"); topicList[k++] = "Latosius"; topicsArray["Maiev Shadowsong"] = new topicElement("Maiev Shadowsong","472.xml","Night Elves",new Array("Maiev")); topicList[k++] = "Maiev Shadowsong"; topicsArray["Malfurion Stormrage"] = new topicElement("Malfurion Stormrage","474.xml","Night Elves",new Array("Malfurion")); topicList[k++] = "Malfurion Stormrage"; topicsArray["Malorne"] = new topicElement("Malorne","475.xml","Demigods"); topicList[k++] = "Malorne"; topicsArray["Moon Guard"] = new topicElement("Moon Guard","481.xml","Factions"); topicList[k++] = "Moon Guard"; topicsArray["Mortal Races"] = new topicElement("Mortal Races","545.xml","TopLevel"); topicList[k++] = "Mortal Races"; topicsArray["Naga"] = new topicElement("Naga","487.xml","Mortal Races"); topicList[k++] = "Naga"; topicsArray["Night Elves"] = new topicElement("Night Elves","508.xml","Mortal Races",new Array("night elf")); topicList[k++] = "Night Elves"; topicsArray["Satyrs"] = new topicElement("Satyrs","540.xml","Demons",new Array("satyr")); topicList[k++] = "Satyrs"; topicsArray["Sentinels"] = new topicElement("Sentinels","546.xml","Factions"); topicList[k++] = "Sentinels"; topicsArray["Sisterhood of Elune"] = new topicElement("Sisterhood of Elune","554.xml","Factions",new Array("sisters of elune")); topicList[k++] = "Sisterhood of Elune"; topicsArray["Thalassian"] = new topicElement("Thalassian","576.xml","Languages"); topicList[k++] = "Thalassian"; topicsArray["The Warcraft Universe"] = new topicElement("The Warcraft Universe","580.xml","TopLevel"); topicList[k++] = "The Warcraft Universe"; topicsArray["Twisting Nether"] = new topicElement("Twisting Nether","594.xml","The Warcraft Universe"); topicList[k++] = "Twisting Nether"; topicsArray["Tyrande Whisperwind"] = new topicElement("Tyrande Whisperwind","598.xml","Night Elves"); topicList[k++] = "Tyrande Whisperwind"; topicsArray["Valstann Staghelm"] = new topicElement("Valstann Staghelm","608.xml","Night Elves"); topicList[k++] = "Valstann Staghelm"; topicsArray["Vashj"] = new topicElement("Vashj","610.xml","Naga"); topicList[k++] = "Vashj"; topicsArray["Vereesa Windrunner"] = new topicElement("Vereesa Windrunner","611.xml","High Elves and Blood Elves",new Array("Vereesa")); topicList[k++] = "Vereesa Windrunner"; topicsArray["Vocations"] = new topicElement("Vocations","612.xml","TopLevel"); topicList[k++] = "Vocations"; topicsArray["Watchers"] = new topicElement("Watchers","624.xml","Factions"); topicList[k++] = "Watchers"; topicsArray["Xavius"] = new topicElement("Xavius","634.xml","Demons"); topicList[k++] = "Xavius"; topicsArray["TopLevel"] = new topicElement("TopLevel","index.xml","TopLevel");
JavaScript
var global_nav_lang, opt; function buildtopnav(){ global_nav_lang = (global_nav_lang) ? global_nav_lang.toLowerCase() : ""; linkarray = new Array(); outstring = ""; link1 = new Object(); link2 = new Object(); link3 = new Object(); switch(global_nav_lang){ case "de_de": link2.text = "Das Arsenal" link3.text = "Foren" break; case "ru_ru": link2.text = "Оружейная" link3.text = "Форумы" break; case "fr_fr": link2.text = "l'Armurerie" link3.text = "Forums" break; default: link2.text = "Armory" link3.text = "Forums" break; } link1.text = site_name; link1.href = site_link; link2.href = armory_link; link3.href = forum_link; // linkarray.push(link1) linkarray.push(link2) linkarray.push(link3) for(i=0; i<linkarray.length; i++) { div = (i<linkarray.length-1) ? "<img src='templates/WotLK/images/topnav/topnav_div.gif'/>":"" outstring += "<a href='"+linkarray[i].href+ "'>"+ linkarray[i].text +"</a>"+div; } topnavguts = ""; topnavguts += "<div class='topnav'><div class='tn_interior'>"; topnavguts += outstring; topnavguts += "</div></div><div class='tn_push'></div>"; if(document.location.href) hrefString = document.location.href; else hrefString = document.location; divclass = (hrefString.indexOf("forums")>=0)?"tn_forums":(hrefString.indexOf("armory")>=0)?"tn_armory":"tn_wow"; targ = document.getElementById("shared_topnav"); if(targ != null) { targ.innerHTML = topnavguts; if(!targ.className || targ.className == ""){targ.className = divclass;} if(targ.className.indexOf("tn_armory")>=0){ if (!is_opera) {document.body.style.backgroundPosition = "50% 26px"; }} if(targ.className.indexOf("tn_forums")>=0){ document.body.style.backgroundPosition = "100% 26px"; } } } buildtopnav();
JavaScript
function hideMenu(menuNum){ document.getElementById("menuContainer"+menuNum).style.display="none"; } function showMenu(menuNum){ document.getElementById("menuContainer"+menuNum).style.display="block"; } function newsCollapse(newsPost) { var obj; obj = document.getElementById(newsPost); if (obj.style.display != "block") obj.style.display = "block"; else obj.style.display = "none"; } function getexpirydate(nodays){ var UTCstring; Today = new Date(); nomilli=Date.parse(Today); Today.setTime(nomilli+nodays*24*60*60*1000); UTCstring = Today.toUTCString(); return UTCstring; } function getcookie(cookiename) { var cookiestring=""+document.cookie; var index1=cookiestring.indexOf(cookiename); if (index1==-1 || cookiename=="") return ""; var index2=cookiestring.indexOf(';',index1); if (index2==-1) index2=cookiestring.length; return unescape(cookiestring.substring(index1+cookiename.length+1,index2)); } function setcookie(name,value){ cookiestring=name+"="+escape(value)+";EXPIRES="+ getexpirydate(365)+";PATH="+SITE_PATH; document.cookie=cookiestring; } function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else expires = ""; document.cookie = name+"="+value+expires+"; path="+SITE_PATH; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function initTheme(e) { var cookie = readCookie("style"); var title = cookie ? cookie : getPreferredStyleSheet(); setActiveStyleSheet(title); } function setCookie (name, value, expires, path, domain, secure) { var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "/") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); document.cookie = curCookie; } function getCookie (name) { var prefix = name + '='; var c = document.cookie; var nullstring = ''; var cookieStartIndex = c.indexOf(prefix); if (cookieStartIndex == -1) return nullstring; var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length); if (cookieEndIndex == -1) cookieEndIndex = c.length; return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex)); } function deleteCookie (name, path, domain) { if (getCookie(name)) document.cookie = name + "=" + ((path) ? "; path=" + path : "/") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } function fixDate (date) { var base = new Date(0); var skew = base.getTime(); if (skew > 0) date.setTime(date.getTime() - skew); } function rememberMe (f) { var now = new Date(); fixDate(now); now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000); setCookie('mtcmtauth', f.author.value, now, '', HOST, ''); setCookie('mtcmtmail', f.email.value, now, '', HOST, ''); setCookie('mtcmthome', f.url.value, now, '', HOST, ''); } function forgetMe (f) { deleteCookie('mtcmtmail', '', HOST); deleteCookie('mtcmthome', '', HOST); deleteCookie('mtcmtauth', '', HOST); f.email.value = ''; f.author.value = ''; f.url.value = ''; } var menuCookie; var tempString; if(!(tempString = getcookie("menuCookie"))){ setcookie('menuCookie', '1 1 0 0 0 1 0 0'); menuCookie = [1, 1, 0, 0, 0, 1, 0, 0]; } else { menuCookie = tempString.split(" "); } var menuNames = ["menunews", "menuaccount", "menugameguide", "menuinteractive", "menumedia", "menuforums", "menucommunity", "menusupport"]; function toggleNewMenu(menuID) { var menuNum = parseInt(menuID)+1; var toggleState = menuCookie[menuID]; var menuName = menuNames[menuID]+ "-inner"; var collapseLink = menuNames[menuID]+ "-collapse"; var menuVisual = menuNames[menuID]+ "-icon"; var menuHeader = menuNames[menuID]+ "-header"; var menuButton = menuNames[menuID]+ "-button"; if (toggleState == 0) { try{showMenu(menuNum);}catch(err){} document.getElementById(menuName).style.visibility = "visible"; document.getElementById(menuName).style.display = "block"; document.getElementById(menuButton).className = "menu-button-on"; document.getElementById(collapseLink).className = "leftmenu-minuslink"; document.getElementById(menuVisual).className = menuNames[menuID]+ "-icon-on"; document.getElementById(menuHeader).className = menuNames[menuID]+ "-header-on"; menuCookie[menuID] = 1; } else { try{hidewMenu(menuNum);}catch(err){} document.getElementById(menuName).style.visibility = "hidden"; document.getElementById(menuName).style.display = "none"; document.getElementById(menuButton).className = "menu-button-off"; document.getElementById(collapseLink).className = "leftmenu-pluslink"; document.getElementById(menuVisual).className = menuNames[menuID]+ "-icon-off"; document.getElementById(menuHeader).className = menuNames[menuID]+ "-header-off"; menuCookie[menuID] = 0; } var theString = menuCookie[0] + " " +menuCookie[1]+ " " +menuCookie[2]+ " " +menuCookie[3]+ " " +menuCookie[4]+ " " +menuCookie[5] + " " +menuCookie[6] + " " +menuCookie[7]; setcookie('menuCookie', theString); } function dummyFunction(){} function toggleEntry(newsID,alt) { var newsEntry = "news"+newsID; var collapseLink = "plus"+newsID; if (document.getElementById(newsEntry).className == 'news-expand') { document.getElementById(newsEntry).className = "news-collapse"+alt; setcookie(newsEntry, "0"); } else { document.getElementById(newsEntry).className = "news-expand"; setcookie(newsEntry, "1"); } } function clearFiller(menuNum) { document.getElementById("menuFiller" + menuNum).style.visibility="hidden"; } bgTimeout = null; function changeNavBgPos() { var n, e; e = n = document.getElementById("nav"); y = 0; x = 0; if (e.offsetParent) { while (e.offsetParent) { y += e.offsetTop; x += e.offsetLeft; e = e.offsetParent; } } else if (e.x && e.y) { y += e.y; x += e.x; } n.style.backgroundPosition = (x*-1) + "px " + (y*-1) + "px"; } function addEvent(obj, evType, fn) { if (obj.addEventListener) { obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent) { var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } }
JavaScript
function $(id) { return document.getElementById(id); } function show(id) { $(id).style.display = "block"; } function hide(id) { $(id).style.display = "none"; } function onStatusBoxFocus(elt) { elt.value = ''; elt.style.color = "#000"; show('status_submit'); } function updateStatus() { var message = $('status_input').value; if (message == "") { return; } $('status_input').disabled = true; $('status_submit').disabled = true; app.updateStatus(message); } function onStatusUpdated(html) { $('status_input').disabled = false; $('status_submit').disabled = false; $('posts').innerHTML = html + $('posts').innerHTML; } function like(post_id) { doLike(post_id, true); } function unlike(post_id) { doLike(post_id, false); } function doLike(post_id, val) { var ids = getLikeLinkIds(post_id, val); $(ids[0]).disabled = true; app.like(post_id, val); } // called when the api request has succeeded function onLike(post_id, val) { var ids = getLikeLinkIds(post_id, val); $(ids[0]).disabled = false; hide(ids[0]); show(ids[1]); } function getLikeLinkIds(post_id, val) { if (val) { var prefix1 = 'like'; var prefix2 = 'unlike'; } else { var prefix1 = 'unlike'; var prefix2 = 'like'; } return [prefix1 + post_id, prefix2 + post_id]; } function comment(post_id) { show("comment_box" + post_id); $("comment_box_input" + post_id).focus(); } function postComment(post_id) { var message = $("comment_box_input" + post_id).value; if (message == "") { return; } $("comment_box" + post_id).disabled = true; app.postComment(post_id, message); } function onComment(post_id, html) { $("comments" + post_id).innerHTML += html; $("comment_box" + post_id).disabled = false; $("comment_box_input" + post_id).value = ""; }
JavaScript
$(document).ready(function() { if($('div.form.login').length) { // in login page $('input#LoginForm_password').focus(); } $('table.preview input[name="checkAll"]').click(function() { $('table.preview .confirm input').attr('checked', this.checked); }); $('table.preview td.confirm input').click(function() { $('table.preview input[name="checkAll"]').attr('checked', !$('table.preview td.confirm input:not(:checked)').length); }); $('table.preview input[name="checkAll"]').attr('checked', !$('table.preview td.confirm input:not(:checked)').length); $('.form .row.sticky input:not(.error), .form .row.sticky select:not(.error), .form .row.sticky textarea:not(.error)').each(function(){ var value; if(this.tagName=='SELECT') value=this.options[this.selectedIndex].text; else if(this.tagName=='TEXTAREA') value=$(this).html(); else value=$(this).val(); if(value=='') value='[empty]'; $(this).before('<div class="value">'+value+'</div>').hide(); }); $('.form.gii .row.sticky .value').live('click', function(){ $(this).hide(); $(this).next().show().get(0).focus(); }); $('.form.gii .row input, .form.gii .row textarea, .form.gii .row select, .with-tooltip').not('.no-tooltip, .no-tooltip *').tooltip({ position: "center right", offset: [-2, 10] }); $('.form.gii .row input').change(function(){ $('.form.gii .feedback').hide(); $('.form.gii input[name="generate"]').hide(); }); $('.form.gii .view-code').click(function(){ var title=$(this).attr('rel'); $.fancybox.showActivity(); $.ajax({ type: 'POST', cache: false, url: $(this).attr('href'), data: $('.form.gii form').serializeArray(), success: function(data){ $.fancybox(data, { 'title': title, 'titlePosition': 'inside', 'titleFormat': function(title, currentArray, currentIndex, currentOpts) { return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.close();">close</a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + '</div>'; }, 'showCloseButton': false, 'autoDimensions': false, 'width': 900, 'height': 'auto', 'onComplete':function(){ $('#fancybox-inner').scrollTop(0); } }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $.fancybox('<div class="error">'+XMLHttpRequest.responseText+'</div>'); } }); return false; }); $('#fancybox-inner .close-code').live('click', function(){ $.fancybox.close(); return false; }); });
JavaScript
/** * jQuery Yii ListView plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yiilistview.js 3296 2011-06-22 17:15:17Z qiang.xue $ */ ;(function($) { /** * yiiListView set function. * @param options map settings for the list view. Availablel options are as follows: * - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response * - ajaxVar: string, the name of the GET variable indicating the ID of the element triggering the AJAX request * - pagerClass: string, the CSS class for the pager container * - sorterClass: string, the CSS class for the sorter container * - updateSelector: string, the selector for choosing which elements can trigger ajax requests * - beforeAjaxUpdate: function, the function to be called before ajax request is sent * - afterAjaxUpdate: function, the function to be called after ajax response is received */ $.fn.yiiListView = function(options) { return this.each(function(){ var settings = $.extend({}, $.fn.yiiListView.defaults, options || {}); var $this = $(this); var id = $this.attr('id'); if(settings.updateSelector == undefined) { settings.updateSelector = '#'+id+' .'+settings.pagerClass.replace(/\s+/g,'.')+' a, #'+id+' .'+settings.sorterClass.replace(/\s+/g,'.')+' a'; } $.fn.yiiListView.settings[id] = settings; if(settings.ajaxUpdate.length > 0) { $(settings.updateSelector).die('click').live('click',function(){ $.fn.yiiListView.update(id, {url: $(this).attr('href')}); return false; }); } }); }; $.fn.yiiListView.defaults = { ajaxUpdate: [], ajaxVar: 'ajax', pagerClass: 'pager', loadingClass: 'loading', sorterClass: 'sorter' // updateSelector: '#id .pager a, '#id .sort a', // beforeAjaxUpdate: function(id) {}, // afterAjaxUpdate: function(id, data) {}, // url: 'ajax request URL' }; $.fn.yiiListView.settings = {}; /** * Returns the key value for the specified row * @param id string the ID of the list view container * @param index integer the zero-based index of the data item * @return string the key value */ $.fn.yiiListView.getKey = function(id, index) { return $('#'+id+' > div.keys > span:eq('+index+')').text(); }; /** * Returns the URL that generates the list view content. * @param id string the ID of the list view container * @return string the URL that generates the list view content. */ $.fn.yiiListView.getUrl = function(id) { var settings = $.fn.yiiListView.settings[id]; return settings.url || $('#'+id+' > div.keys').attr('title'); }; /** * Performs an AJAX-based update of the list view contents. * @param id string the ID of the list view container * @param options map the AJAX request options (see jQuery.ajax API manual). By default, * the URL to be requested is the one that generates the current content of the list view. */ $.fn.yiiListView.update = function(id, options) { var settings = $.fn.yiiListView.settings[id]; $('#'+id).addClass(settings.loadingClass); options = $.extend({ type: 'GET', url: $.fn.yiiListView.getUrl(id), success: function(data,status) { $.each(settings.ajaxUpdate, function(i,v) { var id='#'+v; $(id).replaceWith($(id,'<div>'+data+'</div>')); }); if(settings.afterAjaxUpdate != undefined) settings.afterAjaxUpdate(id, data); $('#'+id).removeClass(settings.loadingClass); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('#'+id).removeClass(settings.loadingClass); alert(XMLHttpRequest.responseText); } }, options || {}); if(options.data!=undefined && options.type=='GET') { options.url = $.param.querystring(options.url, options.data); options.data = {}; } options.url = $.param.querystring(options.url, settings.ajaxVar+'='+id); if(settings.beforeAjaxUpdate != undefined) settings.beforeAjaxUpdate(id); $.ajax(options); }; })(jQuery);
JavaScript
/** * jQuery Yii GridView plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yiigridview.js 3286 2011-06-16 17:34:34Z qiang.xue $ */ ;(function($) { /** * yiiGridView set function. * @param options map settings for the grid view. Availablel options are as follows: * - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response * - ajaxVar: string, the name of the GET variable indicating the ID of the element triggering the AJAX request * - pagerClass: string, the CSS class for the pager container * - tableClass: string, the CSS class for the table * - selectableRows: integer, the number of rows that can be selected * - updateSelector: string, the selector for choosing which elements can trigger ajax requests * - beforeAjaxUpdate: function, the function to be called before ajax request is sent * - afterAjaxUpdate: function, the function to be called after ajax response is received * - ajaxUpdateError: function, the function to be called if an ajax error occurs * - selectionChanged: function, the function to be called after the row selection is changed */ $.fn.yiiGridView = function(options) { return this.each(function(){ var settings = $.extend({}, $.fn.yiiGridView.defaults, options || {}); var $this = $(this); var id = $this.attr('id'); if(settings.updateSelector === undefined) settings.updateSelector = '#'+id+' .'+settings.pagerClass.replace(/\s+/g,'.')+' a, #'+id+' .'+settings.tableClass.replace(/\s+/g,'.')+' thead th a'; $.fn.yiiGridView.settings[id] = settings; if(settings.ajaxUpdate.length > 0) { $(settings.updateSelector).die('click').live('click',function(){ $.fn.yiiGridView.update(id, {url: $(this).attr('href')}); return false; }); } var inputSelector='#'+id+' .'+settings.filterClass+' input, '+'#'+id+' .'+settings.filterClass+' select'; $('body').undelegate(inputSelector, 'change').delegate(inputSelector, 'change', function(){ var data = $(inputSelector).serialize(); if(settings.pageVar!==undefined) data += '&'+settings.pageVar+'=1'; $.fn.yiiGridView.update(id, {data: data}); }); $.fn.yiiGridView.selectCheckedRows(id); if(settings.selectableRows > 0) { $('#'+id+' .'+settings.tableClass+' > tbody > tr').die('click').live('click',function(e){ if('checkbox'!=e.target.type){ if(settings.selectableRows == 1) $(this).siblings().removeClass('selected'); var isRowSelected=$(this).toggleClass('selected').hasClass('selected'); $('input.select-on-check',this).each(function(){ if(settings.selectableRows == 1) $("input[name='"+this.name+"']").attr('checked',false); this.checked=isRowSelected; var sboxallname=this.name.substring(0,this.name.length-2)+'_all'; //.. remove '[]' and add '_all' $("input[name='"+sboxallname+"']").attr('checked', $("input[name='"+this.name+"']").length==$("input[name='"+this.name+"']:checked").length); }); if(settings.selectionChanged !== undefined) settings.selectionChanged(id); } }); } $('#'+id+' .'+settings.tableClass+' > tbody > tr > td > input.select-on-check').die('click').live('click',function(){ if(settings.selectableRows === 0) return false; var $row=$(this).parent().parent(); if(settings.selectableRows == 1){ $row.siblings().removeClass('selected'); $("input:not(#"+this.id+")[name='"+this.name+"']").attr('checked',false); } else $('#'+id+' .'+settings.tableClass+' > thead > tr > th >input.select-on-check-all').attr('checked', $("input.select-on-check").length==$("input.select-on-check:checked").length); $row.toggleClass('selected',this.checked); if(settings.selectionChanged !== undefined) settings.selectionChanged(id); return true; }); if(settings.selectableRows > 1) { $('#'+id+' .'+settings.tableClass+' > thead > tr > th > input.select-on-check-all').die('click').live('click',function(){ var checkedall=this.checked; var name=this.name.substring(0,this.name.length-4)+'[]'; //.. remove '_all' and add '[]' $("input[name='"+name+"']").each(function() { this.checked=checkedall; $(this).parent().parent().toggleClass('selected',checkedall); }); if(settings.selectionChanged !== undefined) settings.selectionChanged(id); }); } }); }; $.fn.yiiGridView.defaults = { ajaxUpdate: [], ajaxVar: 'ajax', pagerClass: 'pager', loadingClass: 'loading', filterClass: 'filters', tableClass: 'items', selectableRows: 1 // updateSelector: '#id .pager a, '#id .grid thead th a', // beforeAjaxUpdate: function(id) {}, // afterAjaxUpdate: function(id, data) {}, // selectionChanged: function(id) {}, // url: 'ajax request URL' }; $.fn.yiiGridView.settings = {}; /** * Returns the key value for the specified row * @param id string the ID of the grid view container * @param row integer the row number (zero-based index) * @return string the key value */ $.fn.yiiGridView.getKey = function(id, row) { return $('#'+id+' > div.keys > span:eq('+row+')').text(); }; /** * Returns the URL that generates the grid view content. * @param id string the ID of the grid view container * @return string the URL that generates the grid view content. */ $.fn.yiiGridView.getUrl = function(id) { var settings = $.fn.yiiGridView.settings[id]; return settings.url || $('#'+id+' > div.keys').attr('title'); }; /** * Returns the jQuery collection of the cells in the specified row. * @param id string the ID of the grid view container * @param row integer the row number (zero-based index) * @return jQuery the jQuery collection of the cells in the specified row. */ $.fn.yiiGridView.getRow = function(id, row) { var settings = $.fn.yiiGridView.settings[id]; return $('#'+id+' .'+settings.tableClass+' > tbody > tr:eq('+row+') > td'); }; /** * Returns the jQuery collection of the cells in the specified column. * @param id string the ID of the grid view container * @param column integer the column number (zero-based index) * @return jQuery the jQuery collection of the cells in the specified column. */ $.fn.yiiGridView.getColumn = function(id, column) { var settings = $.fn.yiiGridView.settings[id]; return $('#'+id+' .'+settings.tableClass+' > tbody > tr > td:nth-child('+(column+1)+')'); }; /** * Performs an AJAX-based update of the grid view contents. * @param id string the ID of the grid view container * @param options map the AJAX request options (see jQuery.ajax API manual). By default, * the URL to be requested is the one that generates the current content of the grid view. */ $.fn.yiiGridView.update = function(id, options) { var settings = $.fn.yiiGridView.settings[id]; $('#'+id).addClass(settings.loadingClass); if(options && options.error !== undefined) { var customError=options.error; delete options.error; } options = $.extend({ type: 'GET', url: $.fn.yiiGridView.getUrl(id), success: function(data,status) { $.each(settings.ajaxUpdate, function(i,v) { var id='#'+v; $(id).replaceWith($(id,'<div>'+data+'</div>')); }); if(settings.afterAjaxUpdate !== undefined) settings.afterAjaxUpdate(id, data); $('#'+id).removeClass(settings.loadingClass); $.fn.yiiGridView.selectCheckedRows(id); }, error: function(XHR, textStatus, errorThrown) { $('#'+id).removeClass(settings.loadingClass); if(XHR.readyState == 0 || XHR.status == 0) return; if(customError!==undefined) { var ret = customError(XHR); if( ret!==undefined && !ret) return; } var err=''; switch(textStatus) { case 'timeout': err='The request timed out!'; break; case 'parsererror': err='Parser error!'; break; case 'error': if(XHR.status && !/^\s*$/.test(XHR.status)) err='Error ' + XHR.status; else err='Error'; if(XHR.responseText && !/^\s*$/.test(XHR.responseText)) err=err + ': ' + XHR.responseText; break; } if(settings.ajaxUpdateError !== undefined) settings.ajaxUpdateError(XHR, textStatus, errorThrown,err); else if(err) alert(err); } }, options || {}); if(options.data!==undefined && options.type=='GET') { options.url = $.param.querystring(options.url, options.data); options.data = {}; } if(settings.ajaxUpdate!==false) { options.url = $.param.querystring(options.url, settings.ajaxVar+'='+id); if(settings.beforeAjaxUpdate !== undefined) settings.beforeAjaxUpdate(id, options); $.ajax(options); } else { // non-ajax mode if(options.type=='GET') { window.location.href=options.url; } else { // POST mode var $form=$('<form action="'+options.url+'" method="post"></form>').appendTo('body'); if(options.data===undefined) options.data={}; if(options.data.returnUrl===undefined) options.data.returnUrl=window.location.href; $.each(options.data, function(name,value) { $form.append($('<input type="hidden" name="t" value="" />').attr('name',name).val(value)); }); $form.submit(); } } }; /** * 1. Selects rows that have checkbox checked (only checkbox that is connected with selecting a row) * 2. Check if "check all" need to be checked/unchecked (all checkboxes) * @param id string the ID of the grid view container */ $.fn.yiiGridView.selectCheckedRows = function(id) { var settings = $.fn.yiiGridView.settings[id]; $('#'+id+' .'+settings.tableClass+' > tbody > tr > td >input.select-on-check:checked').each(function(){ $(this).parent().parent().addClass('selected'); }); $('#'+id+' .'+settings.tableClass+' > thead > tr > th >input[type="checkbox"]').each(function(){ var name=this.name.substring(0,this.name.length-4)+'[]'; //.. remove '_all' and add '[]'' this.checked=$("input[name='"+name+"']").length==$("input[name='"+name+"']:checked").length; }); }; /** * Returns the key values of the currently selected rows. * @param id string the ID of the grid view container * @return array the key values of the currently selected rows. */ $.fn.yiiGridView.getSelection = function(id) { var settings = $.fn.yiiGridView.settings[id]; var keys = $('#'+id+' > div.keys > span'); var selection = []; $('#'+id+' .'+settings.tableClass+' > tbody > tr').each(function(i){ if($(this).hasClass('selected')) selection.push(keys.eq(i).text()); }); return selection; }; /** * Returns the key values of the currently checked rows. * @param id string the ID of the grid view container * @param column_id string the ID of the column * @return array the key values of the currently checked rows. */ $.fn.yiiGridView.getChecked = function(id,column_id) { var settings = $.fn.yiiGridView.settings[id]; var keys = $('#'+id+' > div.keys > span'); if(column_id.substring(column_id.length-2)!='[]') column_id=column_id+'[]'; var checked = []; $('#'+id+' .'+settings.tableClass+' > tbody > tr > td > input[name="'+column_id+'"]').each(function(i){ if(this.checked) checked.push(keys.eq(i).text()); }); return checked; }; })(jQuery);
JavaScript
/** * jQuery Yii plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yii.js 3053 2011-03-12 21:25:33Z qiang.xue $ */ ;(function($) { $.yii = { version : '1.0', submitForm : function (element, url, params) { var f = $(element).parents('form')[0]; if (!f) { f = document.createElement('form'); f.style.display = 'none'; element.parentNode.appendChild(f); f.method = 'POST'; } if (typeof url == 'string' && url != '') { f.action = url; } if (element.target != null) { f.target = element.target; } var inputs = []; $.each(params, function(name, value) { var input = document.createElement("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", name); input.setAttribute("value", value); f.appendChild(input); inputs.push(input); }); // remember who triggers the form submission // this is used by jquery.yiiactiveform.js $(f).data('submitObject', $(element)); $(f).trigger('submit'); $.each(inputs, function() { f.removeChild(this); }); } }; })(jQuery);
JavaScript
/* ### jQuery Star Rating Plugin v3.13 - 2009-03-26 ### * Home: http://www.fyneworks.com/jquery/star-rating/ * Code: http://code.google.com/p/jquery-star-rating-plugin/ * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html ### */ /*# AVOID COLLISIONS #*/ ;if(window.jQuery) (function($){ // IE6 Background Image Fix if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { } // Thanks to http://www.visualjquery.com/rating/rating_redux.html // plugin initialization $.fn.rating = function(options){ if(this.length==0) return this; // quick fail // Handle API methods if(typeof arguments[0]=='string'){ // Perform API methods on individual elements if(this.length>1){ var args = arguments; return this.each(function(){ $.fn.rating.apply($(this), args); }); } // Invoke API method handler $.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []); // Quick exit... return this; } // Initialize options for this call var options = $.extend( {}/* new object */, $.fn.rating.options/* default options */, options || {} /* just-in-time options */ ); // Allow multiple controls with the same name by making each call unique $.fn.rating.calls++; // loop through each matched element this .not('.star-rating-applied') .addClass('star-rating-applied') .each(function(){ // Load control parameters / find context / etc var control, input = $(this); var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,''); var context = $(this.form || document.body); // FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23 var raters = context.data('rating'); if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls }; var rater = raters[eid]; // if rater is available, verify that the control still exists if(rater) control = rater.data('rating'); if(rater && control)//{// save a byte! // add star to control if rater is available and the same control still exists control.count++; //}// save a byte! else{ // create new control if first star or control element was removed/replaced // Initialize options for this raters control = $.extend( {}/* new object */, options || {} /* current call options */, ($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */ { count:0, stars: [], inputs: [] } ); // increment number of rating controls control.serial = raters.count++; // create rating element rater = $('<span class="star-rating-control"/>'); input.before(rater); // Mark element for initialization (once all stars are ready) rater.addClass('rating-to-be-drawn'); // Accept readOnly setting from 'disabled' property if(input.attr('disabled')) control.readOnly = true; // Create 'cancel' button rater.append( control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>') .mouseover(function(){ $(this).rating('drain'); $(this).addClass('star-rating-hover'); //$(this).rating('focus'); }) .mouseout(function(){ $(this).rating('draw'); $(this).removeClass('star-rating-hover'); //$(this).rating('blur'); }) .click(function(){ $(this).rating('select'); }) .data('rating', control) ); } // first element of group // insert rating star var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>'); rater.append(star); // inherit attributes from input element if(this.id) star.attr('id', this.id); if(this.className) star.addClass(this.className); // Half-stars? if(control.half) control.split = 2; // Prepare division control if(typeof control.split=='number' && control.split>0){ var stw = ($.fn.width ? star.width() : 0) || control.starWidth; var spi = (control.count % control.split), spw = Math.floor(stw/control.split); star // restrict star's width and hide overflow (already in CSS) .width(spw) // move the star left by using a negative margin // this is work-around to IE's stupid box model (position:relative doesn't work) .find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' }) } // readOnly? if(control.readOnly)//{ //save a byte! // Mark star as readOnly so user can customize display star.addClass('star-rating-readonly'); //} //save a byte! else//{ //save a byte! // Enable hover css effects star.addClass('star-rating-live') // Attach mouse events .mouseover(function(){ $(this).rating('fill'); $(this).rating('focus'); }) .mouseout(function(){ $(this).rating('draw'); $(this).rating('blur'); }) .click(function(){ $(this).rating('select'); }) ; //}; //save a byte! // set current selection if(this.checked) control.current = star; // hide input element input.hide(); // backward compatibility, form element to plugin input.change(function(){ $(this).rating('select'); }); // attach reference to star to input element and vice-versa star.data('rating.input', input.data('rating.star', star)); // store control information in form (or body when form not available) control.stars[control.stars.length] = star[0]; control.inputs[control.inputs.length] = input[0]; control.rater = raters[eid] = rater; control.context = context; input.data('rating', control); rater.data('rating', control); star.data('rating', control); context.data('rating', raters); }); // each element // Initialize ratings (first draw) $('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn'); return this; // don't break the chain... }; /*--------------------------------------------------------*/ /* ### Core functionality and API ### */ $.extend($.fn.rating, { // Used to append a unique serial number to internal control ID // each time the plugin is invoked so same name controls can co-exist calls: 0, focus: function(){ var control = this.data('rating'); if(!control) return this; if(!control.focus) return this; // quick fail if not required // find data for event var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null ); // focus handler, as requested by focusdigital.co.uk if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]); }, // $.fn.rating.focus blur: function(){ var control = this.data('rating'); if(!control) return this; if(!control.blur) return this; // quick fail if not required // find data for event var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null ); // blur handler, as requested by focusdigital.co.uk if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]); }, // $.fn.rating.blur fill: function(){ // fill to the current mouse position. var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // Reset all stars and highlight them up to this element this.rating('drain'); this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover'); },// $.fn.rating.fill drain: function() { // drain all the stars. var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // Reset all stars control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover'); },// $.fn.rating.drain draw: function(){ // set value and stars to reflect current selection var control = this.data('rating'); if(!control) return this; // Clear all stars this.rating('drain'); // Set control value if(control.current){ control.current.data('rating.input').attr('checked','checked'); control.current.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-on'); } else $(control.inputs).removeAttr('checked'); // Show/hide 'cancel' button control.cancel[control.readOnly || control.required?'hide':'show'](); // Add/remove read-only classes to remove hand pointer this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly'); },// $.fn.rating.draw select: function(value,wantCallBack){ // select a value // ***** MODIFICATION ***** // Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27 // // ***** LIST OF MODIFICATION ***** // ***** added Parameter wantCallBack : false if you don't want a callback. true or undefined if you want postback to be performed at the end of this method' // ***** recursive calls to this method were like : ... .rating('select') it's now like .rating('select',undefined,wantCallBack); (parameters are set.) // ***** line which is calling callback // ***** /LIST OF MODIFICATION ***** var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // clear selection control.current = null; // programmatically (based on user input) if(typeof value!='undefined'){ // select by index (0 based) if(typeof value=='number') return $(control.stars[value]).rating('select',undefined,wantCallBack); // select by literal value (must be passed as a string if(typeof value=='string') //return $.each(control.stars, function(){ if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack); }); } else control.current = this[0].tagName=='INPUT' ? this.data('rating.star') : (this.is('.rater-'+ control.serial) ? this : null); // Update rating control state this.data('rating', control); // Update display this.rating('draw'); // find data for event var input = $( control.current ? control.current.data('rating.input') : null ); // click callback, as requested here: http://plugins.jquery.com/node/1655 // **** MODIFICATION ***** // Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27 // //old line doing the callback : //if(control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event // //new line doing the callback (if i want :) if((wantCallBack ||wantCallBack == undefined) && control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event //to ensure retro-compatibility, wantCallBack must be considered as true by default // **** /MODIFICATION ***** },// $.fn.rating.select readOnly: function(toggle, disable){ // make the control read-only (still submits value) var control = this.data('rating'); if(!control) return this; // setread-only status control.readOnly = toggle || toggle==undefined ? true : false; // enable/disable control value submission if(disable) $(control.inputs).attr("disabled", "disabled"); else $(control.inputs).removeAttr("disabled"); // Update rating control state this.data('rating', control); // Update display this.rating('draw'); },// $.fn.rating.readOnly disable: function(){ // make read-only and never submit value this.rating('readOnly', true, true); },// $.fn.rating.disable enable: function(){ // make read/write and submit value this.rating('readOnly', false, false); }// $.fn.rating.select }); /*--------------------------------------------------------*/ /* ### Default Settings ### eg.: You can override default control like this: $.fn.rating.options.cancel = 'Clear'; */ $.fn.rating.options = { //$.extend($.fn.rating, { options: { cancel: 'Cancel Rating', // advisory title for the 'cancel' link cancelValue: '', // value to submit when user click the 'cancel' link split: 0, // split the star into how many parts? // Width of star image in case the plugin can't work it out. This can happen if // the jQuery.dimensions plugin is not available OR the image is hidden at installation starWidth: 16//, //NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code! //half: false, // just a shortcut to control.split = 2 //required: false, // disables the 'cancel' button so user can only select one of the specified values //readOnly: false, // disable rating plugin interaction/ values cannot be changed //focus: function(){}, // executed when stars are focused //blur: function(){}, // executed when stars are focused //callback: function(){}, // executed when a star is clicked }; //} }); /*--------------------------------------------------------*/ /* ### Default implementation ### The plugin will attach itself to file inputs with the class 'multi' when the page loads */ $(function(){ $('input[type=radio].star').rating(); }); /*# AVOID COLLISIONS #*/ })(jQuery);
JavaScript
/** * Ajax Queue Plugin * * Homepage: http://jquery.com/plugins/project/ajaxqueue * Documentation: http://docs.jquery.com/AjaxQueue */ /** <script> $(function(){ jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); }); </script> <ul style="position: absolute; top: 5px; right: 5px;"></ul> */ /* * Queued Ajax requests. * A new Ajax request won't be started until the previous queued * request has finished. */ /* * Synced Ajax requests. * The Ajax request will happen as soon as you call this method, but * the callbacks (success/error/complete) won't fire until all previous * synced requests have been completed. */ (function($) { var ajax = $.ajax; var pendingRequests = {}; var synced = []; var syncedData = []; $.ajax = function(settings) { // create settings for compatibility with ajaxSetup settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings)); var port = settings.port; switch(settings.mode) { case "abort": if ( pendingRequests[port] ) { pendingRequests[port].abort(); } return pendingRequests[port] = ajax.apply(this, arguments); case "queue": var _old = settings.complete; settings.complete = function(){ if ( _old ) _old.apply( this, arguments ); jQuery([ajax]).dequeue("ajax" + port );; }; jQuery([ ajax ]).queue("ajax" + port, function(){ ajax( settings ); }); return; case "sync": var pos = synced.length; synced[ pos ] = { error: settings.error, success: settings.success, complete: settings.complete, done: false }; syncedData[ pos ] = { error: [], success: [], complete: [] }; settings.error = function(){ syncedData[ pos ].error = arguments; }; settings.success = function(){ syncedData[ pos ].success = arguments; }; settings.complete = function(){ syncedData[ pos ].complete = arguments; synced[ pos ].done = true; if ( pos == 0 || !synced[ pos-1 ] ) for ( var i = pos; i < synced.length && synced[i].done; i++ ) { if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error ); if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success ); if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete ); synced[i] = null; syncedData[i] = null; } }; } return ajax.apply(this, arguments); }; })(jQuery);
JavaScript
/* * jQuery Autocomplete plugin 1.1 * * Modified for Yii Framework: * - Renamed "autocomplete" to "legacyautocomplete". * - Fixed IE8 problems (mario.ffranco). * * Copyright (c) 2009 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $ */ ;(function($) { $.fn.extend({ legacyautocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); // if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; }; // if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem; return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } }); $.Autocompleter = function(input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; // Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // a keypress means the input has focus // avoids issue where input had focus before the autocomplete was applied hasFocus = 1; // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) { case KEY.UP: event.preventDefault(); if ( select.visible() ) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if ( select.visible() ) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if ( select.visible() ) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if ( select.visible() ) { select.pageDown(); } else { onChange(0, true); } break; // matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if( selectCurrent() ) { // stop default to prevent a form submit, Opera needs special handling event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) { for (var i=0; i < data.length; i++) { if( data[i].result.toLowerCase() == q.toLowerCase() ) { result = data[i]; break; } } } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if( !selected ) return false; var v = selected.result; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { var seperator = options.multipleSeparator.length; var cursorAt = $(input).selection().start; var wordAt, progress = 0; $.each(words, function(i, word) { progress += word.length; if (cursorAt <= progress) { wordAt = i; // Following return caused IE8 to set cursor to the start of the line. // return false; } progress += seperator; }); words[wordAt] = v; // TODO this should set the cursor to the right position, but it gets overriden somewhere //$.Autocompleter.Selection(input, progress + seperator, progress + seperator); v = words.join( options.multipleSeparator ); } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; } var currentValue = $input.val(); if ( !skipPrevCheck && currentValue == previousValue ) return; previousValue = currentValue; currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if (!value) return [""]; if (!options.multiple) return [$.trim(value)]; return $.map(value.split(options.multipleSeparator), function(word) { return $.trim(value).length ? $.trim(word) : null; }); } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); if (words.length == 1) return words[0]; var cursorAt = $(input).selection().start; if (cursorAt == value.length) { words = trimWords(value) } else { words = trimWords(value.replace(value.substring(cursorAt), "")); } return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $(input).selection(previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search( function (result){ // if no value found, clear the input box if( !result ) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); } else { $input.val( "" ); $input.trigger("result", null); } } } ); } }; function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){ var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function(key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function(data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function(options) { var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (options.matchContains == "word"){ i = s.toLowerCase().search("\\b" + sub.toLowerCase()); } if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0; // no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1; // track all options for minChars = 0 stMatchSets[""] = []; // loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false ) continue; var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] ) stMatchSets[firstChar] = []; // if the match is a string var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; // push the current match into the set list stMatchSets[firstChar].push(row); // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets[""].push(row); } }; // add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length) return null; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if( !options.url && options.matchContains ){ // track all matches var csub = []; // loop through all the data grids for matches for( var k in data ){ // don't search through the stMatchSets[""] (minChars: 0) cache // this prevents duplicates if( k.length > 0 ){ var c = data[k]; $.each(c, function(i, x) { // if we've got a match, add it to the array if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else // if the exact item exists, use it if (data[q]){ return data[q]; } else if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function(i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null; } }; }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; }); if( options.width > 0 ) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if(options.scroll) { var offset = 0; listItems.slice(0, active).each(function() { offset += this.offsetHeight; }); if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if(offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false ) continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) { moveSelect( -active ); } else { moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect( listItems.size() - 1 - active ); } else { moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if(options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function() { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); if (!scrollbarsVisible) { // IE doesn't recalculate width when scrollbar disappears listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); } } } }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; }; $.fn.selection = function(start, end) { if (start !== undefined) { return this.each(function() { if( this.createTextRange ){ var selRange = this.createTextRange(); if (end === undefined || start == end) { selRange.move("character", start); selRange.select(); } else { selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } } else if( this.setSelectionRange ){ this.setSelectionRange(start, end); } else if( this.selectionStart ){ this.selectionStart = start; this.selectionEnd = end; } }); } var field = this[0]; if ( field.createTextRange ) { var range = document.selection.createRange(), orig = field.value, teststring = "<->", textLength = range.text.length; range.text = teststring; var caretAt = field.value.indexOf(teststring); field.value = orig; this.selection(caretAt, caretAt + textLength); return { start: caretAt, end: caretAt + textLength } } else if( field.selectionStart !== undefined ){ return { start: field.selectionStart, end: field.selectionEnd } } }; })(jQuery);
JavaScript
/*! * jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010 * http://benalman.com/projects/jquery-bbq-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery BBQ: Back Button & Query Library // // *Version: 1.2.1, Last updated: 2/17/2010* // // Project Home - http://benalman.com/projects/jquery-bbq-plugin/ // GitHub - http://github.com/cowboy/jquery-bbq/ // Source - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.js // (Minified) - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.min.js (4.0kb) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // Basic AJAX - http://benalman.com/code/projects/jquery-bbq/examples/fragment-basic/ // Advanced AJAX - http://benalman.com/code/projects/jquery-bbq/examples/fragment-advanced/ // jQuery UI Tabs - http://benalman.com/code/projects/jquery-bbq/examples/fragment-jquery-ui-tabs/ // Deparam - http://benalman.com/code/projects/jquery-bbq/examples/deparam/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, // Chrome 4-5, Opera 9.6-10.1. // Unit Tests - http://benalman.com/code/projects/jquery-bbq/unit/ // // About: Release History // // 1.2.1 - (2/17/2010) Actually fixed the stale window.location Safari bug from // <jQuery hashchange event> in BBQ, which was the main reason for the // previous release! // 1.2 - (2/16/2010) Integrated <jQuery hashchange event> v1.2, which fixes a // Safari bug, the event can now be bound before DOM ready, and IE6/7 // page should no longer scroll when the event is first bound. Also // added the <jQuery.param.fragment.noEscape> method, and reworked the // <hashchange event (BBQ)> internal "add" method to be compatible with // changes made to the jQuery 1.4.2 special events API. // 1.1.1 - (1/22/2010) Integrated <jQuery hashchange event> v1.1, which fixes an // obscure IE8 EmulateIE7 meta tag compatibility mode bug. // 1.1 - (1/9/2010) Broke out the jQuery BBQ event.special <hashchange event> // functionality into a separate plugin for users who want just the // basic event & back button support, without all the extra awesomeness // that BBQ provides. This plugin will be included as part of jQuery BBQ, // but also be available separately. See <jQuery hashchange event> // plugin for more information. Also added the <jQuery.bbq.removeState> // method and added additional <jQuery.deparam> examples. // 1.0.3 - (12/2/2009) Fixed an issue in IE 6 where location.search and // location.hash would report incorrectly if the hash contained the ? // character. Also <jQuery.param.querystring> and <jQuery.param.fragment> // will no longer parse params out of a URL that doesn't contain ? or #, // respectively. // 1.0.2 - (10/10/2009) Fixed an issue in IE 6/7 where the hidden IFRAME caused // a "This page contains both secure and nonsecure items." warning when // used on an https:// page. // 1.0.1 - (10/7/2009) Fixed an issue in IE 8. Since both "IE7" and "IE8 // Compatibility View" modes erroneously report that the browser // supports the native window.onhashchange event, a slightly more // robust test needed to be added. // 1.0 - (10/2/2009) Initial release (function($,window){ '$:nomunge'; // Used by YUI compressor. // Some convenient shortcuts. var undefined, aps = Array.prototype.slice, decode = decodeURIComponent, // Method / object references. jq_param = $.param, jq_param_fragment, jq_deparam, jq_deparam_fragment, jq_bbq = $.bbq = $.bbq || {}, jq_bbq_pushState, jq_bbq_getState, jq_elemUrlAttr, jq_event_special = $.event.special, // Reused strings. str_hashchange = 'hashchange', str_querystring = 'querystring', str_fragment = 'fragment', str_elemUrlAttr = 'elemUrlAttr', str_location = 'location', str_href = 'href', str_src = 'src', // Reused RegExp. re_trim_querystring = /^.*\?|#.*$/g, re_trim_fragment = /^.*\#/, re_no_escape, // Used by jQuery.elemUrlAttr. elemUrlAttr_cache = {}; // A few commonly used bits, broken out to help reduce minified file size. function is_string( arg ) { return typeof arg === 'string'; }; // Why write the same function twice? Let's curry! Mmmm, curry.. function curry( func ) { var args = aps.call( arguments, 1 ); return function() { return func.apply( this, args.concat( aps.call( arguments ) ) ); }; }; // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { return url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Get location.search (or what you'd expect location.search to be) sans any // leading #. Thanks for making this necessary, IE6! function get_querystring( url ) { return url.replace( /(?:^[^?#]*\?([^#]*).*$)?.*/, '$1' ); }; // Section: Param (to string) // // Method: jQuery.param.querystring // // Retrieve the query string from a URL or if no arguments are passed, the // current window.location. // // Usage: // // > jQuery.param.querystring( [ url ] ); // // Arguments: // // url - (String) A URL containing query string params to be parsed. If url // is not passed, the current window.location is used. // // Returns: // // (String) The parsed query string, with any leading "?" removed. // // Method: jQuery.param.querystring (build url) // // Merge a URL, with or without pre-existing query string params, plus any // object, params string or URL containing query string params into a new URL. // // Usage: // // > jQuery.param.querystring( url, params [, merge_mode ] ); // // Arguments: // // url - (String) A valid URL for params to be merged into. This URL may // contain a query string and/or fragment (hash). // params - (String) A params string or URL containing query string params to // be merged into url. // params - (Object) A params object to be merged into url. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any query string // params in url. // * 1: any query string params in url will override params in the params // argument. // * 2: params argument will completely replace any query string in url. // // Returns: // // (String) Either a params string with urlencoded data or a URL with a // urlencoded query string in the format 'a=b&c=d&e=f'. // Method: jQuery.param.fragment // // Retrieve the fragment (hash) from a URL or if no arguments are passed, the // current window.location. // // Usage: // // > jQuery.param.fragment( [ url ] ); // // Arguments: // // url - (String) A URL containing fragment (hash) params to be parsed. If // url is not passed, the current window.location is used. // // Returns: // // (String) The parsed fragment (hash) string, with any leading "#" removed. // Method: jQuery.param.fragment (build url) // // Merge a URL, with or without pre-existing fragment (hash) params, plus any // object, params string or URL containing fragment (hash) params into a new // URL. // // Usage: // // > jQuery.param.fragment( url, params [, merge_mode ] ); // // Arguments: // // url - (String) A valid URL for params to be merged into. This URL may // contain a query string and/or fragment (hash). // params - (String) A params string or URL containing fragment (hash) params // to be merged into url. // params - (Object) A params object to be merged into url. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any fragment (hash) // params in url. // * 1: any fragment (hash) params in url will override params in the // params argument. // * 2: params argument will completely replace any query string in url. // // Returns: // // (String) Either a params string with urlencoded data or a URL with a // urlencoded fragment (hash) in the format 'a=b&c=d&e=f'. function jq_param_sub( is_fragment, get_func, url, params, merge_mode ) { var result, qs, matches, url_params, hash; if ( params !== undefined ) { // Build URL by merging params into url string. // matches[1] = url part that precedes params, not including trailing ?/# // matches[2] = params, not including leading ?/# // matches[3] = if in 'querystring' mode, hash including leading #, otherwise '' matches = url.match( is_fragment ? /^([^#]*)\#?(.*)$/ : /^([^#?]*)\??([^#]*)(#?.*)/ ); // Get the hash if in 'querystring' mode, and it exists. hash = matches[3] || ''; if ( merge_mode === 2 && is_string( params ) ) { // If merge_mode is 2 and params is a string, merge the fragment / query // string into the URL wholesale, without converting it into an object. qs = params.replace( is_fragment ? re_trim_fragment : re_trim_querystring, '' ); } else { // Convert relevant params in url to object. url_params = jq_deparam( matches[2] ); params = is_string( params ) // Convert passed params string into object. ? jq_deparam[ is_fragment ? str_fragment : str_querystring ]( params ) // Passed params object. : params; qs = merge_mode === 2 ? params // passed params replace url params : merge_mode === 1 ? $.extend( {}, params, url_params ) // url params override passed params : $.extend( {}, url_params, params ); // passed params override url params // Convert params object to a string. qs = jq_param( qs ); // Unescape characters specified via $.param.noEscape. Since only hash- // history users have requested this feature, it's only enabled for // fragment-related params strings. if ( is_fragment ) { qs = qs.replace( re_no_escape, decode ); } } // Build URL from the base url, querystring and hash. In 'querystring' // mode, ? is only added if a query string exists. In 'fragment' mode, # // is always added. result = matches[1] + ( is_fragment ? '#' : qs || !matches[1] ? '?' : '' ) + qs + hash; } else { // If URL was passed in, parse params from URL string, otherwise parse // params from window.location. result = get_func( url !== undefined ? url : window[ str_location ][ str_href ] ); } return result; }; jq_param[ str_querystring ] = curry( jq_param_sub, 0, get_querystring ); jq_param[ str_fragment ] = jq_param_fragment = curry( jq_param_sub, 1, get_fragment ); // Method: jQuery.param.fragment.noEscape // // Specify characters that will be left unescaped when fragments are created // or merged using <jQuery.param.fragment>, or when the fragment is modified // using <jQuery.bbq.pushState>. This option only applies to serialized data // object fragments, and not set-as-string fragments. Does not affect the // query string. Defaults to ",/" (comma, forward slash). // // Note that this is considered a purely aesthetic option, and will help to // create URLs that "look pretty" in the address bar or bookmarks, without // affecting functionality in any way. That being said, be careful to not // unescape characters that are used as delimiters or serve a special // purpose, such as the "#?&=+" (octothorpe, question mark, ampersand, // equals, plus) characters. // // Usage: // // > jQuery.param.fragment.noEscape( [ chars ] ); // // Arguments: // // chars - (String) The characters to not escape in the fragment. If // unspecified, defaults to empty string (escape all characters). // // Returns: // // Nothing. jq_param_fragment.noEscape = function( chars ) { chars = chars || ''; var arr = $.map( chars.split(''), encodeURIComponent ); re_no_escape = new RegExp( arr.join('|'), 'g' ); }; // A sensible default. These are the characters people seem to complain about // "uglifying up the URL" the most. jq_param_fragment.noEscape( ',/' ); // Section: Deparam (from string) // // Method: jQuery.deparam // // Deserialize a params string into an object, optionally coercing numbers, // booleans, null and undefined values; this method is the counterpart to the // internal jQuery.param method. // // Usage: // // > jQuery.deparam( params [, coerce ] ); // // Arguments: // // params - (String) A params string to be parsed. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false if omitted. // // Returns: // // (Object) An object representing the deserialized params string. $.deparam = jq_deparam = function( params, coerce ) { var obj = {}, coerce_types = { 'true': !0, 'false': !1, 'null': null }; // Iterate over all name=value pairs. $.each( params.replace( /\+/g, ' ' ).split( '&' ), function(j,v){ var param = v.split( '=' ), key = decode( param[0] ), val, cur = obj, i = 0, // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it // into its component parts. keys = key.split( '][' ), keys_last = keys.length - 1; // If the first keys part contains [ and the last ends with ], then [] // are correctly balanced. if ( /\[/.test( keys[0] ) && /\]$/.test( keys[ keys_last ] ) ) { // Remove the trailing ] from the last keys part. keys[ keys_last ] = keys[ keys_last ].replace( /\]$/, '' ); // Split first keys part into two parts on the [ and add them back onto // the beginning of the keys array. keys = keys.shift().split('[').concat( keys ); keys_last = keys.length - 1; } else { // Basic 'foo' style key. keys_last = 0; } // Are we dealing with a name=value pair, or just a name? if ( param.length === 2 ) { val = decode( param[1] ); // Coerce values. if ( coerce ) { val = val && !isNaN(val) ? +val // number : val === 'undefined' ? undefined // undefined : coerce_types[val] !== undefined ? coerce_types[val] // true, false, null : val; // string } if ( keys_last ) { // Complex key, build deep object structure based on a few rules: // * The 'cur' pointer starts at the object top-level. // * [] = array push (n is set to array length), [n] = array if n is // numeric, otherwise object. // * If at the last keys part, set the value. // * For each keys part, if the current level is undefined create an // object or array based on the type of the next keys part. // * Move the 'cur' pointer to the next level. // * Rinse & repeat. for ( ; i <= keys_last; i++ ) { key = keys[i] === '' ? cur.length : keys[i]; cur = cur[key] = i < keys_last ? cur[key] || ( keys[i+1] && isNaN( keys[i+1] ) ? {} : [] ) : val; } } else { // Simple key, even simpler rules, since only scalars and shallow // arrays are allowed. if ( $.isArray( obj[key] ) ) { // val is already an array, so push on the next value. obj[key].push( val ); } else if ( obj[key] !== undefined ) { // val isn't an array, but since a second value has been specified, // convert val into an array. obj[key] = [ obj[key], val ]; } else { // val is a scalar. obj[key] = val; } } } else if ( key ) { // No value was defined, so set something meaningful. obj[key] = coerce ? undefined : ''; } }); return obj; }; // Method: jQuery.deparam.querystring // // Parse the query string from a URL or the current window.location, // deserializing it into an object, optionally coercing numbers, booleans, // null and undefined values. // // Usage: // // > jQuery.deparam.querystring( [ url ] [, coerce ] ); // // Arguments: // // url - (String) An optional params string or URL containing query string // params to be parsed. If url is omitted, the current window.location // is used. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false if omitted. // // Returns: // // (Object) An object representing the deserialized params string. // Method: jQuery.deparam.fragment // // Parse the fragment (hash) from a URL or the current window.location, // deserializing it into an object, optionally coercing numbers, booleans, // null and undefined values. // // Usage: // // > jQuery.deparam.fragment( [ url ] [, coerce ] ); // // Arguments: // // url - (String) An optional params string or URL containing fragment (hash) // params to be parsed. If url is omitted, the current window.location // is used. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false if omitted. // // Returns: // // (Object) An object representing the deserialized params string. function jq_deparam_sub( is_fragment, url_or_params, coerce ) { if ( url_or_params === undefined || typeof url_or_params === 'boolean' ) { // url_or_params not specified. coerce = url_or_params; url_or_params = jq_param[ is_fragment ? str_fragment : str_querystring ](); } else { url_or_params = is_string( url_or_params ) ? url_or_params.replace( is_fragment ? re_trim_fragment : re_trim_querystring, '' ) : url_or_params; } return jq_deparam( url_or_params, coerce ); }; jq_deparam[ str_querystring ] = curry( jq_deparam_sub, 0 ); jq_deparam[ str_fragment ] = jq_deparam_fragment = curry( jq_deparam_sub, 1 ); // Section: Element manipulation // // Method: jQuery.elemUrlAttr // // Get the internal "Default URL attribute per tag" list, or augment the list // with additional tag-attribute pairs, in case the defaults are insufficient. // // In the <jQuery.fn.querystring> and <jQuery.fn.fragment> methods, this list // is used to determine which attribute contains the URL to be modified, if // an "attr" param is not specified. // // Default Tag-Attribute List: // // a - href // base - href // iframe - src // img - src // input - src // form - action // link - href // script - src // // Usage: // // > jQuery.elemUrlAttr( [ tag_attr ] ); // // Arguments: // // tag_attr - (Object) An object containing a list of tag names and their // associated default attribute names in the format { tag: 'attr', ... } to // be merged into the internal tag-attribute list. // // Returns: // // (Object) An object containing all stored tag-attribute values. // Only define function and set defaults if function doesn't already exist, as // the urlInternal plugin will provide this method as well. $[ str_elemUrlAttr ] || ($[ str_elemUrlAttr ] = function( obj ) { return $.extend( elemUrlAttr_cache, obj ); })({ a: str_href, base: str_href, iframe: str_src, img: str_src, input: str_src, form: 'action', link: str_href, script: str_src }); jq_elemUrlAttr = $[ str_elemUrlAttr ]; // Method: jQuery.fn.querystring // // Update URL attribute in one or more elements, merging the current URL (with // or without pre-existing query string params) plus any params object or // string into a new URL, which is then set into that attribute. Like // <jQuery.param.querystring (build url)>, but for all elements in a jQuery // collection. // // Usage: // // > jQuery('selector').querystring( [ attr, ] params [, merge_mode ] ); // // Arguments: // // attr - (String) Optional name of an attribute that will contain a URL to // merge params or url into. See <jQuery.elemUrlAttr> for a list of default // attributes. // params - (Object) A params object to be merged into the URL attribute. // params - (String) A URL containing query string params, or params string // to be merged into the URL attribute. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any params in attr URL. // * 1: any params in attr URL will override params in the params argument. // * 2: params argument will completely replace any query string in attr // URL. // // Returns: // // (jQuery) The initial jQuery collection of elements, but with modified URL // attribute values. // Method: jQuery.fn.fragment // // Update URL attribute in one or more elements, merging the current URL (with // or without pre-existing fragment/hash params) plus any params object or // string into a new URL, which is then set into that attribute. Like // <jQuery.param.fragment (build url)>, but for all elements in a jQuery // collection. // // Usage: // // > jQuery('selector').fragment( [ attr, ] params [, merge_mode ] ); // // Arguments: // // attr - (String) Optional name of an attribute that will contain a URL to // merge params into. See <jQuery.elemUrlAttr> for a list of default // attributes. // params - (Object) A params object to be merged into the URL attribute. // params - (String) A URL containing fragment (hash) params, or params // string to be merged into the URL attribute. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any params in attr URL. // * 1: any params in attr URL will override params in the params argument. // * 2: params argument will completely replace any fragment (hash) in attr // URL. // // Returns: // // (jQuery) The initial jQuery collection of elements, but with modified URL // attribute values. function jq_fn_sub( mode, force_attr, params, merge_mode ) { if ( !is_string( params ) && typeof params !== 'object' ) { // force_attr not specified. merge_mode = params; params = force_attr; force_attr = undefined; } return this.each(function(){ var that = $(this), // Get attribute specified, or default specified via $.elemUrlAttr. attr = force_attr || jq_elemUrlAttr()[ ( this.nodeName || '' ).toLowerCase() ] || '', // Get URL value. url = attr && that.attr( attr ) || ''; // Update attribute with new URL. that.attr( attr, jq_param[ mode ]( url, params, merge_mode ) ); }); }; $.fn[ str_querystring ] = curry( jq_fn_sub, str_querystring ); $.fn[ str_fragment ] = curry( jq_fn_sub, str_fragment ); // Section: History, hashchange event // // Method: jQuery.bbq.pushState // // Adds a 'state' into the browser history at the current position, setting // location.hash and triggering any bound <hashchange event> callbacks // (provided the new state is different than the previous state). // // If no arguments are passed, an empty state is created, which is just a // shortcut for jQuery.bbq.pushState( {}, 2 ). // // Usage: // // > jQuery.bbq.pushState( [ params [, merge_mode ] ] ); // // Arguments: // // params - (String) A serialized params string or a hash string beginning // with # to merge into location.hash. // params - (Object) A params object to merge into location.hash. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified (unless a hash string beginning with # is specified, in which // case merge behavior defaults to 2), and is as-follows: // // * 0: params in the params argument will override any params in the // current state. // * 1: any params in the current state will override params in the params // argument. // * 2: params argument will completely replace current state. // // Returns: // // Nothing. // // Additional Notes: // // * Setting an empty state may cause the browser to scroll. // * Unlike the fragment and querystring methods, if a hash string beginning // with # is specified as the params agrument, merge_mode defaults to 2. jq_bbq.pushState = jq_bbq_pushState = function( params, merge_mode ) { if ( is_string( params ) && /^#/.test( params ) && merge_mode === undefined ) { // Params string begins with # and merge_mode not specified, so completely // overwrite window.location.hash. merge_mode = 2; } var has_args = params !== undefined, // Merge params into window.location using $.param.fragment. url = jq_param_fragment( window[ str_location ][ str_href ], has_args ? params : {}, has_args ? merge_mode : 2 ); // Set new window.location.href. If hash is empty, use just # to prevent // browser from reloading the page. Note that Safari 3 & Chrome barf on // location.hash = '#'. window[ str_location ][ str_href ] = url + ( /#/.test( url ) ? '' : '#' ); }; // Method: jQuery.bbq.getState // // Retrieves the current 'state' from the browser history, parsing // location.hash for a specific key or returning an object containing the // entire state, optionally coercing numbers, booleans, null and undefined // values. // // Usage: // // > jQuery.bbq.getState( [ key ] [, coerce ] ); // // Arguments: // // key - (String) An optional state key for which to return a value. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false. // // Returns: // // (Anything) If key is passed, returns the value corresponding with that key // in the location.hash 'state', or undefined. If not, an object // representing the entire 'state' is returned. jq_bbq.getState = jq_bbq_getState = function( key, coerce ) { return key === undefined || typeof key === 'boolean' ? jq_deparam_fragment( key ) // 'key' really means 'coerce' here : jq_deparam_fragment( coerce )[ key ]; }; // Method: jQuery.bbq.removeState // // Remove one or more keys from the current browser history 'state', creating // a new state, setting location.hash and triggering any bound // <hashchange event> callbacks (provided the new state is different than // the previous state). // // If no arguments are passed, an empty state is created, which is just a // shortcut for jQuery.bbq.pushState( {}, 2 ). // // Usage: // // > jQuery.bbq.removeState( [ key [, key ... ] ] ); // // Arguments: // // key - (String) One or more key values to remove from the current state, // passed as individual arguments. // key - (Array) A single array argument that contains a list of key values // to remove from the current state. // // Returns: // // Nothing. // // Additional Notes: // // * Setting an empty state may cause the browser to scroll. jq_bbq.removeState = function( arr ) { var state = {}; // If one or more arguments is passed.. if ( arr !== undefined ) { // Get the current state. state = jq_bbq_getState(); // For each passed key, delete the corresponding property from the current // state. $.each( $.isArray( arr ) ? arr : arguments, function(i,v){ delete state[ v ]; }); } // Set the state, completely overriding any existing state. jq_bbq_pushState( state, 2 ); }; // Event: hashchange event (BBQ) // // Usage in jQuery 1.4 and newer: // // In jQuery 1.4 and newer, the event object passed into any hashchange event // callback is augmented with a copy of the location.hash fragment at the time // the event was triggered as its event.fragment property. In addition, the // event.getState method operates on this property (instead of location.hash) // which allows this fragment-as-a-state to be referenced later, even after // window.location may have changed. // // Note that event.fragment and event.getState are not defined according to // W3C (or any other) specification, but will still be available whether or // not the hashchange event exists natively in the browser, because of the // utility they provide. // // The event.fragment property contains the output of <jQuery.param.fragment> // and the event.getState method is equivalent to the <jQuery.bbq.getState> // method. // // > $(window).bind( 'hashchange', function( event ) { // > var hash_str = event.fragment, // > param_obj = event.getState(), // > param_val = event.getState( 'param_name' ), // > param_val_coerced = event.getState( 'param_name', true ); // > ... // > }); // // Usage in jQuery 1.3.2: // // In jQuery 1.3.2, the event object cannot to be augmented as in jQuery 1.4+, // so the fragment state isn't bound to the event object and must instead be // parsed using the <jQuery.param.fragment> and <jQuery.bbq.getState> methods. // // > $(window).bind( 'hashchange', function( event ) { // > var hash_str = $.param.fragment(), // > param_obj = $.bbq.getState(), // > param_val = $.bbq.getState( 'param_name' ), // > param_val_coerced = $.bbq.getState( 'param_name', true ); // > ... // > }); // // Additional Notes: // // * Due to changes in the special events API, jQuery BBQ v1.2 or newer is // required to enable the augmented event object in jQuery 1.4.2 and newer. // * See <jQuery hashchange event> for more detailed information. jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], { // Augmenting the event object with the .fragment property and .getState // method requires jQuery 1.4 or newer. Note: with 1.3.2, everything will // work, but the event won't be augmented) add: function( handleObj ) { var old_handler; function new_handler(e) { // e.fragment is set to the value of location.hash (with any leading # // removed) at the time the event is triggered. var hash = e[ str_fragment ] = jq_param_fragment(); // e.getState() works just like $.bbq.getState(), but uses the // e.fragment property stored on the event object. e.getState = function( key, coerce ) { return key === undefined || typeof key === 'boolean' ? jq_deparam( hash, key ) // 'key' really means 'coerce' here : jq_deparam( hash, coerce )[ key ]; }; old_handler.apply( this, arguments ); }; // This may seem a little complicated, but it normalizes the special event // .add method between jQuery 1.4/1.4.1 and 1.4.2+ if ( $.isFunction( handleObj ) ) { // 1.4, 1.4.1 old_handler = handleObj; return new_handler; } else { // 1.4.2+ old_handler = handleObj.handler; handleObj.handler = new_handler; } } }); })(jQuery,this); /*! * jQuery hashchange event - v1.2 - 2/11/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.2, Last updated: 2/11/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (1.1kb) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // This working example, complete with fully commented code, illustrate one way // in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, Chrome, Opera 9.6-10.1. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and robust, // there are a few unfortunate browser bugs surrounding expected hashchange // event-based behaviors, independent of any JavaScript window.onhashchange // abstraction. See the following examples for more information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // About: Release History // // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Method / object references. var fake_onhashchange, jq_event_special = $.event.special, // Reused strings. str_location = 'location', str_hashchange = 'hashchange', str_href = 'href', // IE6/7 specifically need some special love when it comes to back-button // support, so let's do a little browser sniffing.. browser = $.browser, mode = document.documentMode, is_old_ie = browser.msie && ( mode === undefined || mode < 8 ), // Does the browser support window.onhashchange? Test for IE version, since // IE8 incorrectly reports this when in "IE7" or "IE8 Compatibility View"! supports_onhashchange = 'on' + str_hashchange in window && !is_old_ie; // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || window[ str_location ][ str_href ]; return url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Property: jQuery.hashchangeDelay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 100. $[ str_hashchange + 'Delay' ] = 100; // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // window.onhashchange event is used (IE8, FF3.6), otherwise a polling loop is // initialized, running every <jQuery.hashchangeDelay> milliseconds to see if // the hash has changed. In IE 6 and 7, a hidden Iframe is created to allow // the back button and hash-based history to work. // // Usage: // // > $(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one callback // is actually bound to 'hashchange'. // * If you need the bound callback(s) to execute immediately, in cases where // the page 'state' exists on page load (via bookmark or page refresh, for // example) use $(window).trigger( 'hashchange' ); // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a $(document).ready() callback. jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, iframe, set_history, get_history; // Initialize. In IE 6/7, creates a hidden Iframe for history handling. function init(){ // Most browsers don't need special methods here.. set_history = get_history = function(val){ return val; }; // But IE6/7 do! if ( is_old_ie ) { // Create hidden Iframe after the end of the body to prevent initial // page load from scrolling unnecessarily. iframe = $('<iframe src="javascript:0"/>').hide().insertAfter( 'body' )[0].contentWindow; // Get history by looking at the hidden Iframe's location.hash. get_history = function() { return get_fragment( iframe.document[ str_location ][ str_href ] ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. set_history = function( hash, history_hash ) { if ( hash !== history_hash ) { var doc = iframe.document; doc.open().close(); doc[ str_location ].hash = '#' + hash; } }; // Set initial history. set_history( get_fragment() ); } }; // Start the polling loop. self.start = function() { // Polling loop is already running! if ( timeout_id ) { return; } // Remember the initial hash so it doesn't get triggered immediately. var last_hash = get_fragment(); // Initialize if not yet initialized. set_history || init(); // This polling loop checks every $.hashchangeDelay milliseconds to see if // location.hash has changed, and triggers the 'hashchange' event on // window when necessary. (function loopy(){ var hash = get_fragment(), history_hash = get_history( last_hash ); if ( hash !== last_hash ) { set_history( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { window[ str_location ][ str_href ] = window[ str_location ][ str_href ].replace( /#.*/, '' ) + '#' + history_hash; } timeout_id = setTimeout( loopy, $[ str_hashchange + 'Delay' ] ); })(); }; // Stop the polling loop, but only if an IE6/7 Iframe wasn't created. In // that case, even if there are no longer any bound event handlers, the // polling loop is still necessary for back/next to work at all! self.stop = function() { if ( !iframe ) { timeout_id && clearTimeout( timeout_id ); timeout_id = 0; } }; return self; })(); })(jQuery,this);
JavaScript
/* * Metadata - jQuery plugin for parsing metadata from elements * * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $ * */ /** * Sets the type of metadata to use. Metadata is encoded in JSON, and each property * in the JSON will become a property of the element itself. * * There are four supported types of metadata storage: * * attr: Inside an attribute. The name parameter indicates *which* attribute. * * class: Inside the class attribute, wrapped in curly braces: { } * * elem: Inside a child element (e.g. a script tag). The * name parameter indicates *which* element. * html5: Values are stored in data-* attributes. * * The metadata for an element is loaded the first time the element is accessed via jQuery. * * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements * matched by expr, then redefine the metadata type and run another $(expr) for other elements. * * @name $.metadata.setType * * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p> * @before $.metadata.setType("class") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from the class attribute * * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p> * @before $.metadata.setType("attr", "data") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a "data" attribute * * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p> * @before $.metadata.setType("elem", "script") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a nested script element * * @example <p id="one" class="some_class" data-item_id="1" data-item_label="Label">This is a p</p> * @before $.metadata.setType("html5") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a series of data-* attributes * * @param String type The encoding type * @param String name The name of the attribute to be used to get metadata (optional) * @cat Plugins/Metadata * @descr Sets the type of encoding to be used when loading metadata for the first time * @type undefined * @see metadata() */ (function($) { $.extend({ metadata : { defaults : { type: 'class', name: 'metadata', cre: /({.*})/, single: 'metadata' }, setType: function( type, name ){ this.defaults.type = type; this.defaults.name = name; }, get: function( elem, opts ){ var settings = $.extend({},this.defaults,opts); // check for empty string in single property if ( !settings.single.length ) settings.single = 'metadata'; var data = $.data(elem, settings.single); // returned cached data if it already exists if ( data ) return data; data = "{}"; var getData = function(data) { if(typeof data != "string") return data; if( data.indexOf('{') < 0 ) { data = eval("(" + data + ")"); } }; var getObject = function(data) { if(typeof data != "string") return data; data = eval("(" + data + ")"); return data; }; if ( settings.type == "html5" ) { var object = {}; $( elem.attributes ).each(function() { var name = this.nodeName; if(name.match(/^data-/)) name = name.replace(/^data-/, ''); else return true; object[name] = getObject(this.nodeValue); }); } else { if ( settings.type == "class" ) { var m = settings.cre.exec( elem.className ); if ( m ) data = m[1]; } else if ( settings.type == "elem" ) { if( !elem.getElementsByTagName ) return; var e = elem.getElementsByTagName(settings.name); if ( e.length ) data = $.trim(e[0].innerHTML); } else if ( elem.getAttribute != undefined ) { var attr = elem.getAttribute( settings.name ); if ( attr ) data = attr; } object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data); } $.data( elem, settings.single, object ); return object; } } }); /** * Returns the metadata object for the first member of the jQuery object. * * @name metadata * @descr Returns element's metadata object * @param Object opts An object contianing settings to override the defaults * @type jQuery * @cat Plugins/Metadata */ $.fn.metadata = function( opts ){ return $.metadata.get( this[0], opts ); }; })(jQuery);
JavaScript
/** * jQuery yiiactiveform plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yiiactiveform.js 3158 2011-04-02 22:48:01Z qiang.xue $ * @since 1.1.1 */ ;(function($) { /** * yiiactiveform set function. * @param options map settings for the active form plugin. Please see {@link CActiveForm::options} for availablel options. */ $.fn.yiiactiveform = function(options) { return this.each(function() { var settings = $.extend({}, $.fn.yiiactiveform.defaults, options || {}); var $form = $(this); var id = $form.attr('id'); if(settings.validationUrl == undefined) settings.validationUrl = $form.attr('action'); $.each(settings.attributes, function(i,attribute){ settings.attributes[i] = $.extend({ validationDelay : settings.validationDelay, validateOnChange : settings.validateOnChange, validateOnType : settings.validateOnType, hideErrorMessage : settings.hideErrorMessage, inputContainer : settings.inputContainer, errorCssClass : settings.errorCssClass, successCssClass : settings.successCssClass, beforeValidateAttribute : settings.beforeValidateAttribute, afterValidateAttribute : settings.afterValidateAttribute, validatingCssClass : settings.validatingCssClass }, attribute); settings.attributes[i].value = $('#'+attribute.inputID, $form).val(); }); $(this).data('settings', settings); settings.submitting=false; // whether it is waiting for ajax submission result var validate = function(attribute, forceValidate) { if (forceValidate) attribute.status = 2; $.each(settings.attributes, function(){ if (this.value != $('#'+this.inputID, $form).val()) { this.status = 2; forceValidate = true; } }); if (!forceValidate) return; if(settings.timer!=undefined) { clearTimeout(settings.timer); } settings.timer = setTimeout(function(){ if(settings.submitting) return; if(attribute.beforeValidateAttribute==undefined || attribute.beforeValidateAttribute($form, attribute)) { $.each(settings.attributes, function(){ if (this.status == 2) { this.status = 3; $.fn.yiiactiveform.getInputContainer(this, $form).addClass(this.validatingCssClass); } }); $.fn.yiiactiveform.validate($form, function(data) { var hasError=false; $.each(settings.attributes, function(){ if (this.status == 2 || this.status == 3) { hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError; } }); if(attribute.afterValidateAttribute!=undefined) { attribute.afterValidateAttribute($form,attribute,data,hasError); } }); } }, attribute.validationDelay); }; $.each(settings.attributes, function(i, attribute) { if (attribute.validateOnChange) { $('#'+attribute.inputID, $form).change(function(){ var inputType = $('#'+attribute.inputID).attr('type'); validate(attribute, inputType=='checkbox' || inputType=='radio'); }).blur(function(){ if(attribute.status!=2 && attribute.status!=3) validate(attribute, !attribute.status); }); } if (attribute.validateOnType) { $('#'+attribute.inputID, $form).keyup(function(){ if (attribute.value != $('#'+attribute.inputID, $form).val()) validate(attribute, false); }); } }); if (settings.validateOnSubmit) { $form.find(':submit').live('mouseup keyup',function(){ $form.data('submitObject',$(this)); }); var validated = false; $form.submit(function(){ if (validated) return true; if(settings.timer!=undefined) { clearTimeout(settings.timer); } settings.submitting=true; if(settings.beforeValidate==undefined || settings.beforeValidate($form)) { $.fn.yiiactiveform.validate($form, function(data){ var hasError = false; $.each(settings.attributes, function(i, attribute){ hasError = $.fn.yiiactiveform.updateInput(attribute, data, $form) || hasError; }); $.fn.yiiactiveform.updateSummary($form, data); if(settings.afterValidate==undefined || settings.afterValidate($form, data, hasError)) { if(!hasError) { validated = true; var $button = $form.data('submitObject') || $form.find(':submit:first'); // TODO: if the submission is caused by "change" event, it will not work if ($button.length) $button.click(); else // no submit button in the form $form.submit(); return false; } } settings.submitting=false; }); } else { settings.submitting=false; } return false; }); } /* * In case of reseting the form we need to reset error messages * NOTE1: $form.reset - does not exist * NOTE2: $form.live('reset',...) does not work */ $form.bind('reset',function(){ /* * because we bind directly to a form reset event, not to a reset button (that could or could not exist), * when this function is executed form elements values have not been reset yet, * because of that we use the setTimeout */ setTimeout(function(){ $.each(settings.attributes, function(i, attribute){ attribute.status = 0; var $error = $('#'+attribute.errorID, $form); var $container = $.fn.yiiactiveform.getInputContainer(attribute, $form); $container .removeClass(attribute.validatingCssClass) .removeClass(attribute.errorCssClass) .removeClass(attribute.successCssClass); $error.html('').hide(); /* * without the setTimeout() call val() would return the entered value instead of the reseted value */ attribute.value = $('#'+attribute.inputID, $form).val(); /* * If the form is submited (non ajax) with errors, labels and input gets the class 'error' */ $('label,input',$form).each(function(){ $(this).removeClass('error'); }); }); $('#'+settings.summaryID+' ul').html(''); $('#'+settings.summaryID).hide(); //.. set to initial focus on reset if(settings.focus != undefined && !window.location.hash) $(settings.focus).focus(); },1); }); /* * set to initial focus */ if(settings.focus != undefined && !window.location.hash) $(settings.focus).focus(); }); }; /** * Returns the container element of the specified attribute. * @param attribute object the configuration for a particular attribute. * @param form the form jQuery object * @return jquery the jquery representation of the container */ $.fn.yiiactiveform.getInputContainer = function(attribute, form) { if(attribute.inputContainer == undefined) return $('#'+attribute.inputID, form).closest('div'); else return $(attribute.inputContainer).filter(':has("#'+attribute.inputID+'")'); }; /** * updates the error message and the input container for a particular attribute. * @param attribute object the configuration for a particular attribute. * @param messages array the json data obtained from the ajax validation request * @param form the form jQuery object * @return boolean whether there is a validation error for the specified attribute */ $.fn.yiiactiveform.updateInput = function(attribute, messages, form) { attribute.status = 1; var hasError = messages!=null && $.isArray(messages[attribute.id]) && messages[attribute.id].length>0; var $error = $('#'+attribute.errorID, form); var $container = $.fn.yiiactiveform.getInputContainer(attribute, form); $container.removeClass(attribute.validatingCssClass) .removeClass(attribute.errorCssClass) .removeClass(attribute.successCssClass); if(hasError) { $error.html(messages[attribute.id][0]); $container.addClass(attribute.errorCssClass); } else if(attribute.enableAjaxValidation || attribute.clientValidation) { $container.addClass(attribute.successCssClass); } if(!attribute.hideErrorMessage) $error.toggle(hasError); attribute.value = $('#'+attribute.inputID, form).val(); return hasError; }; /** * updates the error summary, if any. * @param form jquery the jquery representation of the form * @param messages array the json data obtained from the ajax validation request */ $.fn.yiiactiveform.updateSummary = function(form, messages) { var settings = $(form).data('settings'); if (settings.summaryID == undefined) return; var content = ''; $.each(settings.attributes, function(i, attribute){ if(messages && $.isArray(messages[attribute.id])) { $.each(messages[attribute.id],function(j,message){ content = content + '<li>' + message + '</li>'; }); } }); $('#'+settings.summaryID+' ul').html(content); $('#'+settings.summaryID).toggle(content!=''); }; /** * Performs the ajax validation request. * This method is invoked internally to trigger the ajax validation. * @param form jquery the jquery representation of the form * @param successCallback function the function to be invoked if the ajax request succeeds * @param errorCallback function the function to be invoked if the ajax request fails */ $.fn.yiiactiveform.validate = function(form, successCallback, errorCallback) { var $form = $(form); var settings = $form.data('settings'); var messages = {}; var needAjaxValidation = false; $.each(settings.attributes, function(){ var msg = []; if (this.clientValidation != undefined && (settings.submitting || this.status == 2 || this.status == 3)) { var value = $('#'+this.inputID, $form).val(); this.clientValidation(value, msg, this); if (msg.length) { messages[this.id] = msg; } } if (this.enableAjaxValidation && !msg.length && (settings.submitting || this.status == 2 || this.status == 3)) needAjaxValidation = true; }); if (!needAjaxValidation || settings.submitting && !$.isEmptyObject(messages)) { if(settings.submitting) { // delay callback so that the form can be submitted without problem setTimeout(function(){ successCallback(messages); },200); } else { successCallback(messages); } return; } $.ajax({ url : settings.validationUrl, type : $form.attr('method'), data : $form.serialize()+'&'+settings.ajaxVar+'='+$form.attr('id'), dataType : 'json', success : function(data) { if (data != null && typeof data == 'object') { $.each(settings.attributes, function() { if (!this.enableAjaxValidation) delete data[this.id]; }); successCallback($.extend({}, messages, data)); } else { successCallback(messages); } }, error : function() { if (errorCallback!=undefined) { errorCallback(); } } }); }; /** * Returns the configuration for the specified form. * The configuration contains all needed information to perform ajax-based validation. * @param form jquery the jquery representation of the form * @return object the configuration for the specified form. */ $.fn.yiiactiveform.getSettings = function(form) { return $(form).data('settings'); }; $.fn.yiiactiveform.defaults = { ajaxVar: 'ajax', validationUrl: undefined, validationDelay: 200, validateOnSubmit : false, validateOnChange : true, validateOnType : false, hideErrorMessage : false, inputContainer : undefined, errorCssClass : 'error', successCssClass : 'success', validatingCssClass : 'validating', summaryID : undefined, timer: undefined, beforeValidateAttribute: undefined, // function(form, attribute) : boolean afterValidateAttribute: undefined, // function(form, attribute, data, hasError) beforeValidate: undefined, // function(form) : boolean afterValidate: undefined, // function(form, data, hasError) : boolean /** * list of attributes to be validated. Each array element is of the following structure: * { * id : 'ModelClass_attribute', // the unique attribute ID * model : 'ModelClass', // the model class name * name : 'name', // attribute name * inputID : 'input-tag-id', * errorID : 'error-tag-id', * value : undefined, * status : 0, // 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating * focus : undefined, // jquery selector that indicates which element to receive input focus initially * validationDelay: 200, * validateOnChange : true, * validateOnType : false, * hideErrorMessage : false, * inputContainer : undefined, * errorCssClass : 'error', * successCssClass : 'success', * validatingCssClass : 'validating', * enableAjaxValidation : true, * enableClientValidation : true, * clientValidation : undefined, // function(value, messages, attribute) : client-side validation * beforeValidateAttribute: undefined, // function(form, attribute) : boolean * afterValidateAttribute: undefined, // function(form, attribute, data, hasError) * } */ attributes : [] }; })(jQuery);
JavaScript
/* * Treeview 1.5pre - jQuery plugin to hide and show branches of a tree * * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ * http://docs.jquery.com/Plugins/Treeview * * Copyright (c) 2007 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $ * */ ;(function($) { // TODO rewrite as a widget, removing all the extra plugins $.extend($.fn, { swapClass: function(c1, c2) { var c1Elements = this.filter('.' + c1); this.filter('.' + c2).removeClass(c2).addClass(c1); c1Elements.removeClass(c1).addClass(c2); return this; }, replaceClass: function(c1, c2) { return this.filter('.' + c1).removeClass(c1).addClass(c2).end(); }, hoverClass: function(className) { className = className || "hover"; return this.hover(function() { $(this).addClass(className); }, function() { $(this).removeClass(className); }); }, heightToggle: function(animated, callback) { animated ? this.animate({ height: "toggle" }, animated, callback) : this.each(function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ](); if(callback) callback.apply(this, arguments); }); }, heightHide: function(animated, callback) { if (animated) { this.animate({ height: "hide" }, animated, callback); } else { this.hide(); if (callback) this.each(callback); } }, prepareBranches: function(settings) { if (!settings.prerendered) { // mark last tree items this.filter(":last-child:not(ul)").addClass(CLASSES.last); // collapse whole tree, or only those marked as closed, anyway except those marked as open this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide(); } // return all items with sublists return this.filter(":has(>ul)"); }, applyClasses: function(settings, toggler) { // TODO use event delegation this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) { // don't handle click events on children, eg. checkboxes if ( this == event.target ) toggler.apply($(this).next()); }).add( $("a", this) ).hoverClass(); if (!settings.prerendered) { // handle closed ones first this.filter(":has(>ul:hidden)") .addClass(CLASSES.expandable) .replaceClass(CLASSES.last, CLASSES.lastExpandable); // handle open ones this.not(":has(>ul:hidden)") .addClass(CLASSES.collapsable) .replaceClass(CLASSES.last, CLASSES.lastCollapsable); // create hitarea if not present var hitarea = this.find("div." + CLASSES.hitarea); if (!hitarea.length) hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea); hitarea.removeClass().addClass(CLASSES.hitarea).each(function() { var classes = ""; $.each($(this).parent().attr("class").split(" "), function() { classes += this + "-hitarea "; }); $(this).addClass( classes ); }) } // apply event to hitarea this.find("div." + CLASSES.hitarea).click( toggler ); }, treeview: function(settings) { settings = $.extend({ cookieId: "treeview" }, settings); if ( settings.toggle ) { var callback = settings.toggle; settings.toggle = function() { return callback.apply($(this).parent()[0], arguments); }; } // factory for treecontroller function treeController(tree, control) { // factory for click handlers function handler(filter) { return function() { // reuse toggle event handler, applying the elements to toggle // start searching for all hitareas toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() { // for plain toggle, no filter is provided, otherwise we need to check the parent element return filter ? $(this).parent("." + filter).length : true; }) ); return false; }; } // click on first element to collapse tree $("a:eq(0)", control).click( handler(CLASSES.collapsable) ); // click on second to expand tree $("a:eq(1)", control).click( handler(CLASSES.expandable) ); // click on third to toggle tree $("a:eq(2)", control).click( handler() ); } // handle toggle event function toggler() { $(this) .parent() // swap classes for hitarea .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() // swap classes for parent li .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) // find child lists .find( ">ul" ) // toggle them .heightToggle( settings.animated, settings.toggle ); if ( settings.unique ) { $(this).parent() .siblings() // swap classes for hitarea .find(">.hitarea") .replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() .replaceClass( CLASSES.collapsable, CLASSES.expandable ) .replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find( ">ul" ) .heightHide( settings.animated, settings.toggle ); } } this.data("toggler", toggler); function serialize() { function binary(arg) { return arg ? 1 : 0; } var data = []; branches.each(function(i, e) { data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0; }); $.cookie(settings.cookieId, data.join(""), settings.cookieOptions ); } function deserialize() { var stored = $.cookie(settings.cookieId); if ( stored ) { var data = stored.split(""); branches.each(function(i, e) { $(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ](); }); } } // add treeview class to activate styles this.addClass("treeview"); // prepare branches and find all tree items with child lists var branches = this.find("li").prepareBranches(settings); switch(settings.persist) { case "cookie": var toggleCallback = settings.toggle; settings.toggle = function() { serialize(); if (toggleCallback) { toggleCallback.apply(this, arguments); } }; deserialize(); break; case "location": var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); }); if ( current.length ) { // TODO update the open/closed classes var items = current.addClass("selected").parents("ul, li").add( current.next() ).show(); if (settings.prerendered) { // if prerendered is on, replicate the basic class swapping items.filter("li") .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ); } } break; } branches.applyClasses(settings, toggler); // if control option is set, create the treecontroller and show it if ( settings.control ) { treeController(this, settings.control); $(settings.control).show(); } return this; } }); // classes used by the plugin // need to be styled via external stylesheet, see first example $.treeview = {}; var CLASSES = ($.treeview.classes = { open: "open", closed: "closed", expandable: "expandable", expandableHitarea: "expandable-hitarea", lastExpandableHitarea: "lastExpandable-hitarea", collapsable: "collapsable", collapsableHitarea: "collapsable-hitarea", lastCollapsableHitarea: "lastCollapsable-hitarea", lastCollapsable: "lastCollapsable", lastExpandable: "lastExpandable", last: "last", hitarea: "hitarea" }); })(jQuery);
JavaScript
(function($) { var CLASSES = $.treeview.classes; var proxied = $.fn.treeview; $.fn.treeview = function(settings) { settings = $.extend({}, settings); if (settings.add) { return this.trigger("add", [settings.add]); } if (settings.remove) { return this.trigger("remove", [settings.remove]); } return proxied.apply(this, arguments).bind("add", function(event, branches) { $(branches).prev() .removeClass(CLASSES.last) .removeClass(CLASSES.lastCollapsable) .removeClass(CLASSES.lastExpandable) .find(">.hitarea") .removeClass(CLASSES.lastCollapsableHitarea) .removeClass(CLASSES.lastExpandableHitarea); $(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, $(this).data("toggler")); }).bind("remove", function(event, branches) { var prev = $(branches).prev(); var parent = $(branches).parent(); $(branches).remove(); prev.filter(":last-child").addClass(CLASSES.last) .filter("." + CLASSES.expandable).replaceClass(CLASSES.last, CLASSES.lastExpandable).end() .find(">.hitarea").replaceClass(CLASSES.expandableHitarea, CLASSES.lastExpandableHitarea).end() .filter("." + CLASSES.collapsable).replaceClass(CLASSES.last, CLASSES.lastCollapsable).end() .find(">.hitarea").replaceClass(CLASSES.collapsableHitarea, CLASSES.lastCollapsableHitarea); if (parent.is(":not(:has(>))") && parent[0] != this) { parent.parent().removeClass(CLASSES.collapsable).removeClass(CLASSES.expandable); parent.siblings(".hitarea").andSelf().remove(); } }); }; })(jQuery);
JavaScript
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Version 2.1.2 */ (function($){ $.fn.bgiframe = ($.browser.msie && /msie 6\.0/i.test(navigator.userAgent) ? function(s) { s = $.extend({ top : 'auto', // auto == .currentStyle.borderTopWidth left : 'auto', // auto == .currentStyle.borderLeftWidth width : 'auto', // auto == offsetWidth height : 'auto', // auto == offsetHeight opacity : true, src : 'javascript:false;' }, s); var html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+ 'style="display:block;position:absolute;z-index:-1;'+ (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+ 'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+ 'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+ 'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+ 'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+ '"/>'; return this.each(function() { if ( $(this).children('iframe.bgiframe').length === 0 ) this.insertBefore( document.createElement(html), this.firstChild ); }); } : function() { return this; }); // old alias $.fn.bgIframe = $.fn.bgiframe; function prop(n) { return n && n.constructor === Number ? n + 'px' : n; } })(jQuery);
JavaScript