From 3c4185c9b1dbe2ed0bf46e150a77a2505cec1f5c Mon Sep 17 00:00:00 2001 From: danielyxie Date: Thu, 16 Nov 2017 15:41:40 -0600 Subject: [PATCH] Fixed gang display bug --- dist/bundle.js | 76294 +++++++++++++++++++++++------------------------ src/Gang.js | 2 +- 2 files changed, 38148 insertions(+), 38148 deletions(-) diff --git a/dist/bundle.js b/dist/bundle.js index 8dcfe37c5..a6599e1fa 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -74,23 +74,23 @@ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BitNode_js__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Company_js__ = __webpack_require__(21); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__ = __webpack_require__(15); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Crimes_js__ = __webpack_require__(32); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Crimes_js__ = __webpack_require__(31); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Faction_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Gang_js__ = __webpack_require__(34); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Faction_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Gang_js__ = __webpack_require__(39); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Location_js__ = __webpack_require__(13); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__NetscriptFunctions_js__ = __webpack_require__(19); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__NetscriptFunctions_js__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Server_js__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__SourceFile_js__ = __webpack_require__(35); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_decimal_js__ = __webpack_require__(28); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_decimal_js__ = __webpack_require__(29); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_14__utils_decimal_js__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__utils_IPAddress_js__ = __webpack_require__(17); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__utils_IPAddress_js__ = __webpack_require__(18); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__utils_JSONReviver_js__ = __webpack_require__(8); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_numeral_min_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_numeral_min_js__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_19__utils_numeral_min_js__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__utils_StringHelperFunctions_js__ = __webpack_require__(4); @@ -3882,7 +3882,7 @@ Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_GameOptions_js__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_LogBox_js__ = __webpack_require__(30); @@ -3891,27 +3891,27 @@ Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__BitNode_js__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Company_js__ = __webpack_require__(21); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__CreateProgram_js__ = __webpack_require__(15); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Faction_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__CreateProgram_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Faction_js__ = __webpack_require__(11); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__Location_js__ = __webpack_require__(13); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__Gang_js__ = __webpack_require__(34); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__HacknetNode_js__ = __webpack_require__(39); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__InteractiveTutorial_js__ = __webpack_require__(27); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__Gang_js__ = __webpack_require__(39); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__HacknetNode_js__ = __webpack_require__(38); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__InteractiveTutorial_js__ = __webpack_require__(26); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__Literature_js__ = __webpack_require__(46); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__Message_js__ = __webpack_require__(24); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__Missions_js__ = __webpack_require__(26); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__NetscriptFunctions_js__ = __webpack_require__(19); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__NetscriptWorker_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__Missions_js__ = __webpack_require__(27); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__NetscriptFunctions_js__ = __webpack_require__(22); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__NetscriptWorker_js__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__Prestige_js__ = __webpack_require__(36); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__RedPill_js__ = __webpack_require__(37); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__Prestige_js__ = __webpack_require__(34); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__RedPill_js__ = __webpack_require__(33); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__SaveObject_js__ = __webpack_require__(75); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__Script_js__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_27__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__Settings_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__Settings_js__ = __webpack_require__(15); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_29__SourceFile_js__ = __webpack_require__(35); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_30__SpecialServerIps_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_31__StockMarket_js__ = __webpack_require__(29); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_31__StockMarket_js__ = __webpack_require__(28); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_32__Terminal_js__ = __webpack_require__(23); @@ -5645,12 +5645,12 @@ window.onload = function() { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return prestigeHomeComputer; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__ = __webpack_require__(15); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__ = __webpack_require__(14); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Script_js__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__ = __webpack_require__(17); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__ = __webpack_require__(18); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__ = __webpack_require__(8); @@ -17055,6 +17055,254 @@ return jQuery; /* 10 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return WorkerScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return workerScripts; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptPorts; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptsLoop; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return killWorkerScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return addWorkerScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return updateOnlineScriptTimes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return prestigeWorkerScripts; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(25); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__engine_js__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__ = __webpack_require__(37); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__ = __webpack_require__(36); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(15); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__ = __webpack_require__(47); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_acorn_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__ = __webpack_require__(2); + + + + + + + + + + + + +function WorkerScript(runningScriptObj) { + this.name = runningScriptObj.filename; + this.running = false; + this.serverIp = null; + this.code = runningScriptObj.scriptRef.code; + this.env = new __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__["a" /* Environment */](this); + this.env.set("args", runningScriptObj.args); + this.output = ""; + this.ramUsage = 0; + this.scriptRef = runningScriptObj; + this.errorMessage = ""; + this.args = runningScriptObj.args; + //this.killTrigger = function() {}; //CB func used to clear any delays (netscriptDelay()) + this.delay = null; + this.fnWorker = null; //Workerscript for a function call +} + +//Returns the server on which the workerScript is running +WorkerScript.prototype.getServer = function() { + return __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][this.serverIp]; +} + +//Array containing all scripts that are running across all servers, to easily run them all +let workerScripts = []; + +let NetscriptPorts = { + Port1: [], + Port2: [], + Port3: [], + Port4: [], + Port5: [], + Port6: [], + Port7: [], + Port8: [], + Port9: [], + Port10: [], +} + +function prestigeWorkerScripts() { + for (var i = 0; i < workerScripts.length; ++i) { + Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["b" /* deleteActiveScriptsItem */])(workerScripts[i]); + workerScripts[i].env.stopFlag = true; + } + workerScripts.length = 0; +} + +//Loop through workerScripts and run every script that is not currently running +function runScriptsLoop() { + //Delete any scripts that finished or have been killed. Loop backwards bc removing + //items fucks up the indexing + for (var i = workerScripts.length - 1; i >= 0; i--) { + if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) { + console.log("Deleting script: " + workerScripts[i].name); + //Delete script from the runningScripts array on its host serverIp + var ip = workerScripts[i].serverIp; + var name = workerScripts[i].name; + + for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts.length; j++) { + if (__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts[j].filename == name && + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["c" /* compareArrays */])(__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts[j].args, workerScripts[i].args)) { + __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts.splice(j, 1); + break; + } + } + + //Free RAM + __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].ramUsed -= workerScripts[i].ramUsage; + + //Delete script from Active Scripts + Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["b" /* deleteActiveScriptsItem */])(workerScripts[i]); + + //Delete script from workerScripts + workerScripts.splice(i, 1); + } + } + + //Run any scripts that haven't been started + for (var i = 0; i < workerScripts.length; i++) { + //If it isn't running, start the script + if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { + try { + var ast = Object(__WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__["parse"])(workerScripts[i].code); + //console.log(ast); + } catch (e) { + console.log("Error parsing script: " + workerScripts[i].name); + Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Syntax ERROR in " + workerScripts[i].name + ":
" + e); + workerScripts[i].env.stopFlag = true; + continue; + } + + workerScripts[i].running = true; + var p = Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["a" /* evaluate */])(ast, workerScripts[i]); + //Once the code finishes (either resolved or rejected, doesnt matter), set its + //running status to false + p.then(function(w) { + console.log("Stopping script " + w.name + " because it finished running naturally"); + w.running = false; + w.env.stopFlag = true; + w.scriptRef.log("Script finished running"); + }).catch(function(w) { + console.log(w); + if (w instanceof Error) { + Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script runtime unknown error. This is a bug please contact game developer"); + console.log("ERROR: Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString()); + return; + } else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") { + //Script ends with a return statement + console.log("Script returning with value: " + w[1]); + //TODO maybe do something with this in the future + return; + } else if (w instanceof WorkerScript) { + if (Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["b" /* isScriptErrorMessage */])(w.errorMessage)) { + var errorTextArray = w.errorMessage.split("|"); + if (errorTextArray.length != 4) { + console.log("ERROR: Something wrong with Error text in evaluator..."); + console.log("Error text: " + errorText); + return; + } + var serverIp = errorTextArray[1]; + var scriptName = errorTextArray[2]; + var errorMsg = errorTextArray[3]; + + Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script runtime error:
Server Ip: " + serverIp + + "
Script name: " + scriptName + + "
Args:" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["f" /* printArray */])(w.args) + "
" + errorMsg); + w.scriptRef.log("Script crashed with runtime error"); + } else { + w.scriptRef.log("Script killed"); + } + w.running = false; + w.env.stopFlag = true; + + } else if (Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["b" /* isScriptErrorMessage */])(w)) { + Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script runtime unknown error. This is a bug please contact game developer"); + console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString()); + return; + } else { + Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("An unknown script died for an unknown reason. This is a bug please contact game dev"); + } + }); + } + } + + setTimeout(runScriptsLoop, 6000); +} + +//Queues a script to be killed by settings its stop flag to true. Then, the code will reject +//all of its promises recursively, and when it does so it will no longer be running. +//The runScriptsLoop() will then delete the script from worker scripts +function killWorkerScript(runningScriptObj, serverIp) { + for (var i = 0; i < workerScripts.length; i++) { + if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp && + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["c" /* compareArrays */])(workerScripts[i].args, runningScriptObj.args)) { + workerScripts[i].env.stopFlag = true; + Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["c" /* killNetscriptDelay */])(workerScripts[i]); + if (workerScripts[i].fnWorker) { + workerScripts[i].fnWorker.env.stopFlag = true; + Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["c" /* killNetscriptDelay */])(workerScripts[i].fnWorker); + } + return true; + } + } + return false; +} + +//Queues a script to be run +function addWorkerScript(runningScriptObj, server) { + var filename = runningScriptObj.filename; + + //Update server's ram usage + var threads = 1; + if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) { + threads = runningScriptObj.threads; + } else { + runningScriptObj.threads = 1; + } + var ramUsage = runningScriptObj.scriptRef.ramUsage * threads + * Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultithreadingRAMCost, threads-1); + var ramAvailable = server.maxRam - server.ramUsed; + if (ramUsage > ramAvailable) { + Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Not enough RAM to run script " + runningScriptObj.filename + " with args " + + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["f" /* printArray */])(runningScriptObj.args) + ". This likely occurred because you re-loaded " + + "the game and the script's RAM usage increased (either because of an update to the game or " + + "your changes to the script.)"); + return; + } + server.ramUsed += ramUsage; + + //Create the WorkerScript + var s = new WorkerScript(runningScriptObj); + s.serverIp = server.ip; + s.ramUsage = ramUsage; + + //Add the WorkerScript to the Active Scripts list + Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["a" /* addActiveScriptsItem */])(s); + + //Add the WorkerScript + workerScripts.push(s); + return; +} + +//Updates the online running time stat of all running scripts +function updateOnlineScriptTimes(numCycles = 1) { + var time = (numCycles * __WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed) / 1000; //seconds + for (var i = 0; i < workerScripts.length; ++i) { + workerScripts[i].scriptRef.onlineRunningTime += time; + } +} + + + + +/***/ }), +/* 11 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + "use strict"; /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getNextNeurofluxLevel; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Factions; }); @@ -17071,17 +17319,17 @@ return jQuery; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BitNode_js__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Constants_js__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__ = __webpack_require__(52); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__ = __webpack_require__(50); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Location_js__ = __webpack_require__(13); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Missions_js__ = __webpack_require__(26); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Missions_js__ = __webpack_require__(27); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Settings_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Settings_js__ = __webpack_require__(15); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_FactionInvitationBox_js__ = __webpack_require__(54); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_FactionInvitationBox_js__ = __webpack_require__(74); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_HelperFunctions_js__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_JSONReviver_js__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__utils_StringHelperFunctions_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_YesNoBox_js__ = __webpack_require__(22); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_YesNoBox_js__ = __webpack_require__(17); @@ -18128,254 +18376,6 @@ function processPassiveFactionRepGain(numCycles) { /* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9))) -/***/ }), -/* 11 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return WorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return workerScripts; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptPorts; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptsLoop; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return killWorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return addWorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return updateOnlineScriptTimes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return prestigeWorkerScripts; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(25); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__ = __webpack_require__(31); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__ = __webpack_require__(38); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(14); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__ = __webpack_require__(47); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_acorn_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__ = __webpack_require__(2); - - - - - - - - - - - - -function WorkerScript(runningScriptObj) { - this.name = runningScriptObj.filename; - this.running = false; - this.serverIp = null; - this.code = runningScriptObj.scriptRef.code; - this.env = new __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__["a" /* Environment */](this); - this.env.set("args", runningScriptObj.args); - this.output = ""; - this.ramUsage = 0; - this.scriptRef = runningScriptObj; - this.errorMessage = ""; - this.args = runningScriptObj.args; - //this.killTrigger = function() {}; //CB func used to clear any delays (netscriptDelay()) - this.delay = null; - this.fnWorker = null; //Workerscript for a function call -} - -//Returns the server on which the workerScript is running -WorkerScript.prototype.getServer = function() { - return __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][this.serverIp]; -} - -//Array containing all scripts that are running across all servers, to easily run them all -let workerScripts = []; - -let NetscriptPorts = { - Port1: [], - Port2: [], - Port3: [], - Port4: [], - Port5: [], - Port6: [], - Port7: [], - Port8: [], - Port9: [], - Port10: [], -} - -function prestigeWorkerScripts() { - for (var i = 0; i < workerScripts.length; ++i) { - Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["b" /* deleteActiveScriptsItem */])(workerScripts[i]); - workerScripts[i].env.stopFlag = true; - } - workerScripts.length = 0; -} - -//Loop through workerScripts and run every script that is not currently running -function runScriptsLoop() { - //Delete any scripts that finished or have been killed. Loop backwards bc removing - //items fucks up the indexing - for (var i = workerScripts.length - 1; i >= 0; i--) { - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) { - console.log("Deleting script: " + workerScripts[i].name); - //Delete script from the runningScripts array on its host serverIp - var ip = workerScripts[i].serverIp; - var name = workerScripts[i].name; - - for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts.length; j++) { - if (__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts[j].filename == name && - Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["c" /* compareArrays */])(__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts[j].args, workerScripts[i].args)) { - __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts.splice(j, 1); - break; - } - } - - //Free RAM - __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].ramUsed -= workerScripts[i].ramUsage; - - //Delete script from Active Scripts - Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["b" /* deleteActiveScriptsItem */])(workerScripts[i]); - - //Delete script from workerScripts - workerScripts.splice(i, 1); - } - } - - //Run any scripts that haven't been started - for (var i = 0; i < workerScripts.length; i++) { - //If it isn't running, start the script - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { - try { - var ast = Object(__WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__["parse"])(workerScripts[i].code); - //console.log(ast); - } catch (e) { - console.log("Error parsing script: " + workerScripts[i].name); - Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Syntax ERROR in " + workerScripts[i].name + ":
" + e); - workerScripts[i].env.stopFlag = true; - continue; - } - - workerScripts[i].running = true; - var p = Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["a" /* evaluate */])(ast, workerScripts[i]); - //Once the code finishes (either resolved or rejected, doesnt matter), set its - //running status to false - p.then(function(w) { - console.log("Stopping script " + w.name + " because it finished running naturally"); - w.running = false; - w.env.stopFlag = true; - w.scriptRef.log("Script finished running"); - }).catch(function(w) { - console.log(w); - if (w instanceof Error) { - Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") { - //Script ends with a return statement - console.log("Script returning with value: " + w[1]); - //TODO maybe do something with this in the future - return; - } else if (w instanceof WorkerScript) { - if (Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["b" /* isScriptErrorMessage */])(w.errorMessage)) { - var errorTextArray = w.errorMessage.split("|"); - if (errorTextArray.length != 4) { - console.log("ERROR: Something wrong with Error text in evaluator..."); - console.log("Error text: " + errorText); - return; - } - var serverIp = errorTextArray[1]; - var scriptName = errorTextArray[2]; - var errorMsg = errorTextArray[3]; - - Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script runtime error:
Server Ip: " + serverIp + - "
Script name: " + scriptName + - "
Args:" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["f" /* printArray */])(w.args) + "
" + errorMsg); - w.scriptRef.log("Script crashed with runtime error"); - } else { - w.scriptRef.log("Script killed"); - } - w.running = false; - w.env.stopFlag = true; - - } else if (Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["b" /* isScriptErrorMessage */])(w)) { - Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else { - Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("An unknown script died for an unknown reason. This is a bug please contact game dev"); - } - }); - } - } - - setTimeout(runScriptsLoop, 6000); -} - -//Queues a script to be killed by settings its stop flag to true. Then, the code will reject -//all of its promises recursively, and when it does so it will no longer be running. -//The runScriptsLoop() will then delete the script from worker scripts -function killWorkerScript(runningScriptObj, serverIp) { - for (var i = 0; i < workerScripts.length; i++) { - if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp && - Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["c" /* compareArrays */])(workerScripts[i].args, runningScriptObj.args)) { - workerScripts[i].env.stopFlag = true; - Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["c" /* killNetscriptDelay */])(workerScripts[i]); - if (workerScripts[i].fnWorker) { - workerScripts[i].fnWorker.env.stopFlag = true; - Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["c" /* killNetscriptDelay */])(workerScripts[i].fnWorker); - } - return true; - } - } - return false; -} - -//Queues a script to be run -function addWorkerScript(runningScriptObj, server) { - var filename = runningScriptObj.filename; - - //Update server's ram usage - var threads = 1; - if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) { - threads = runningScriptObj.threads; - } else { - runningScriptObj.threads = 1; - } - var ramUsage = runningScriptObj.scriptRef.ramUsage * threads - * Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultithreadingRAMCost, threads-1); - var ramAvailable = server.maxRam - server.ramUsed; - if (ramUsage > ramAvailable) { - Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Not enough RAM to run script " + runningScriptObj.filename + " with args " + - Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["f" /* printArray */])(runningScriptObj.args) + ". This likely occurred because you re-loaded " + - "the game and the script's RAM usage increased (either because of an update to the game or " + - "your changes to the script.)"); - return; - } - server.ramUsed += ramUsage; - - //Create the WorkerScript - var s = new WorkerScript(runningScriptObj); - s.serverIp = server.ip; - s.ramUsage = ramUsage; - - //Add the WorkerScript to the Active Scripts list - Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["a" /* addActiveScriptsItem */])(s); - - //Add the WorkerScript - workerScripts.push(s); - return; -} - -//Updates the online running time stat of all running scripts -function updateOnlineScriptTimes(numCycles = 1) { - var time = (numCycles * __WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed) / 1000; //seconds - for (var i = 0; i < workerScripts.length; ++i) { - workerScripts[i].scriptRef.onlineRunningTime += time; - } -} - - - - /***/ }), /* 12 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -18448,20 +18448,20 @@ function initSpecialServerIps() { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initLocationButtons; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Company_js__ = __webpack_require__(21); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Crimes_js__ = __webpack_require__(32); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Crimes_js__ = __webpack_require__(31); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Infiltration_js__ = __webpack_require__(50); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Infiltration_js__ = __webpack_require__(51); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__ServerPurchases_js__ = __webpack_require__(70); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__ServerPurchases_js__ = __webpack_require__(73); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__SpecialServerIps_js__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_IPAddress_js__ = __webpack_require__(17); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_numeral_min_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_IPAddress_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_numeral_min_js__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_12__utils_numeral_min_js__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__utils_StringHelperFunctions_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_YesNoBox_js__ = __webpack_require__(22); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_YesNoBox_js__ = __webpack_require__(17); @@ -20559,78 +20559,6 @@ function purchaseServerBoxCreate(ram, cost) { /* 14 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Settings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return initSettings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return setSettingsLabels; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadSettings; }); -/* Settings.js */ -let Settings = { - CodeInstructionRunTime: 50, - MaxLogCapacity: 50, - MaxPortCapacity: 50, - SuppressMessages: false, - SuppressFactionInvites: false, -} - -function loadSettings(saveString) { - Settings = JSON.parse(saveString); -} - -function initSettings() { - Settings.CodeInstructionRunTime = 50; - Settings.MaxLogCapacity = 50; - Settings.MaxPortCapacity = 50; - Settings.SuppressMessages = false; - Settings.SuppressFactionInvites = false; -} - -function setSettingsLabels() { - var nsExecTime = document.getElementById("settingsNSExecTimeRangeValLabel"); - var nsLogLimit = document.getElementById("settingsNSLogRangeValLabel"); - var nsPortLimit = document.getElementById("settingsNSPortRangeValLabel"); - var suppressMsgs = document.getElementById("settingsSuppressMessages"); - var suppressFactionInv = document.getElementById("settingsSuppressFactionInvites") - - //Initialize values on labels - nsExecTime.innerHTML = Settings.CodeInstructionRunTime + "ms"; - nsLogLimit.innerHTML = Settings.MaxLogCapacity; - nsPortLimit.innerHTML = Settings.MaxPortCapacity; - suppressMsgs.checked = Settings.SuppressMessages; - suppressFactionInv.checked = Settings.SuppressFactionInvites; - - //Set handlers for when input changes - document.getElementById("settingsNSExecTimeRangeVal").oninput = function() { - nsExecTime.innerHTML = this.value + 'ms'; - Settings.CodeInstructionRunTime = this.value; - }; - - document.getElementById("settingsNSLogRangeVal").oninput = function() { - nsLogLimit.innerHTML = this.value; - Settings.MaxLogCapacity = this.value; - }; - - document.getElementById("settingsNSPortRangeVal").oninput = function() { - nsPortLimit.innerHTML = this.value; - Settings.MaxPortCapacity = this.value; - }; - - document.getElementById("settingsSuppressMessages").onclick = function() { - Settings.SuppressMessages = this.checked; - }; - - document.getElementById("settingsSuppressFactionInvites").onclick = function() { - Settings.SuppressFactionInvites = this.checked; - }; -} - - - - -/***/ }), -/* 15 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Programs; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return displayCreateProgramContent; }); @@ -20840,6 +20768,78 @@ function initCreateProgramButtons() { +/***/ }), +/* 15 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Settings; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return initSettings; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return setSettingsLabels; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadSettings; }); +/* Settings.js */ +let Settings = { + CodeInstructionRunTime: 50, + MaxLogCapacity: 50, + MaxPortCapacity: 50, + SuppressMessages: false, + SuppressFactionInvites: false, +} + +function loadSettings(saveString) { + Settings = JSON.parse(saveString); +} + +function initSettings() { + Settings.CodeInstructionRunTime = 50; + Settings.MaxLogCapacity = 50; + Settings.MaxPortCapacity = 50; + Settings.SuppressMessages = false; + Settings.SuppressFactionInvites = false; +} + +function setSettingsLabels() { + var nsExecTime = document.getElementById("settingsNSExecTimeRangeValLabel"); + var nsLogLimit = document.getElementById("settingsNSLogRangeValLabel"); + var nsPortLimit = document.getElementById("settingsNSPortRangeValLabel"); + var suppressMsgs = document.getElementById("settingsSuppressMessages"); + var suppressFactionInv = document.getElementById("settingsSuppressFactionInvites") + + //Initialize values on labels + nsExecTime.innerHTML = Settings.CodeInstructionRunTime + "ms"; + nsLogLimit.innerHTML = Settings.MaxLogCapacity; + nsPortLimit.innerHTML = Settings.MaxPortCapacity; + suppressMsgs.checked = Settings.SuppressMessages; + suppressFactionInv.checked = Settings.SuppressFactionInvites; + + //Set handlers for when input changes + document.getElementById("settingsNSExecTimeRangeVal").oninput = function() { + nsExecTime.innerHTML = this.value + 'ms'; + Settings.CodeInstructionRunTime = this.value; + }; + + document.getElementById("settingsNSLogRangeVal").oninput = function() { + nsLogLimit.innerHTML = this.value; + Settings.MaxLogCapacity = this.value; + }; + + document.getElementById("settingsNSPortRangeVal").oninput = function() { + nsPortLimit.innerHTML = this.value; + Settings.MaxPortCapacity = this.value; + }; + + document.getElementById("settingsSuppressMessages").onclick = function() { + Settings.SuppressMessages = this.checked; + }; + + document.getElementById("settingsSuppressFactionInvites").onclick = function() { + Settings.SuppressFactionInvites = this.checked; + }; +} + + + + /***/ }), /* 16 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -20853,17 +20853,19 @@ function initCreateProgramButtons() { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AllServersMap; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__InteractiveTutorial_js__ = __webpack_require__(27); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__ = __webpack_require__(19); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__InteractiveTutorial_js__ = __webpack_require__(26); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__ = __webpack_require__(22); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Settings_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Settings_js__ = __webpack_require__(15); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_JSONReviver_js__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__ = __webpack_require__(4); -var ace = __webpack_require__(55); +var ace = __webpack_require__(53); +__webpack_require__(55); +__webpack_require__(56); __webpack_require__(57); __webpack_require__(58); __webpack_require__(59); @@ -20875,8 +20877,6 @@ __webpack_require__(64); __webpack_require__(65); __webpack_require__(66); __webpack_require__(67); -__webpack_require__(68); -__webpack_require__(69); @@ -21514,6 +21514,105 @@ __WEBPACK_IMPORTED_MODULE_9__utils_JSONReviver_js__["c" /* Reviver */].construct /* 17 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return yesNoBoxCreate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return yesNoTxtInpBoxCreate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return yesNoBoxGetYesButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return yesNoBoxGetNoButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return yesNoTxtInpBoxGetYesButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return yesNoTxtInpBoxGetNoButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return yesNoTxtInpBoxGetInput; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return yesNoBoxClose; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return yesNoTxtInpBoxClose; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return yesNoBoxOpen; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__ = __webpack_require__(2); + +/* Generic Yes-No Pop-up box + * Can be used to create pop-up boxes that require a yes/no response from player + */ +var yesNoBoxOpen = false; +function yesNoBoxClose() { + var container = document.getElementById("yes-no-box-container"); + if (container) { + container.style.display = "none"; + } else { + console.log("ERROR: Container not found for YesNoBox"); + } + yesNoBoxOpen = false; +} + +function yesNoBoxGetYesButton() { + return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-box-yes"); +} + +function yesNoBoxGetNoButton() { + return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-box-no"); +} + +function yesNoBoxCreate(txt) { + if (yesNoBoxOpen) {return false;} //Already open + yesNoBoxOpen = true; + var textElement = document.getElementById("yes-no-box-text"); + if (textElement) { + textElement.innerHTML = txt; + } + + var c = document.getElementById("yes-no-box-container"); + if (c) { + c.style.display = "block"; + } else { + console.log("ERROR: Container not found for YesNoBox"); + } + return true; +} + +/* Generic Yes-No POp-up Box with Text input */ +function yesNoTxtInpBoxClose() { + var c = document.getElementById("yes-no-text-input-box-container"); + if (c) { + c.style.display = "none"; + } else { + console.log("ERROR: Container not found for YesNoTextInputBox"); + } + yesNoBoxOpen = false; +} + +function yesNoTxtInpBoxGetYesButton() { + return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-text-input-box-yes"); +} + +function yesNoTxtInpBoxGetNoButton() { + return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-text-input-box-no"); +} + +function yesNoTxtInpBoxGetInput() { + var val = document.getElementById("yes-no-text-input-box-input").value; + val = val.replace(/\s+/g, ''); + return val; +} + +function yesNoTxtInpBoxCreate(txt) { + yesNoBoxOpen = true; + var txtE = document.getElementById("yes-no-text-input-box-text"); + if (txtE) { + txtE.innerHTML = txt; + } + + var c = document.getElementById("yes-no-text-input-box-container"); + if (c) { + c.style.display = "block"; + } else { + console.log("ERROR: Container not found for YesNoTextInputBox"); + } +} + + + + +/***/ }), +/* 18 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createRandomIp; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ipExists; }); @@ -21565,7 +21664,7 @@ function isValidIPAddress(ipaddress) { /***/ }), -/* 18 */ +/* 19 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! @preserve @@ -21581,2407 +21680,6 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! @preserve __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):"object"==typeof module&&module.exports?module.exports=b():a.numeral=b()}(this,function(){function a(a,b){this._input=a,this._value=b}var b,c,d="2.0.6",e={},f={},g={currentLocale:"en",zeroFormat:null,nullFormat:null,defaultFormat:"0,0",scalePercentBy100:!0},h={currentLocale:g.currentLocale,zeroFormat:g.zeroFormat,nullFormat:g.nullFormat,defaultFormat:g.defaultFormat,scalePercentBy100:g.scalePercentBy100};return b=function(d){var f,g,i,j;if(b.isNumeral(d))f=d.value();else if(0===d||"undefined"==typeof d)f=0;else if(null===d||c.isNaN(d))f=null;else if("string"==typeof d)if(h.zeroFormat&&d===h.zeroFormat)f=0;else if(h.nullFormat&&d===h.nullFormat||!d.replace(/[^0-9]+/g,"").length)f=null;else{for(g in e)if(j="function"==typeof e[g].regexps.unformat?e[g].regexps.unformat():e[g].regexps.unformat,j&&d.match(j)){i=e[g].unformat;break}i=i||b._.stringToNumber,f=i(d)}else f=Number(d)||null;return new a(d,f)},b.version=d,b.isNumeral=function(b){return b instanceof a},b._=c={numberToFormat:function(a,c,d){var e,g,h,i,j,k,l,m=f[b.options.currentLocale],n=!1,o=!1,p=0,q="",r=1e12,s=1e9,t=1e6,u=1e3,v="",w=!1;if(a=a||0,g=Math.abs(a),b._.includes(c,"(")?(n=!0,c=c.replace(/[\(|\)]/g,"")):(b._.includes(c,"+")||b._.includes(c,"-"))&&(j=b._.includes(c,"+")?c.indexOf("+"):0>a?c.indexOf("-"):-1,c=c.replace(/[\+|\-]/g,"")),b._.includes(c,"a")&&(e=c.match(/a(k|m|b|t)?/),e=e?e[1]:!1,b._.includes(c," a")&&(q=" "),c=c.replace(new RegExp(q+"a[kmbt]?"),""),g>=r&&!e||"t"===e?(q+=m.abbreviations.trillion,a/=r):r>g&&g>=s&&!e||"b"===e?(q+=m.abbreviations.billion,a/=s):s>g&&g>=t&&!e||"m"===e?(q+=m.abbreviations.million,a/=t):(t>g&&g>=u&&!e||"k"===e)&&(q+=m.abbreviations.thousand,a/=u)),b._.includes(c,"[.]")&&(o=!0,c=c.replace("[.]",".")),h=a.toString().split(".")[0],i=c.split(".")[1],k=c.indexOf(","),p=(c.split(".")[0].split(",")[0].match(/0/g)||[]).length,i?(b._.includes(i,"[")?(i=i.replace("]",""),i=i.split("["),v=b._.toFixed(a,i[0].length+i[1].length,d,i[1].length)):v=b._.toFixed(a,i.length,d),h=v.split(".")[0],v=b._.includes(v,".")?m.delimiters.decimal+v.split(".")[1]:"",o&&0===Number(v.slice(1))&&(v="")):h=b._.toFixed(a,0,d),q&&!e&&Number(h)>=1e3&&q!==m.abbreviations.trillion)switch(h=String(Number(h)/1e3),q){case m.abbreviations.thousand:q=m.abbreviations.million;break;case m.abbreviations.million:q=m.abbreviations.billion;break;case m.abbreviations.billion:q=m.abbreviations.trillion}if(b._.includes(h,"-")&&(h=h.slice(1),w=!0),h.length0;x--)h="0"+h;return k>-1&&(h=h.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+m.delimiters.thousands)),0===c.indexOf(".")&&(h=""),l=h+v+(q?q:""),n?l=(n&&w?"(":"")+l+(n&&w?")":""):j>=0?l=0===j?(w?"-":"+")+l:l+(w?"-":"+"):w&&(l="-"+l),l},stringToNumber:function(a){var b,c,d,e=f[h.currentLocale],g=a,i={thousand:3,million:6,billion:9,trillion:12};if(h.zeroFormat&&a===h.zeroFormat)c=0;else if(h.nullFormat&&a===h.nullFormat||!a.replace(/[^0-9]+/g,"").length)c=null;else{c=1,"."!==e.delimiters.decimal&&(a=a.replace(/\./g,"").replace(e.delimiters.decimal,"."));for(b in i)if(d=new RegExp("[^a-zA-Z]"+e.abbreviations[b]+"(?:\\)|(\\"+e.currency.symbol+")?(?:\\))?)?$"),g.match(d)){c*=Math.pow(10,i[b]);break}c*=(a.split("-").length+Math.min(a.split("(").length-1,a.split(")").length-1))%2?1:-1,a=a.replace(/[^0-9\.]+/g,""),c*=Number(a)}return c},isNaN:function(a){return"number"==typeof a&&isNaN(a)},includes:function(a,b){return-1!==a.indexOf(b)},insert:function(a,b,c){return a.slice(0,c)+b+a.slice(c)},reduce:function(a,b){if(null===this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof b)throw new TypeError(b+" is not a function");var c,d=Object(a),e=d.length>>>0,f=0;if(3===arguments.length)c=arguments[2];else{for(;e>f&&!(f in d);)f++;if(f>=e)throw new TypeError("Reduce of empty array with no initial value");c=d[f++]}for(;e>f;f++)f in d&&(c=b(c,d[f],f,d));return c},multiplier:function(a){var b=a.toString().split(".");return b.length<2?1:Math.pow(10,b[1].length)},correctionFactor:function(){var a=Array.prototype.slice.call(arguments);return a.reduce(function(a,b){var d=c.multiplier(b);return a>d?a:d},1)},toFixed:function(a,b,c,d){var e,f,g,h,i=a.toString().split("."),j=b-(d||0);return e=2===i.length?Math.min(Math.max(i[1].length,j),b):j,g=Math.pow(10,e),h=(c(a+"e+"+e)/g).toFixed(e),d>b-e&&(f=new RegExp("\\.?0{1,"+(d-(b-e))+"}$"),h=h.replace(f,"")),h}},b.options=h,b.formats=e,b.locales=f,b.locale=function(a){return a&&(h.currentLocale=a.toLowerCase()),h.currentLocale},b.localeData=function(a){if(!a)return f[h.currentLocale];if(a=a.toLowerCase(),!f[a])throw new Error("Unknown locale : "+a);return f[a]},b.reset=function(){for(var a in g)h[a]=g[a]},b.zeroFormat=function(a){h.zeroFormat="string"==typeof a?a:null},b.nullFormat=function(a){h.nullFormat="string"==typeof a?a:null},b.defaultFormat=function(a){h.defaultFormat="string"==typeof a?a:"0.0"},b.register=function(a,b,c){if(b=b.toLowerCase(),this[a+"s"][b])throw new TypeError(b+" "+a+" already registered.");return this[a+"s"][b]=c,c},b.validate=function(a,c){var d,e,f,g,h,i,j,k;if("string"!=typeof a&&(a+="",console.warn&&console.warn("Numeral.js: Value is not string. It has been co-erced to: ",a)),a=a.trim(),a.match(/^\d+$/))return!0;if(""===a)return!1;try{j=b.localeData(c)}catch(l){j=b.localeData(b.locale())}return f=j.currency.symbol,h=j.abbreviations,d=j.delimiters.decimal,e="."===j.delimiters.thousands?"\\.":j.delimiters.thousands,k=a.match(/^[^\d]+/),null!==k&&(a=a.substr(1),k[0]!==f)?!1:(k=a.match(/[^\d]+$/),null!==k&&(a=a.slice(0,-1),k[0]!==h.thousand&&k[0]!==h.million&&k[0]!==h.billion&&k[0]!==h.trillion)?!1:(i=new RegExp(e+"{2}"),a.match(/[^\d.,]/g)?!1:(g=a.split(d),g.length>2?!1:g.length<2?!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i):1===g[0].length?!!g[0].match(/^\d+$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/):!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/))))},b.fn=a.prototype={clone:function(){return b(this)},format:function(a,c){var d,f,g,i=this._value,j=a||h.defaultFormat;if(c=c||Math.round,0===i&&null!==h.zeroFormat)f=h.zeroFormat;else if(null===i&&null!==h.nullFormat)f=h.nullFormat;else{for(d in e)if(j.match(e[d].regexps.format)){g=e[d].format;break}g=g||b._.numberToFormat,f=g(i,j,c)}return f},value:function(){return this._value},input:function(){return this._input},set:function(a){return this._value=Number(a),this},add:function(a){function b(a,b,c,e){return a+Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([this._value,a],b,0)/d,this},subtract:function(a){function b(a,b,c,e){return a-Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([a],b,Math.round(this._value*d))/d,this},multiply:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)*Math.round(b*f)/Math.round(f*f)}return this._value=c.reduce([this._value,a],b,1),this},divide:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)/Math.round(b*f)}return this._value=c.reduce([this._value,a],b),this},difference:function(a){return Math.abs(b(this._value).subtract(a).value())}},b.register("locale","en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th"},currency:{symbol:"$"}}),function(){b.register("format","bps",{regexps:{format:/(BPS)/,unformat:/(BPS)/},format:function(a,c,d){var e,f=b._.includes(c," BPS")?" ":"";return a=1e4*a,c=c.replace(/\s?BPS/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"BPS"),e=e.join("")):e=e+f+"BPS",e},unformat:function(a){return+(1e-4*b._.stringToNumber(a)).toFixed(15)}})}(),function(){var a={base:1e3,suffixes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"]},c={base:1024,suffixes:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]},d=a.suffixes.concat(c.suffixes.filter(function(b){return a.suffixes.indexOf(b)<0})),e=d.join("|");e="("+e.replace("B","B(?!PS)")+")",b.register("format","bytes",{regexps:{format:/([0\s]i?b)/,unformat:new RegExp(e)},format:function(d,e,f){var g,h,i,j,k=b._.includes(e,"ib")?c:a,l=b._.includes(e," b")||b._.includes(e," ib")?" ":"";for(e=e.replace(/\s?i?b/,""),h=0;h<=k.suffixes.length;h++)if(i=Math.pow(k.base,h),j=Math.pow(k.base,h+1),null===d||0===d||d>=i&&j>d){l+=k.suffixes[h],i>0&&(d/=i);break}return g=b._.numberToFormat(d,e,f),g+l},unformat:function(d){var e,f,g=b._.stringToNumber(d);if(g){for(e=a.suffixes.length-1;e>=0;e--){if(b._.includes(d,a.suffixes[e])){f=Math.pow(a.base,e);break}if(b._.includes(d,c.suffixes[e])){f=Math.pow(c.base,e);break}}g*=f||1}return g}})}(),function(){b.register("format","currency",{regexps:{format:/(\$)/},format:function(a,c,d){var e,f,g,h=b.locales[b.options.currentLocale],i={before:c.match(/^([\+|\-|\(|\s|\$]*)/)[0],after:c.match(/([\+|\-|\)|\s|\$]*)$/)[0]};for(c=c.replace(/\s?\$\s?/,""),e=b._.numberToFormat(a,c,d),a>=0?(i.before=i.before.replace(/[\-\(]/,""),i.after=i.after.replace(/[\-\)]/,"")):0>a&&!b._.includes(i.before,"-")&&!b._.includes(i.before,"(")&&(i.before="-"+i.before),g=0;g=0;g--)switch(f=i.after[g]){case"$":e=g===i.after.length-1?e+h.currency.symbol:b._.insert(e,h.currency.symbol,-(i.after.length-(1+g)));break;case" ":e=g===i.after.length-1?e+" ":b._.insert(e," ",-(i.after.length-(1+g)+h.currency.symbol.length-1))}return e}})}(),function(){b.register("format","exponential",{regexps:{format:/(e\+|e-)/,unformat:/(e\+|e-)/},format:function(a,c,d){var e,f="number"!=typeof a||b._.isNaN(a)?"0e+0":a.toExponential(),g=f.split("e");return c=c.replace(/e[\+|\-]{1}0/,""),e=b._.numberToFormat(Number(g[0]),c,d),e+"e"+g[1]},unformat:function(a){function c(a,c,d,e){var f=b._.correctionFactor(a,c),g=a*f*(c*f)/(f*f);return g}var d=b._.includes(a,"e+")?a.split("e+"):a.split("e-"),e=Number(d[0]),f=Number(d[1]);return f=b._.includes(a,"e-")?f*=-1:f,b._.reduce([e,Math.pow(10,f)],c,1)}})}(),function(){b.register("format","ordinal",{regexps:{format:/(o)/},format:function(a,c,d){var e,f=b.locales[b.options.currentLocale],g=b._.includes(c," o")?" ":"";return c=c.replace(/\s?o/,""),g+=f.ordinal(a),e=b._.numberToFormat(a,c,d),e+g}})}(),function(){b.register("format","percentage",{regexps:{format:/(%)/,unformat:/(%)/},format:function(a,c,d){var e,f=b._.includes(c," %")?" ":"";return b.options.scalePercentBy100&&(a=100*a),c=c.replace(/\s?\%/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"%"),e=e.join("")):e=e+f+"%",e},unformat:function(a){var c=b._.stringToNumber(a);return b.options.scalePercentBy100?.01*c:c}})}(),function(){b.register("format","time",{regexps:{format:/(:)/,unformat:/(:)/},format:function(a,b,c){var d=Math.floor(a/60/60),e=Math.floor((a-60*d*60)/60),f=Math.round(a-60*d*60-60*e);return d+":"+(10>e?"0"+e:e)+":"+(10>f?"0"+f:f)},unformat:function(a){var b=a.split(":"),c=0;return 3===b.length?(c+=60*Number(b[0])*60,c+=60*Number(b[1]),c+=Number(b[2])):2===b.length&&(c+=60*Number(b[0]),c+=Number(b[1])),Number(c)}})}(),b}); -/***/ }), -/* 19 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptFunctions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return initSingularitySFFlags; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return hasSingularitySF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return hasBn11SF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return hasWallStreetSF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return wallStreetSFLvl; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(25); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__ = __webpack_require__(20); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__BitNode_js__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Crimes_js__ = __webpack_require__(32); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Company_js__ = __webpack_require__(21); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__ = __webpack_require__(15); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__ = __webpack_require__(45); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Faction_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__HacknetNode_js__ = __webpack_require__(39); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Location_js__ = __webpack_require__(13); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Message_js__ = __webpack_require__(24); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__Missions_js__ = __webpack_require__(26); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__Script_js__ = __webpack_require__(16); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__Settings_js__ = __webpack_require__(14); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__ = __webpack_require__(29); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__Terminal_js__ = __webpack_require__(23); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__TextFile_js__ = __webpack_require__(49); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__ = __webpack_require__(38); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__NetscriptEnvironment_js__ = __webpack_require__(31); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__utils_decimal_js__ = __webpack_require__(28); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_25__utils_decimal_js__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__utils_IPAddress_js__ = __webpack_require__(17); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__ = __webpack_require__(22); -var sprintf = __webpack_require__(41).sprintf, - vsprintf = __webpack_require__(41).vsprintf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var hasSingularitySF=false, hasAISF=false, hasBn11SF=false, hasWallStreetSF=false; -var singularitySFLvl=1, wallStreetSFLvl=1; - -//Used to check and set flags for every Source File, despite the name of the function -function initSingularitySFFlags() { - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles.length; ++i) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 4) { - hasSingularitySF = true; - singularitySFLvl = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].lvl; - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 5) { - hasAISF = true; - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 8) { - hasWallStreetSF = true; - wallStreetSFLvl = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].lvl; - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 11) { - hasBn11SF = true; - } - } -} - -function NetscriptFunctions(workerScript) { - return { - Math : Math, - Date : Date, - hacknetnodes : __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacknetNodes, - sprintf : sprintf, - vsprintf: vsprintf, - scan : function(ip=workerScript.serverIp, hostnames=true){ - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, 'Invalid IP or hostname passed into scan() command'); - } - var out = []; - for (var i = 0; i < server.serversOnNetwork.length; i++) { - var entry; - if (hostnames) { - entry = server.getServerOnNetwork(i).hostname; - } else { - entry = server.getServerOnNetwork(i).ip; - } - if (entry == null) { - continue; - } - out.push(entry); - } - workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname); - return out; - }, - hack : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument"); - } - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); - } - - //Calculate the hacking time - var hackingTime = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["j" /* scriptCalculateHackingTime */])(server); //This is in seconds - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access"); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access"); - } - - if (server.requiredHackingSkill > __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill) { - workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); - } - - workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")"); - //console.log("Hacking " + server.hostname + " after " + hackingTime.toString() + " seconds (t=" + threads + ")"); - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(hackingTime* 1000, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - var hackChance = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["i" /* scriptCalculateHackingChance */])(server); - var rand = Math.random(); - var expGainedOnSuccess = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["g" /* scriptCalculateExpGain */])(server) * threads; - var expGainedOnFailure = (expGainedOnSuccess / 4); - if (rand < hackChance) { //Success! - var moneyGained = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["k" /* scriptCalculatePercentMoneyHacked */])(server); - moneyGained = Math.floor(server.moneyAvailable * moneyGained) * threads; - - //Over-the-top safety checks - if (moneyGained <= 0) { - moneyGained = 0; - expGainedOnSuccess = expGainedOnFailure; - } - if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;} - server.moneyAvailable -= moneyGained; - if (server.moneyAvailable < 0) {server.moneyAvailable = 0;} - - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainMoney(moneyGained); - workerScript.scriptRef.onlineMoneyMade += moneyGained; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].scriptProdSinceLastAug += moneyGained; - workerScript.scriptRef.recordHack(server.ip, moneyGained, threads); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGainedOnSuccess); - workerScript.scriptRef.onlineExpGained += expGainedOnSuccess; - //console.log("Script successfully hacked " + server.hostname + " for $" + formatNumber(moneyGained, 2) + " and " + formatNumber(expGainedOnSuccess, 4) + " exp"); - workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(moneyGained, 2) + " and " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")"); - server.fortify(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ServerFortifyAmount * threads); - return Promise.resolve(true); - } else { - //Player only gains 25% exp for failure? TODO Can change this later to balance - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGainedOnFailure); - workerScript.scriptRef.onlineExpGained += expGainedOnFailure; - //console.log("Script unsuccessful to hack " + server.hostname + ". Gained " + formatNumber(expGainedOnFailure, 4) + " exp"); - workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnFailure, 4) + " exp (t=" + threads + ")"); - return Promise.resolve(false); - } - }); - }, - sleep : function(time,log=true){ - if (time === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument"); - } - if (log) { - workerScript.scriptRef.log("Sleeping for " + time + " milliseconds"); - } - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(time, workerScript).then(function() { - return Promise.resolve(true); - }); - }, - grow : function(ip){ - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip); - } - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access"); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access"); - } - - var growTime = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["h" /* scriptCalculateGrowTime */])(server); - //console.log("Executing grow() on server " + server.hostname + " in " + formatNumber(growTime/1000, 3) + " seconds") - workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(growTime/1000, 3) + " seconds (t=" + threads + ")"); - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(growTime, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - server.moneyAvailable += (1 * threads); //It can be grown even if it has no money - var growthPercentage = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["j" /* processSingleServerGrowth */])(server, 450 * threads); - workerScript.scriptRef.recordGrow(server.ip, threads); - var expGain = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["g" /* scriptCalculateExpGain */])(server) * threads; - if (growthPercentage == 1) { - expGain = 0; - } - workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " - + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(growthPercentage*100 - 100, 6) + "%. Gained " + - Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGain, 4) + " hacking exp (t=" + threads +")"); - workerScript.scriptRef.onlineExpGained += expGain; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGain); - return Promise.resolve(growthPercentage); - }); - }, - weaken : function(ip){ - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip); - } - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access"); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access"); - } - - var weakenTime = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["l" /* scriptCalculateWeakenTime */])(server); - workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " + - Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(weakenTime/1000, 3) + " seconds (t=" + threads + ")"); - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(weakenTime, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - server.weaken(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ServerWeakenAmount * threads); - workerScript.scriptRef.recordWeaken(server.ip, threads); - var expGain = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["g" /* scriptCalculateExpGain */])(server) * threads; - workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty + - ". Gained " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGain, 4) + " hacking exp (t=" + threads + ")"); - workerScript.scriptRef.onlineExpGained += expGain; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGain); - return Promise.resolve(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ServerWeakenAmount * threads); - }); - }, - print : function(args){ - if (args === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument"); - } - workerScript.scriptRef.log(args.toString()); - }, - tprint : function(args) { - if (args === undefined || args == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument"); - } - var x = args.toString(); - if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["d" /* isHTML */])(x)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].takeDamage(1); - Object(__WEBPACK_IMPORTED_MODULE_26__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You suddenly feel a sharp shooting pain through your body as an angry voice in your head exclaims:

" + - "DON'T USE TPRINT() TO OUTPUT HTML ELEMENTS TO YOUR TERMINAL!!!!

" + - "(You lost 1 HP)"); - return; - } - Object(__WEBPACK_IMPORTED_MODULE_20__Terminal_js__["b" /* post */])(workerScript.scriptRef.filename + ": " + args.toString()); - }, - clearLog : function() { - workerScript.scriptRef.clearLog(); - }, - nuke : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - } - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].NukeProgram)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the NUKE.exe virus!"); - } - if (server.openPortCount < server.numOpenPortsRequired) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Not enough ports opened to use NUKE.exe virus"); - } - if (server.hasAdminRights) { - workerScript.scriptRef.log("Already have root access to " + server.hostname); - } else { - server.hasAdminRights = true; - workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access"); - } - return true; - }, - brutessh : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - } - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram)) { - workerScript.scriptRef.log("You do not have the BruteSSH.exe program!"); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the BruteSSH.exe program!"); - } - if (!server.sshPortOpen) { - workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)"); - server.sshPortOpen = true; - ++server.openPortCount; - } else { - workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname); - } - return true; - }, - ftpcrack : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - } - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the FTPCrack.exe program!"); - } - if (!server.ftpPortOpen) { - workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)"); - server.ftpPortOpen = true; - ++server.openPortCount; - } else { - workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname); - } - return true; - }, - relaysmtp : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - } - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the relaySMTP.exe program!"); - } - if (!server.smtpPortOpen) { - workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)"); - server.smtpPortOpen = true; - ++server.openPortCount; - } else { - workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname); - } - return true; - }, - httpworm : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - } - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the HTTPWorm.exe program!"); - } - if (!server.httpPortOpen) { - workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)"); - server.httpPortOpen = true; - ++server.openPortCount; - } else { - workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname); - } - return true; - }, - sqlinject : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - } - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the SQLInject.exe program!"); - } - if (!server.sqlPortOpen) { - workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)"); - server.sqlPortOpen = true; - ++server.openPortCount; - } else { - workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname); - } - return true; - }, - run : function(scriptname,threads = 1){ - if (scriptname === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var scriptServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["f" /* runScriptFromScript */])(scriptServer, scriptname, argsForNewScript, workerScript, threads); - }, - exec : function(scriptname,ip,threads = 1){ - if (scriptname === undefined || ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 3; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip); - } - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["f" /* runScriptFromScript */])(server, scriptname, argsForNewScript, workerScript, threads); - }, - kill : function(filename,ip){ - if (filename === undefined || ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForKillTarget = []; - for (var i = 2; i < arguments.length; ++i) { - argsForKillTarget.push(arguments[i]); - } - var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(filename, argsForKillTarget, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget)); - return false; - } - var res = Object(__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["d" /* killWorkerScript */])(runningScriptObj, server.ip); - if (res) { - workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die..."); - return true; - } else { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget)); - return false; - } - }, - killall : function(ip){ - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = server.runningScripts.length-1; i >= 0; --i) { - Object(__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["d" /* killWorkerScript */])(server.runningScripts[i], server.ip); - } - workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die"); - return true; - }, - scp : function(scriptname, ip1, ip2){ - if (arguments.length !== 2 && arguments.length !== 3) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - if (scriptname && scriptname.constructor === Array) { - //Recursively call scp on all elements of array - var res = false; - scriptname.forEach(function(script) { - if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) { - res = true; - }; - }); - return res; - } - if (!scriptname.endsWith(".lit") && !scriptname.endsWith(".script")) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() only works for .script and .lit files"); - } - - var destServer, currServ; - - if (arguments.length === 3) { //scriptname, source, destination - if (scriptname === undefined || ip1 === undefined || ip2 === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip2); - if (destServer == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); - } - - currServ = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip1); - if (currServ == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); - } - } else if (arguments.length === 2) { //scriptname, destination - if (scriptname === undefined || ip1 === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip1); - if (destServer == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); - } - - currServ = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); - if (currServ == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); - } - } - - //Scp for lit files - if (scriptname.endsWith(".lit")) { - var found = false; - for (var i = 0; i < currServ.messages.length; ++i) { - if (!(currServ.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) && currServ.messages[i] == scriptname) { - found = true; - } - } - - if (!found) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - for (var i = 0; i < destServer.messages.length; ++i) { - if (destServer.messages[i] === scriptname) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - return true; //Already exists - } - } - destServer.messages.push(scriptname); - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - return true; - } - - //Scp for script files - var sourceScript = null; - for (var i = 0; i < currServ.scripts.length; ++i) { - if (scriptname == currServ.scripts[i].filename) { - sourceScript = currServ.scripts[i]; - break; - } - } - if (sourceScript == null) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - //Overwrite script if it already exists - for (var i = 0; i < destServer.scripts.length; ++i) { - if (scriptname == destServer.scripts[i].filename) { - workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten."); - workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname); - var oldScript = destServer.scripts[i]; - oldScript.code = sourceScript.code; - oldScript.ramUsage = sourceScript.ramUsage; - return true; - } - } - - //Create new script if it does not already exist - var newScript = new __WEBPACK_IMPORTED_MODULE_15__Script_js__["c" /* Script */](); - newScript.filename = scriptname; - newScript.code = sourceScript.code; - newScript.ramUsage = sourceScript.ramUsage; - newScript.server = destServer.ip; - destServer.scripts.push(newScript); - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - return true; - }, - ls : function(ip, grep) { - if (ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip); - } - - //Get the grep filter, if one exists - var filter = false; - if (arguments.length >= 2) { - filter = grep.toString(); - } - - var allFiles = []; - for (var i = 0; i < server.programs.length; i++) { - if (filter) { - if (server.programs[i].includes(filter)) { - allFiles.push(server.programs[i]); - } - } else { - allFiles.push(server.programs[i]); - } - } - for (var i = 0; i < server.scripts.length; i++) { - if (filter) { - if (server.scripts[i].filename.includes(filter)) { - allFiles.push(server.scripts[i].filename); - } - } else { - allFiles.push(server.scripts[i].filename); - } - - } - for (var i = 0; i < server.messages.length; i++) { - if (filter) { - if (server.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) { - if (server.messages[i].filename.includes(filter)) { - allFiles.push(server.messages[i].filename); - } - } else if (server.messages[i].includes(filter)) { - allFiles.push(server.messages[i]); - } - } else { - if (server.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) { - allFiles.push(server.messages[i].filename); - } else { - allFiles.push(server.messages[i]); - } - } - } - - //Sort the files alphabetically then print each - allFiles.sort(); - return allFiles; - }, - hasRootAccess : function(ip){ - if (ip===undefined){ - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null){ - workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - } - return server.hasAdminRights; - }, - getIp : function() { - var scriptServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.ip; - }, - getHostname : function(){ - var scriptServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.hostname; - }, - getHackingLevel : function(){ - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].updateSkillLevels(); - workerScript.scriptRef.log("getHackingLevel() returned " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill); - return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill; - }, - getHackingMultipliers : function() { - return { - chance: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_chance_mult, - speed: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_speed_mult, - money: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_money_mult, - growth: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_grow_mult, - }; - }, - getBitNodeMultipliers: function() { - if (!hasAISF) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run."); - } - return __WEBPACK_IMPORTED_MODULE_2__BitNode_js__["a" /* BitNodeMultipliers */]; - }, - getServerMoneyAvailable : function(ip){ - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - } - if (server.hostname == "home") { - //Return player's money - workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.toNumber(), 2)); - return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.toNumber(); - } - workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.moneyAvailable, 2) + " for " + server.hostname); - return server.moneyAvailable; - }, - getServerSecurityLevel : function(ip){ - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.hackDifficulty, 3) + " for " + server.hostname); - return server.hackDifficulty; - }, - getServerBaseSecurityLevel : function(ip){ - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.baseDifficulty, 3) + " for " + server.hostname); - return server.baseDifficulty; - }, - getServerMinSecurityLevel : function(ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.minDifficulty, 3) + " for " + server.hostname); - return server.minDifficulty; - }, - getServerRequiredHackingLevel : function(ip){ - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.requiredHackingSkill, 0) + " for " + server.hostname); - return server.requiredHackingSkill; - }, - getServerMaxMoney : function(ip){ - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.moneyMax, 0) + " for " + server.hostname); - return server.moneyMax; - }, - getServerGrowth : function(ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerGrowth() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.serverGrowth, 0) + " for " + server.hostname); - return server.serverGrowth; - }, - getServerNumPortsRequired : function(ip){ - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.numOpenPortsRequired, 0) + " for " + server.hostname); - return server.numOpenPortsRequired; - }, - getServerRam : function(ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip); - } - workerScript.scriptRef.log("getServerRam() returned [" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.maxRam, 2) + "GB, " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.ramUsed, 2) + "GB]"); - return [server.maxRam, server.ramUsed]; - }, - serverExists : function(ip) { - return (Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip) !== null); - }, - fileExists : function(filename,ip=workerScript.serverIp){ - if (filename === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (filename == server.scripts[i].filename) { - return true; - } - } - for (var i = 0; i < server.programs.length; ++i) { - if (filename.toLowerCase() == server.programs[i].toLowerCase()) { - return true; - } - } - for (var i = 0; i < server.messages.length; ++i) { - if (!(server.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) && - filename.toLowerCase() === server.messages[i]) { - return true; - } - } - return false; - }, - isRunning : function(filename,ip){ - if (filename === undefined || ip === undefined) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForTargetScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForTargetScript.push(arguments[i]); - } - return (Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(filename, argsForTargetScript, server) != null); - }, - getNextHacknetNodeCost : __WEBPACK_IMPORTED_MODULE_10__HacknetNode_js__["b" /* getCostOfNextHacknetNode */], - purchaseHacknetNode : __WEBPACK_IMPORTED_MODULE_10__HacknetNode_js__["d" /* purchaseHacknet */], - getStockPrice : function(symbol) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()"); - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()"); - } - return parseFloat(stock.price.toFixed(3)); - }, - getStockPosition : function(symbol) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()"); - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()"); - } - return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx]; - }, - buyStock : function(symbol, shares) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use buyStock()"); - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into buyStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to buyStock()"); - return false; - } - shares = Math.round(shares); - if (shares === 0) {return false;} - - var totalPrice = stock.price * shares; - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) { - workerScript.scriptRef.log("Not enough money to purchase " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + - symbol + ". Need $" + - Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2).toString()); - return false; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - if (__WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].Page.StockMarket) { - Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["p" /* updateStockPlayerPosition */])(stock); - } - workerScript.scriptRef.log("Bought " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share"); - return true; - }, - sellStock : function(symbol, shares) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use sellStock()"); - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into sellStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to sellStock()"); - return false; - } - shares = Math.round(shares); - if (shares > stock.playerShares) {shares = stock.playerShares;} - if (shares === 0) {return false;} - var gains = stock.price * shares - __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainMoney(gains); - - //Calculate net profit and add to script stats - var netProfit = ((stock.price - stock.playerAvgPx) * shares) - __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; - if (isNaN(netProfit)) {netProfit = 0;} - workerScript.scriptRef.onlineMoneyMade += netProfit; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].scriptProdSinceLastAug += netProfit; - - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - if (__WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].Page.StockMarket) { - Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["p" /* updateStockPlayerPosition */])(stock); - } - workerScript.scriptRef.log("Sold " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. Gained " + - "$" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gains, 2)); - return true; - }, - shortStock(symbol, shares) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use shortStock()"); - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()"); - } - return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["n" /* shortStock */])(stock, shares, workerScript); - }, - sellShort(symbol, shares) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use sellShort()"); - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()"); - } - return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["l" /* sellShort */])(stock, shares, workerScript); - }, - placeOrder(symbol, shares, price, type, pos) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()"); - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].StopSell; - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Long; - } else if (pos.includes('s')) { - orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Short; - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - - return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["k" /* placeOrder */])(stock, shares, price, orderType, orderPos, workerScript); - }, - cancelOrder(symbol, shares, price, type, pos) { - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()"); - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; - if (stock == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()"); - } - if (isNaN(shares) || isNaN(price)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = OrderType.StopSell; - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Long; - } else if (pos.includes('s')) { - orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Short; - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - params = { - stock: stock, - shares: shares, - price: price, - type: orderType, - pos: orderPos - }; - return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["e" /* cancelOrder */])(params, workerScript); - }, - purchaseServer : function(hostname, ram) { - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s\s+/g, ''); - if (hostnameStr == "") { - workerScript.scriptRef.log("Error: Passed empty string for hostname argument of purchaseServer()"); - return ""; - } - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.length >= __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit) { - workerScript.scriptRef.log("Error: You have reached the maximum limit of " + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit + - " servers. You cannot purchase any more."); - return ""; - } - - ram = Math.round(ram); - if (isNaN(ram) || !Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["e" /* powerOfTwo */])(ram)) { - workerScript.scriptRef.log("Error: Invalid ram argument passed to purchaseServer(). Must be numeric and a power of 2"); - return ""; - } - - var cost = ram * __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer; - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(cost)) { - workerScript.scriptRef.log("Error: Not enough money to purchase server. Need $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2)); - return ""; - } - var newServ = new __WEBPACK_IMPORTED_MODULE_16__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_28__utils_IPAddress_js__["a" /* createRandomIp */])(), hostnameStr, "", false, true, true, ram); - Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["a" /* AddToAllServers */])(newServ); - - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.push(newServ.ip); - var homeComputer = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer(); - homeComputer.serversOnNetwork.push(newServ.ip); - newServ.serversOnNetwork.push(homeComputer.ip); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(cost); - workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2)); - return newServ.hostname; - }, - deleteServer : function(hostname) { - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s\s+/g, ''); - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["c" /* GetServerByHostname */])(hostnameStr); - if (server == null) { - workerScript.scriptRef.log("Error: Could not find server with hostname " + hostnameStr + ". deleteServer() failed"); - return false; - } - - if (!server.purchasedByPlayer || server.hostname == "home") { - workerScript.scriptRef.log("Error: Server " + server.hostname + " is not a purchased server. " + - "Cannot be deleted. deleteServer failed"); - return false; - } - - var ip = server.ip; - - //A server cannot delete itself - if (ip == workerScript.serverIp) { - workerScript.scriptRef.log("Error: Cannot call deleteServer() on self. Function failed"); - return false; - } - - //Delete all scripts running on server - if (server.runningScripts.length > 0) { - workerScript.scriptRef.log("Error: Cannot delete server " + server.hostname + " because it still has scripts running."); - return false; - } - - //Delete from player's purchasedServers array - var found = false; - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.length; ++i) { - if (ip == __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers[i]) { - found = true; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.splice(i, 1); - break; - } - } - - if (!found) { - workerScript.scriptRef.log("Error: Could not identify server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - } - - //Delete from all servers - delete __WEBPACK_IMPORTED_MODULE_16__Server_js__["b" /* AllServers */][ip]; - - //Delete from home computer - found = false; - var homeComputer = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer(); - for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) { - if (ip == homeComputer.serversOnNetwork[i]) { - homeComputer.serversOnNetwork.splice(i, 1); - workerScript.scriptRef.log("Deleted server " + hostnameStr); - return true; - } - } - //Wasn't found on home computer - workerScript.scriptRef.log("Error: Could not find server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - }, - getPurchasedServers : function(hostname=true) { - var res = []; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.forEach(function(ip) { - if (hostname) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERR: Could not find server in getPurchasedServers(). This is a bug please report to game dev"); - } - res.push(server.hostname); - } else { - res.push(ip); - } - }); - return res; - }, - round : function(n) { - if (isNaN(n)) {return 0;} - return Math.round(n); - }, - write : function(port, data="", mode="a") { - if (!isNaN(port)) { //Write to port - //Port 1-10 - if (port < 1 || port > 10) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Trying to write to invalid port: " + port + ". Only ports 1-10 are valid."); - } - var portName = "Port" + String(port); - var port = __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["a" /* NetscriptPorts */][portName]; - if (port == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); - } - port.push(data); - if (port.length > __WEBPACK_IMPORTED_MODULE_17__Settings_js__["a" /* Settings */].MaxPortCapacity) { - port.shift(); - return true; - } - return false; - } else if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(port)) { //Write to text file - var fn = port; - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); - if (server == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev"); - } - var txtFile = Object(__WEBPACK_IMPORTED_MODULE_21__TextFile_js__["b" /* getTextFile */])(fn, server); - if (txtFile == null) { - txtFile = Object(__WEBPACK_IMPORTED_MODULE_21__TextFile_js__["a" /* createTextFile */])(fn, data, server); - return true; - } - if (mode === "w") { - txtFile.write(data); - } else { - txtFile.append(data); - } - return true; - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument passed in for port: " + port + ". Must be a number between 1 and 10"); - } - }, - read : function(port) { - if (!isNaN(port)) { //Read from port - //Port 1-10 - if (port < 1 || port > 10) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Trying to write to invalid port: " + port + ". Only ports 1-10 are valid."); - } - var portName = "Port" + String(port); - var port = __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["a" /* NetscriptPorts */][portName]; - if (port == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); - } - if (port.length == 0) { - return "NULL PORT DATA"; - } else { - return port.shift(); - } - } else if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(port)) { //Read from text file - var fn = port; - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); - if (server == null) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev"); - } - var txtFile = Object(__WEBPACK_IMPORTED_MODULE_21__TextFile_js__["b" /* getTextFile */])(fn, server); - if (txtFile !== null) { - return txtFile.text; - } else { - return ""; - } - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument passed in for port: " + port + ". Must be a number between 1 and 10"); - } - }, - scriptRunning : function(scriptname, ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - return true; - } - } - return false; - }, - scriptKill : function(scriptname, ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip); - } - var suc = false; - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - Object(__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["d" /* killWorkerScript */])(server.runningScripts[i], server.ip); - suc = true; - } - } - return suc; - }, - getScriptRam : function (scriptname, ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename == scriptname) { - return server.scripts[i].ramUsage; - } - } - return 0; - }, - getHackTime : function(ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["j" /* scriptCalculateHackingTime */])(server); //Returns seconds - }, - getGrowTime : function(ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["h" /* scriptCalculateGrowTime */])(server) / 1000; //Returns seconds - }, - getWeakenTime : function(ip) { - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["l" /* scriptCalculateWeakenTime */])(server) / 1000; //Returns seconds - }, - getScriptIncome : function(scriptname, ip) { - if (arguments.length === 0) { - //Get total script income - var res = []; - res.push(Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["d" /* updateActiveScriptsItems */])()); - res.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].scriptProdSinceLastAug / (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].playtimeSinceLastAug/1000)); - return res; - } else { - //Get income for a particular script - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForScript)); - return -1; - } - return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime; - } - }, - getScriptExpGain : function(scriptname, ip) { - if (arguments.length === 0) { - var total = 0; - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["h" /* workerScripts */].length; ++i) { - total += (__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["h" /* workerScripts */][i].scriptRef.onlineExpGained / __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["h" /* workerScripts */][i].scriptRef.onlineRunningTime); - } - return total; - } else { - //Get income for a particular script - var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForScript)); - return -1; - } - return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime; - } - }, - getTimeSinceLastAug : function() { - return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].playtimeSinceLastAug; - }, - prompt : function(txt) { - if (__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["e" /* yesNoBoxOpen */]) { - workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open"); - return false; - } - if (!Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(txt)) {txt = String(txt);} - var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(), noBtn = Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])(); - yesBtn.innerHTML = "Yes"; - noBtn.innerHTML = "No"; - return new Promise(function(resolve, reject) { - yesBtn.addEventListener("click", ()=>{ - Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); - resolve(true); - }); - noBtn.addEventListener("click", ()=>{ - Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); - resolve(false); - }); - Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])(txt); - }); - }, - - /* Singularity Functions */ - universityCourse : function(universityName, className) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { - workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission."); - return; - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { - var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); - workerScript.scriptRef.log(txt); - } - - var costMult, expMult; - switch(universityName.toLowerCase()) { - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSummitUniversity.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSummitUniversity; - costMult = 4; - expMult = 3; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12RothmanUniversity.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12RothmanUniversity; - costMult = 3; - expMult = 2; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenZBInstituteOfTechnology.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven) { - workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenZBInstituteOfTechnology; - costMult = 5; - expMult = 4; - break; - default: - workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed"); - return false; - } - - var task; - switch(className.toLowerCase()) { - case "Study Computer Science".toLowerCase(): - task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassStudyComputerScience; - break; - case "Data Structures".toLowerCase(): - task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassDataStructures; - break; - case "Networks".toLowerCase(): - task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassNetworks; - break; - case "Algorithms".toLowerCase(): - task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassAlgorithms; - break; - case "Management".toLowerCase(): - task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassManagement; - break; - case "Leadership".toLowerCase(): - task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassLeadership; - break; - default: - workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, task); - workerScript.scriptRef.log("Started " + task + " at " + universityName); - return true; - }, - - gymWorkout : function(gymName, stat) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { - workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission."); - return; - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { - var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); - workerScript.scriptRef.log(txt); - } - var costMult, expMult; - switch(gymName.toLowerCase()) { - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumCrushFitnessGym.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumCrushFitnessGym; - costMult = 2; - expMult = 1.5; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSnapFitnessGym.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSnapFitnessGym; - costMult = 6; - expMult = 4; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12IronGym.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12IronGym; - costMult = 1; - expMult = 1; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12PowerhouseGym.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12PowerhouseGym; - costMult = 10; - expMult = 7.5; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenMilleniumFitnessGym: - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven) { - workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenMilleniumFitnessGym; - costMult = 3; - expMult = 2.5; - break; - default: - workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed"); - return false; - } - - switch(stat.toLowerCase()) { - case "strength".toLowerCase(): - case "str".toLowerCase(): - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymStrength); - break; - case "defense".toLowerCase(): - case "def".toLowerCase(): - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymDefense); - break; - case "dexterity".toLowerCase(): - case "dex".toLowerCase(): - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymDexterity); - break; - case "agility".toLowerCase(): - case "agi".toLowerCase(): - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymAgility); - break; - default: - workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed"); - return false; - } - workerScript.scriptRef.log("Started training " + stat + " at " + gymName); - return true; - }, - - travelToCity(cityname) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - switch(cityname) { - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum: - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Chongqing: - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12: - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].NewTokyo: - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Ishima: - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven: - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(200000); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city = cityname; - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("Traveled to " + cityname); - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity()."); - return false; - } - }, - - purchaseTor() { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (__WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__["a" /* SpecialServerIps */]["Darkweb Server"] != null) { - workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed"); - return false; - } - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].TorRouterCost)) { - workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].TorRouterCost); - - var darkweb = new __WEBPACK_IMPORTED_MODULE_16__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_28__utils_IPAddress_js__["a" /* createRandomIp */])(), "darkweb", "", false, false, false, 1); - Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["a" /* AddToAllServers */])(darkweb); - __WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp("Darkweb Server", darkweb.ip); - - document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive"); - - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().serversOnNetwork.push(darkweb.ip); - darkweb.serversOnNetwork.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().ip); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("You have purchased a Tor router!"); - return true; - }, - purchaseProgram(programName) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (__WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__["a" /* SpecialServerIps */]["Darkweb Server"] == null) { - workerScript.scriptRef.log("ERROR: You do not have TOR router. purchaseProgram() failed."); - return false; - } - - switch(programName.toLowerCase()) { - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram.toLowerCase(): - var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].BruteSSHProgram); - if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram); - workerScript.scriptRef.log("You have purchased the BruteSSH.exe program. The new program " + - "can be found on your home computer."); - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram.toLowerCase(): - var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].FTPCrackProgram); - if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram); - workerScript.scriptRef.log("You have purchased the FTPCrack.exe program. The new program " + - "can be found on your home computer."); - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram.toLowerCase(): - var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].RelaySMTPProgram); - if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram); - workerScript.scriptRef.log("You have purchased the relaySMTP.exe program. The new program " + - "can be found on your home computer."); - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram.toLowerCase(): - var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].HTTPWormProgram); - if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram); - workerScript.scriptRef.log("You have purchased the HTTPWorm.exe program. The new program " + - "can be found on your home computer."); - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram.toLowerCase(): - var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].SQLInjectProgram); - if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram); - workerScript.scriptRef.log("You have purchased the SQLInject.exe program. The new program " + - "can be found on your home computer."); - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1.toLowerCase(): - var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].DeepScanV1Program); - if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1); - workerScript.scriptRef.log("You have purchased the DeepscanV1.exe program. The new program " + - "can be found on your home computer."); - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2.toLowerCase(): - var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].DeepScanV2Program); - if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2); - workerScript.scriptRef.log("You have purchased the DeepscanV2.exe program. The new program " + - "can be found on your home computer."); - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid program passed into purchaseProgram()."); - return false; - } - return true; - }, - getStats : function() { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return {}; - } - } - - return { - hacking: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill, - strength: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].strength, - defense: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].defense, - dexterity: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].dexterity, - agility: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].agility, - charisma: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].charisma, - intelligence: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].intelligence - } - }, - isBusy : function() { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return; - } - } - return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking; - }, - upgradeHomeRam() { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - //Calculate how many times ram has been upgraded (doubled) - var currentRam = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().maxRam; - var numUpgrades = Math.log2(currentRam); - - //Calculate cost - //Have cost increase by some percentage each time RAM has been upgraded - var cost = currentRam * __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHome; - var mult = Math.pow(1.55, numUpgrades); - cost = cost * mult; - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(cost)) { - workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money"); - return false; - } - - var homeComputer = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer(); - homeComputer.maxRam *= 2; - - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(cost); - - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); - return true; - }, - getUpgradeHomeRamCost() { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - //Calculate how many times ram has been upgraded (doubled) - var currentRam = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().maxRam; - var numUpgrades = Math.log2(currentRam); - - //Calculate cost - //Have cost increase by some percentage each time RAM has been upgraded - var cost = currentRam * __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHome; - var mult = Math.pow(1.55, numUpgrades); - return cost * mult; - }, - workForCompany() { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission."); - return; - } - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition == "" || !(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition instanceof __WEBPACK_IMPORTED_MODULE_4__Company_js__["c" /* CompanyPosition */])) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job"); - return false; - } - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { - var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); - workerScript.scriptRef.log(txt); - } - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition.isPartTimeJob()) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startWorkPartTime(); - } else { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startWork(); - } - workerScript.scriptRef.log("Began working at " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyName + " as a " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition.positionName); - return true; - }, - applyToCompany(companyName, field) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(__WEBPACK_IMPORTED_MODULE_4__Company_js__["e" /* companyExists */])(companyName)) { - workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist."); - return false; - } - - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = companyName; - var res; - switch (field.toLowerCase()) { - case "software": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSoftwareJob(true); - break; - case "software consultant": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSoftwareConsultantJob(true); - break; - case "it": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForItJob(true); - break; - case "security engineer": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSecurityEngineerJob(true); - break; - case "network engineer": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForNetworkEngineerJob(true); - break; - case "business": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForBusinessJob(true); - break; - case "business consultant": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForBusinessConsultantJob(true); - break; - case "security": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSecurityJob(true); - break; - case "agent": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForAgentJob(true); - break; - case "employee": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForEmployeeJob(true); - break; - case "part-time employee": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForPartTimeEmployeeJob(true); - break; - case "waiter": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForWaiterJob(true); - break; - case "part-time waiter": - res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForPartTimeWaiterJob(true); - break; - default: - workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed"); - return false; - } - //The Player object's applyForJob function can return string with special error messages - if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(res)) { - workerScript.scriptRef.log(res); - return false; - } - if (res) { - workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition.positionName); - } else { - workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field."); - } - return res; - }, - getCompanyRep(companyName) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - var company = __WEBPACK_IMPORTED_MODULE_4__Company_js__["a" /* Companies */][companyName]; - if (company == null || !(company instanceof __WEBPACK_IMPORTED_MODULE_4__Company_js__["b" /* Company */])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName); - return -1; - } - return company.playerReputation; - }, - checkFactionInvitations() { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - //Make a copy of Player.factionInvitations - return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.slice(); - }, - joinFaction(name) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist."); - return false; - } - - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.includes(name)) { - workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); - return false; - } - - var index = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.indexOf(name); - if (index === -1) { - //Redundant and should never happen... - workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.splice(index, 1); - var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][name]; - Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["h" /* joinFaction */])(fac); - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("Joined the " + name + " faction."); - return true; - }, - workForFaction(name, type) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission."); - return; - } - - if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist."); - return false; - } - - if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factions.includes(name)) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name); - return false; - } - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { - var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); - workerScript.scriptRef.log(txt); - } - - var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][name]; - //Arrays listing factions that allow each time of work - var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "BitRunners", "The Black Hand", - "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"]; - var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"]; - var scWkAvailable = ["ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", - "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"]; - - switch (type.toLowerCase()) { - case "hacking": - case "hacking contracts": - case "hackingcontracts": - if (!hackAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startFactionHackWork(fac); - workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name); - return true; - case "field": - case "fieldwork": - case "field work": - if (!fdWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startFactionFieldWork(fac); - workerScript.scriptRef.log("Started carrying out field missions for " + fac.name); - return true; - case "security": - case "securitywork": - case "security work": - if (!scWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startFactionSecurityWork(fac); - workerScript.scriptRef.log("Started serving as security details for " + fac.name); - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type); - } - return true; - }, - getFactionRep(name) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist."); - return -1; - } - - return __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][name].playerReputation; - }, - createProgram(name) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { - workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission."); - return; - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { - var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); - workerScript.scriptRef.log(txt); - } - - switch(name.toLowerCase()) { - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].NukeProgram.toLowerCase(): - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].NukeProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes, 1); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 50) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create BruteSSH (level 50 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes * 2, 50); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 100) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create FTPCrack (level 100 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 100); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 250) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create relaySMTP (level 250 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 250); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 500) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create HTTPWorm (level 500 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer4Hours, 500); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 750) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create SQLInject (level 750 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours, 750); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 75) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV1 (level 75 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 75); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 400) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV2 (level 400 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 400); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].ServerProfiler.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 75) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create ServerProfiler (level 75 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].ServerProfiler, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 75); - break; - case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].AutoLink.toLowerCase(): - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 25) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create AutoLink (level 25 req)"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].AutoLink, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 25); - break; - default: - workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name); - return false; - } - workerScript.scriptRef.log("Began creating program: " + name); - return true; - }, - commitCrime : function(crime) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { - workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission."); - return; - } - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { - var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); - workerScript.scriptRef.log(txt); - } - - //Set Location to slums - switch(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city) { - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum: - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSlums; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Chongqing: - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].ChongqingSlums; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12: - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12Slums; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].NewTokyo: - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].NewTokyoSlums; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Ishima: - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].IshimaSlums; - break; - case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven: - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenSlums; - break; - default: - console.log("Invalid Player.city value"); - } - - crime = crime.toLowerCase(); - if (crime.includes("shoplift")) { - workerScript.scriptRef.log("Attempting to shoplift..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["k" /* commitShopliftCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("rob") && crime.includes("store")) { - workerScript.scriptRef.log("Attempting to rob a store..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["j" /* commitRobStoreCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("mug")) { - workerScript.scriptRef.log("Attempting to mug someone..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["i" /* commitMugCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("larceny")) { - workerScript.scriptRef.log("Attempting to commit larceny..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["h" /* commitLarcenyCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("drugs")) { - workerScript.scriptRef.log("Attempting to deal drugs..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["c" /* commitDealDrugsCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("bond") && crime.includes("forge")) { - workerScript.scriptRef.log("Attempting to forge corporate bonds..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["b" /* commitBondForgeryCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("traffick") && crime.includes("arms")) { - workerScript.scriptRef.log("Attempting to traffick illegal arms..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["l" /* commitTraffickArmsCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("homicide")) { - workerScript.scriptRef.log("Attempting to commit homicide..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["f" /* commitHomicideCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("grand") && crime.includes("auto")) { - workerScript.scriptRef.log("Attempting to commit grand theft auto..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["d" /* commitGrandTheftAutoCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("kidnap")) { - workerScript.scriptRef.log("Attempting to kidnap and ransom a high-profile target..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["g" /* commitKidnapCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("assassinate")) { - workerScript.scriptRef.log("Attempting to assassinate a high-profile target..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["a" /* commitAssassinationCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}) - } else if (crime.includes("heist")) { - workerScript.scriptRef.log("Attempting to pull off a heist..."); - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["e" /* commitHeistCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid crime passed into commitCrime(): " + crime); - } - }, - getCrimeChance(crime) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - - crime = crime.toLowerCase(); - if (crime.includes("shoplift")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["w" /* determineCrimeChanceShoplift */])(); - } else if (crime.includes("rob") && crime.includes("store")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["v" /* determineCrimeChanceRobStore */])(); - } else if (crime.includes("mug")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["u" /* determineCrimeChanceMug */])(); - } else if (crime.includes("larceny")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["t" /* determineCrimeChanceLarceny */])(); - } else if (crime.includes("drugs")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["o" /* determineCrimeChanceDealDrugs */])(); - } else if (crime.includes("bond") && crime.includes("forge")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["n" /* determineCrimeChanceBondForgery */])(); - } else if (crime.includes("traffick") && crime.includes("arms")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["x" /* determineCrimeChanceTraffickArms */])(); - } else if (crime.includes("homicide")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["r" /* determineCrimeChanceHomicide */])(); - } else if (crime.includes("grand") && crime.includes("auto")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["p" /* determineCrimeChanceGrandTheftAuto */])(); - } else if (crime.includes("kidnap")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["s" /* determineCrimeChanceKidnap */])(); - } else if (crime.includes("assassinate")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["m" /* determineCrimeChanceAssassination */])(); - } else if (crime.includes("heist")) { - return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["q" /* determineCrimeChanceHeist */])(); - } else { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime); - } - }, - getOwnedAugmentations(purchased=false) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - var res = []; - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations.length; ++i) { - res.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations[i].name); - } - if (purchased) { - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations.length; ++i) { - res.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations[i].name); - } - } - return res; - }, - getAugmentationsFromFaction(facname) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - - if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(facname)) { - workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname); - return []; - } - - var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][facname]; - var res = []; - for (var i = 0; i < fac.augmentations.length; ++i) { - res.push(fac.augmentations[i]); - } - return res; - }, - getAugmentationCost(name) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (!Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(name)) { - workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name); - return [-1, -1]; - } - - var aug = __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][name]; - return [aug.baseRepRequirement, aug.baseCost]; - }, - purchaseAugmentation(faction, name) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][faction]; - if (fac == null || !(fac instanceof __WEBPACK_IMPORTED_MODULE_9__Faction_js__["a" /* Faction */])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction); - return false; - } - - if (!fac.augmentations.includes(name)) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation"); - return false; - } - - var aug = __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][name]; - if (aug == null || !(aug instanceof __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["a" /* Augmentation */])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name); - return false; - } - - var isNeuroflux = false; - if (aug.name === __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) { - isNeuroflux = true; - } - - if (!isNeuroflux) { - for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations.length; ++j) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations.length; ++j) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - } - - if (fac.playerReputation < aug.baseRepRequirement) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name); - return false; - } - - var res = Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["k" /* purchaseAugmentation */])(aug, fac, true); - workerScript.scriptRef.log(res); - if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(res) && res.startsWith("You purchased")) { - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); - return true; - } else { - return false; - } - }, - installAugmentations(cbScript) { - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations.length === 0) { - workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed"); - return false; - } - __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed"); - Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["h" /* installAugmentations */])(cbScript); - return true; - } - } -} - - - - /***/ }), /* 20 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -23997,10 +21695,10 @@ function NetscriptFunctions(workerScript) { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Augmentation; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Faction_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptWorker_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Faction_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptWorker_js__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Prestige_js__ = __webpack_require__(36); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Prestige_js__ = __webpack_require__(34); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Script_js__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Server_js__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__ = __webpack_require__(1); @@ -27170,94 +24868,2396 @@ function getJobRequirementText(company, pos, tooltiptext=false) { /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return yesNoBoxCreate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return yesNoTxtInpBoxCreate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return yesNoBoxGetYesButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return yesNoBoxGetNoButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return yesNoTxtInpBoxGetYesButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return yesNoTxtInpBoxGetNoButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return yesNoTxtInpBoxGetInput; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return yesNoBoxClose; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return yesNoTxtInpBoxClose; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return yesNoBoxOpen; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__ = __webpack_require__(2); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptFunctions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return initSingularitySFFlags; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return hasSingularitySF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return hasBn11SF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return hasWallStreetSF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return wallStreetSFLvl; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(25); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__ = __webpack_require__(20); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__BitNode_js__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Crimes_js__ = __webpack_require__(31); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Company_js__ = __webpack_require__(21); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Constants_js__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__ = __webpack_require__(44); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__engine_js__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Faction_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__HacknetNode_js__ = __webpack_require__(38); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Location_js__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Message_js__ = __webpack_require__(24); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__Missions_js__ = __webpack_require__(27); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__Script_js__ = __webpack_require__(16); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__Server_js__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__Settings_js__ = __webpack_require__(15); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__ = __webpack_require__(12); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__ = __webpack_require__(28); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__Terminal_js__ = __webpack_require__(23); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__TextFile_js__ = __webpack_require__(49); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__ = __webpack_require__(36); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__NetscriptEnvironment_js__ = __webpack_require__(37); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__utils_decimal_js__ = __webpack_require__(29); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_25__utils_decimal_js__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__utils_DialogBox_js__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__ = __webpack_require__(2); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__utils_IPAddress_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__ = __webpack_require__(4); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__ = __webpack_require__(17); +var sprintf = __webpack_require__(43).sprintf, + vsprintf = __webpack_require__(43).vsprintf -/* Generic Yes-No Pop-up box - * Can be used to create pop-up boxes that require a yes/no response from player - */ -var yesNoBoxOpen = false; -function yesNoBoxClose() { - var container = document.getElementById("yes-no-box-container"); - if (container) { - container.style.display = "none"; - } else { - console.log("ERROR: Container not found for YesNoBox"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var hasSingularitySF=false, hasAISF=false, hasBn11SF=false, hasWallStreetSF=false; +var singularitySFLvl=1, wallStreetSFLvl=1; + +//Used to check and set flags for every Source File, despite the name of the function +function initSingularitySFFlags() { + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles.length; ++i) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 4) { + hasSingularitySF = true; + singularitySFLvl = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].lvl; + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 5) { + hasAISF = true; + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 8) { + hasWallStreetSF = true; + wallStreetSFLvl = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].lvl; + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].sourceFiles[i].n === 11) { + hasBn11SF = true; + } } - yesNoBoxOpen = false; } -function yesNoBoxGetYesButton() { - return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-box-yes"); -} +function NetscriptFunctions(workerScript) { + return { + Math : Math, + Date : Date, + hacknetnodes : __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacknetNodes, + sprintf : sprintf, + vsprintf: vsprintf, + scan : function(ip=workerScript.serverIp, hostnames=true){ + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, 'Invalid IP or hostname passed into scan() command'); + } + var out = []; + for (var i = 0; i < server.serversOnNetwork.length; i++) { + var entry; + if (hostnames) { + entry = server.getServerOnNetwork(i).hostname; + } else { + entry = server.getServerOnNetwork(i).ip; + } + if (entry == null) { + continue; + } + out.push(entry); + } + workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname); + return out; + }, + hack : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument"); + } + var threads = workerScript.scriptRef.threads; + if (isNaN(threads) || threads < 1) {threads = 1;} + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); + } -function yesNoBoxGetNoButton() { - return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-box-no"); -} + //Calculate the hacking time + var hackingTime = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["j" /* scriptCalculateHackingTime */])(server); //This is in seconds -function yesNoBoxCreate(txt) { - if (yesNoBoxOpen) {return false;} //Already open - yesNoBoxOpen = true; - var textElement = document.getElementById("yes-no-box-text"); - if (textElement) { - textElement.innerHTML = txt; - } + //No root access or skill level too low + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access"); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access"); + } - var c = document.getElementById("yes-no-box-container"); - if (c) { - c.style.display = "block"; - } else { - console.log("ERROR: Container not found for YesNoBox"); - } - return true; -} + if (server.requiredHackingSkill > __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill) { + workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); + } -/* Generic Yes-No POp-up Box with Text input */ -function yesNoTxtInpBoxClose() { - var c = document.getElementById("yes-no-text-input-box-container"); - if (c) { - c.style.display = "none"; - } else { - console.log("ERROR: Container not found for YesNoTextInputBox"); - } - yesNoBoxOpen = false; -} + workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")"); + //console.log("Hacking " + server.hostname + " after " + hackingTime.toString() + " seconds (t=" + threads + ")"); + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(hackingTime* 1000, workerScript).then(function() { + if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} + var hackChance = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["i" /* scriptCalculateHackingChance */])(server); + var rand = Math.random(); + var expGainedOnSuccess = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["g" /* scriptCalculateExpGain */])(server) * threads; + var expGainedOnFailure = (expGainedOnSuccess / 4); + if (rand < hackChance) { //Success! + var moneyGained = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["k" /* scriptCalculatePercentMoneyHacked */])(server); + moneyGained = Math.floor(server.moneyAvailable * moneyGained) * threads; -function yesNoTxtInpBoxGetYesButton() { - return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-text-input-box-yes"); -} + //Over-the-top safety checks + if (moneyGained <= 0) { + moneyGained = 0; + expGainedOnSuccess = expGainedOnFailure; + } + if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;} + server.moneyAvailable -= moneyGained; + if (server.moneyAvailable < 0) {server.moneyAvailable = 0;} -function yesNoTxtInpBoxGetNoButton() { - return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-text-input-box-no"); -} + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainMoney(moneyGained); + workerScript.scriptRef.onlineMoneyMade += moneyGained; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].scriptProdSinceLastAug += moneyGained; + workerScript.scriptRef.recordHack(server.ip, moneyGained, threads); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGainedOnSuccess); + workerScript.scriptRef.onlineExpGained += expGainedOnSuccess; + //console.log("Script successfully hacked " + server.hostname + " for $" + formatNumber(moneyGained, 2) + " and " + formatNumber(expGainedOnSuccess, 4) + " exp"); + workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(moneyGained, 2) + " and " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")"); + server.fortify(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ServerFortifyAmount * threads); + return Promise.resolve(true); + } else { + //Player only gains 25% exp for failure? TODO Can change this later to balance + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGainedOnFailure); + workerScript.scriptRef.onlineExpGained += expGainedOnFailure; + //console.log("Script unsuccessful to hack " + server.hostname + ". Gained " + formatNumber(expGainedOnFailure, 4) + " exp"); + workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnFailure, 4) + " exp (t=" + threads + ")"); + return Promise.resolve(false); + } + }); + }, + sleep : function(time,log=true){ + if (time === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument"); + } + if (log) { + workerScript.scriptRef.log("Sleeping for " + time + " milliseconds"); + } + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(time, workerScript).then(function() { + return Promise.resolve(true); + }); + }, + grow : function(ip){ + var threads = workerScript.scriptRef.threads; + if (isNaN(threads) || threads < 1) {threads = 1;} + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip); + } -function yesNoTxtInpBoxGetInput() { - var val = document.getElementById("yes-no-text-input-box-input").value; - val = val.replace(/\s+/g, ''); - return val; -} + //No root access or skill level too low + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access"); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access"); + } -function yesNoTxtInpBoxCreate(txt) { - yesNoBoxOpen = true; - var txtE = document.getElementById("yes-no-text-input-box-text"); - if (txtE) { - txtE.innerHTML = txt; - } + var growTime = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["h" /* scriptCalculateGrowTime */])(server); + //console.log("Executing grow() on server " + server.hostname + " in " + formatNumber(growTime/1000, 3) + " seconds") + workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(growTime/1000, 3) + " seconds (t=" + threads + ")"); + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(growTime, workerScript).then(function() { + if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} + server.moneyAvailable += (1 * threads); //It can be grown even if it has no money + var growthPercentage = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["j" /* processSingleServerGrowth */])(server, 450 * threads); + workerScript.scriptRef.recordGrow(server.ip, threads); + var expGain = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["g" /* scriptCalculateExpGain */])(server) * threads; + if (growthPercentage == 1) { + expGain = 0; + } + workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " + + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(growthPercentage*100 - 100, 6) + "%. Gained " + + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGain, 4) + " hacking exp (t=" + threads +")"); + workerScript.scriptRef.onlineExpGained += expGain; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGain); + return Promise.resolve(growthPercentage); + }); + }, + weaken : function(ip){ + var threads = workerScript.scriptRef.threads; + if (isNaN(threads) || threads < 1) {threads = 1;} + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip); + } - var c = document.getElementById("yes-no-text-input-box-container"); - if (c) { - c.style.display = "block"; - } else { - console.log("ERROR: Container not found for YesNoTextInputBox"); + //No root access or skill level too low + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access"); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access"); + } + + var weakenTime = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["l" /* scriptCalculateWeakenTime */])(server); + workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " + + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(weakenTime/1000, 3) + " seconds (t=" + threads + ")"); + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["e" /* netscriptDelay */])(weakenTime, workerScript).then(function() { + if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} + server.weaken(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ServerWeakenAmount * threads); + workerScript.scriptRef.recordWeaken(server.ip, threads); + var expGain = Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["g" /* scriptCalculateExpGain */])(server) * threads; + workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty + + ". Gained " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGain, 4) + " hacking exp (t=" + threads + ")"); + workerScript.scriptRef.onlineExpGained += expGain; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainHackingExp(expGain); + return Promise.resolve(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ServerWeakenAmount * threads); + }); + }, + print : function(args){ + if (args === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument"); + } + workerScript.scriptRef.log(args.toString()); + }, + tprint : function(args) { + if (args === undefined || args == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument"); + } + var x = args.toString(); + if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["d" /* isHTML */])(x)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].takeDamage(1); + Object(__WEBPACK_IMPORTED_MODULE_26__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You suddenly feel a sharp shooting pain through your body as an angry voice in your head exclaims:

" + + "DON'T USE TPRINT() TO OUTPUT HTML ELEMENTS TO YOUR TERMINAL!!!!

" + + "(You lost 1 HP)"); + return; + } + Object(__WEBPACK_IMPORTED_MODULE_20__Terminal_js__["b" /* post */])(workerScript.scriptRef.filename + ": " + args.toString()); + }, + clearLog : function() { + workerScript.scriptRef.clearLog(); + }, + nuke : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip); + } + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].NukeProgram)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the NUKE.exe virus!"); + } + if (server.openPortCount < server.numOpenPortsRequired) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Not enough ports opened to use NUKE.exe virus"); + } + if (server.hasAdminRights) { + workerScript.scriptRef.log("Already have root access to " + server.hostname); + } else { + server.hasAdminRights = true; + workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access"); + } + return true; + }, + brutessh : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); + } + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram)) { + workerScript.scriptRef.log("You do not have the BruteSSH.exe program!"); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the BruteSSH.exe program!"); + } + if (!server.sshPortOpen) { + workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)"); + server.sshPortOpen = true; + ++server.openPortCount; + } else { + workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname); + } + return true; + }, + ftpcrack : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); + } + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the FTPCrack.exe program!"); + } + if (!server.ftpPortOpen) { + workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)"); + server.ftpPortOpen = true; + ++server.openPortCount; + } else { + workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname); + } + return true; + }, + relaysmtp : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); + } + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the relaySMTP.exe program!"); + } + if (!server.smtpPortOpen) { + workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)"); + server.smtpPortOpen = true; + ++server.openPortCount; + } else { + workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname); + } + return true; + }, + httpworm : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); + } + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the HTTPWorm.exe program!"); + } + if (!server.httpPortOpen) { + workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)"); + server.httpPortOpen = true; + ++server.openPortCount; + } else { + workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname); + } + return true; + }, + sqlinject : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); + } + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the SQLInject.exe program!"); + } + if (!server.sqlPortOpen) { + workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)"); + server.sqlPortOpen = true; + ++server.openPortCount; + } else { + workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname); + } + return true; + }, + run : function(scriptname,threads = 1){ + if (scriptname === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)"); + } + if (isNaN(threads) || threads < 1) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); + } + var argsForNewScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForNewScript.push(arguments[i]); + } + var scriptServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); + if (scriptServer == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); + } + + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["f" /* runScriptFromScript */])(scriptServer, scriptname, argsForNewScript, workerScript, threads); + }, + exec : function(scriptname,ip,threads = 1){ + if (scriptname === undefined || ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)"); + } + if (isNaN(threads) || threads < 1) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0"); + } + var argsForNewScript = []; + for (var i = 3; i < arguments.length; ++i) { + argsForNewScript.push(arguments[i]); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip); + } + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["f" /* runScriptFromScript */])(server, scriptname, argsForNewScript, workerScript, threads); + }, + kill : function(filename,ip){ + if (filename === undefined || ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip); + } + var argsForKillTarget = []; + for (var i = 2; i < arguments.length; ++i) { + argsForKillTarget.push(arguments[i]); + } + var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(filename, argsForKillTarget, server); + if (runningScriptObj == null) { + workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget)); + return false; + } + var res = Object(__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["d" /* killWorkerScript */])(runningScriptObj, server.ip); + if (res) { + workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die..."); + return true; + } else { + workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget)); + return false; + } + }, + killall : function(ip){ + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip); + } + for (var i = server.runningScripts.length-1; i >= 0; --i) { + Object(__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["d" /* killWorkerScript */])(server.runningScripts[i], server.ip); + } + workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die"); + return true; + }, + scp : function(scriptname, ip1, ip2){ + if (arguments.length !== 2 && arguments.length !== 3) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); + } + if (scriptname && scriptname.constructor === Array) { + //Recursively call scp on all elements of array + var res = false; + scriptname.forEach(function(script) { + if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) { + res = true; + }; + }); + return res; + } + if (!scriptname.endsWith(".lit") && !scriptname.endsWith(".script")) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() only works for .script and .lit files"); + } + + var destServer, currServ; + + if (arguments.length === 3) { //scriptname, source, destination + if (scriptname === undefined || ip1 === undefined || ip2 === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); + } + destServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip2); + if (destServer == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); + } + + currServ = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip1); + if (currServ == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); + } + } else if (arguments.length === 2) { //scriptname, destination + if (scriptname === undefined || ip1 === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); + } + destServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip1); + if (destServer == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); + } + + currServ = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); + if (currServ == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); + } + } + + //Scp for lit files + if (scriptname.endsWith(".lit")) { + var found = false; + for (var i = 0; i < currServ.messages.length; ++i) { + if (!(currServ.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) && currServ.messages[i] == scriptname) { + found = true; + } + } + + if (!found) { + workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); + return false; + } + + for (var i = 0; i < destServer.messages.length; ++i) { + if (destServer.messages[i] === scriptname) { + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + return true; //Already exists + } + } + destServer.messages.push(scriptname); + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + return true; + } + + //Scp for script files + var sourceScript = null; + for (var i = 0; i < currServ.scripts.length; ++i) { + if (scriptname == currServ.scripts[i].filename) { + sourceScript = currServ.scripts[i]; + break; + } + } + if (sourceScript == null) { + workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); + return false; + } + + //Overwrite script if it already exists + for (var i = 0; i < destServer.scripts.length; ++i) { + if (scriptname == destServer.scripts[i].filename) { + workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten."); + workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname); + var oldScript = destServer.scripts[i]; + oldScript.code = sourceScript.code; + oldScript.ramUsage = sourceScript.ramUsage; + return true; + } + } + + //Create new script if it does not already exist + var newScript = new __WEBPACK_IMPORTED_MODULE_15__Script_js__["c" /* Script */](); + newScript.filename = scriptname; + newScript.code = sourceScript.code; + newScript.ramUsage = sourceScript.ramUsage; + newScript.server = destServer.ip; + destServer.scripts.push(newScript); + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + return true; + }, + ls : function(ip, grep) { + if (ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip); + } + + //Get the grep filter, if one exists + var filter = false; + if (arguments.length >= 2) { + filter = grep.toString(); + } + + var allFiles = []; + for (var i = 0; i < server.programs.length; i++) { + if (filter) { + if (server.programs[i].includes(filter)) { + allFiles.push(server.programs[i]); + } + } else { + allFiles.push(server.programs[i]); + } + } + for (var i = 0; i < server.scripts.length; i++) { + if (filter) { + if (server.scripts[i].filename.includes(filter)) { + allFiles.push(server.scripts[i].filename); + } + } else { + allFiles.push(server.scripts[i].filename); + } + + } + for (var i = 0; i < server.messages.length; i++) { + if (filter) { + if (server.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) { + if (server.messages[i].filename.includes(filter)) { + allFiles.push(server.messages[i].filename); + } + } else if (server.messages[i].includes(filter)) { + allFiles.push(server.messages[i]); + } + } else { + if (server.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) { + allFiles.push(server.messages[i].filename); + } else { + allFiles.push(server.messages[i]); + } + } + } + + //Sort the files alphabetically then print each + allFiles.sort(); + return allFiles; + }, + hasRootAccess : function(ip){ + if (ip===undefined){ + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null){ + workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); + } + return server.hasAdminRights; + }, + getIp : function() { + var scriptServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); + if (scriptServer == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); + } + return scriptServer.ip; + }, + getHostname : function(){ + var scriptServer = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); + if (scriptServer == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); + } + return scriptServer.hostname; + }, + getHackingLevel : function(){ + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].updateSkillLevels(); + workerScript.scriptRef.log("getHackingLevel() returned " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill); + return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill; + }, + getHackingMultipliers : function() { + return { + chance: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_chance_mult, + speed: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_speed_mult, + money: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_money_mult, + growth: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_grow_mult, + }; + }, + getBitNodeMultipliers: function() { + if (!hasAISF) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run."); + } + return __WEBPACK_IMPORTED_MODULE_2__BitNode_js__["a" /* BitNodeMultipliers */]; + }, + getServerMoneyAvailable : function(ip){ + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); + } + if (server.hostname == "home") { + //Return player's money + workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.toNumber(), 2)); + return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.toNumber(); + } + workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.moneyAvailable, 2) + " for " + server.hostname); + return server.moneyAvailable; + }, + getServerSecurityLevel : function(ip){ + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.hackDifficulty, 3) + " for " + server.hostname); + return server.hackDifficulty; + }, + getServerBaseSecurityLevel : function(ip){ + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.baseDifficulty, 3) + " for " + server.hostname); + return server.baseDifficulty; + }, + getServerMinSecurityLevel : function(ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.minDifficulty, 3) + " for " + server.hostname); + return server.minDifficulty; + }, + getServerRequiredHackingLevel : function(ip){ + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.requiredHackingSkill, 0) + " for " + server.hostname); + return server.requiredHackingSkill; + }, + getServerMaxMoney : function(ip){ + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.moneyMax, 0) + " for " + server.hostname); + return server.moneyMax; + }, + getServerGrowth : function(ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerGrowth() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.serverGrowth, 0) + " for " + server.hostname); + return server.serverGrowth; + }, + getServerNumPortsRequired : function(ip){ + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.numOpenPortsRequired, 0) + " for " + server.hostname); + return server.numOpenPortsRequired; + }, + getServerRam : function(ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip); + } + workerScript.scriptRef.log("getServerRam() returned [" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.maxRam, 2) + "GB, " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.ramUsed, 2) + "GB]"); + return [server.maxRam, server.ramUsed]; + }, + serverExists : function(ip) { + return (Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip) !== null); + }, + fileExists : function(filename,ip=workerScript.serverIp){ + if (filename === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip); + } + for (var i = 0; i < server.scripts.length; ++i) { + if (filename == server.scripts[i].filename) { + return true; + } + } + for (var i = 0; i < server.programs.length; ++i) { + if (filename.toLowerCase() == server.programs[i].toLowerCase()) { + return true; + } + } + for (var i = 0; i < server.messages.length; ++i) { + if (!(server.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_12__Message_js__["a" /* Message */]) && + filename.toLowerCase() === server.messages[i]) { + return true; + } + } + return false; + }, + isRunning : function(filename,ip){ + if (filename === undefined || ip === undefined) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)"); + } + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip); + } + var argsForTargetScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForTargetScript.push(arguments[i]); + } + return (Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(filename, argsForTargetScript, server) != null); + }, + getNextHacknetNodeCost : __WEBPACK_IMPORTED_MODULE_10__HacknetNode_js__["b" /* getCostOfNextHacknetNode */], + purchaseHacknetNode : __WEBPACK_IMPORTED_MODULE_10__HacknetNode_js__["d" /* purchaseHacknet */], + getStockPrice : function(symbol) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()"); + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()"); + } + return parseFloat(stock.price.toFixed(3)); + }, + getStockPosition : function(symbol) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()"); + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()"); + } + return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx]; + }, + buyStock : function(symbol, shares) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use buyStock()"); + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into buyStock()"); + } + if (shares < 0 || isNaN(shares)) { + workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to buyStock()"); + return false; + } + shares = Math.round(shares); + if (shares === 0) {return false;} + + var totalPrice = stock.price * shares; + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) { + workerScript.scriptRef.log("Not enough money to purchase " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + + symbol + ". Need $" + + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2).toString()); + return false; + } + + var origTotal = stock.playerShares * stock.playerAvgPx; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission); + var newTotal = origTotal + totalPrice; + stock.playerShares += shares; + stock.playerAvgPx = newTotal / stock.playerShares; + if (__WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].Page.StockMarket) { + Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["p" /* updateStockPlayerPosition */])(stock); + } + workerScript.scriptRef.log("Bought " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share"); + return true; + }, + sellStock : function(symbol, shares) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use sellStock()"); + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into sellStock()"); + } + if (shares < 0 || isNaN(shares)) { + workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to sellStock()"); + return false; + } + shares = Math.round(shares); + if (shares > stock.playerShares) {shares = stock.playerShares;} + if (shares === 0) {return false;} + var gains = stock.price * shares - __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainMoney(gains); + + //Calculate net profit and add to script stats + var netProfit = ((stock.price - stock.playerAvgPx) * shares) - __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; + if (isNaN(netProfit)) {netProfit = 0;} + workerScript.scriptRef.onlineMoneyMade += netProfit; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].scriptProdSinceLastAug += netProfit; + + stock.playerShares -= shares; + if (stock.playerShares == 0) { + stock.playerAvgPx = 0; + } + if (__WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_8__engine_js__["Engine"].Page.StockMarket) { + Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["p" /* updateStockPlayerPosition */])(stock); + } + workerScript.scriptRef.log("Sold " + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. Gained " + + "$" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gains, 2)); + return true; + }, + shortStock(symbol, shares) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use shortStock()"); + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); + } + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()"); + } + return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["n" /* shortStock */])(stock, shares, workerScript); + }, + sellShort(symbol, shares) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use sellShort()"); + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); + } + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()"); + } + return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["l" /* sellShort */])(stock, shares, workerScript); + }, + placeOrder(symbol, shares, price, type, pos) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()"); + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); + } + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()"); + } + var orderType, orderPos; + type = type.toLowerCase(); + if (type.includes("limit") && type.includes("buy")) { + orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitBuy; + } else if (type.includes("limit") && type.includes("sell")) { + orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitSell; + } else if (type.includes("stop") && type.includes("buy")) { + orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].StopBuy; + } else if (type.includes("stop") && type.includes("sell")) { + orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].StopSell; + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); + } + + pos = pos.toLowerCase(); + if (pos.includes("l")) { + orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Long; + } else if (pos.includes('s')) { + orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Short; + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); + } + + return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["k" /* placeOrder */])(stock, shares, price, orderType, orderPos, workerScript); + }, + cancelOrder(symbol, shares, price, type, pos) { + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hasTixApiAccess) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()"); + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); + } + } + var stock = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["d" /* SymbolToStockMap */][symbol]; + if (stock == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()"); + } + if (isNaN(shares) || isNaN(price)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric"); + } + var orderType, orderPos; + type = type.toLowerCase(); + if (type.includes("limit") && type.includes("buy")) { + orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitBuy; + } else if (type.includes("limit") && type.includes("sell")) { + orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].LimitSell; + } else if (type.includes("stop") && type.includes("buy")) { + orderType = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["a" /* OrderTypes */].StopBuy; + } else if (type.includes("stop") && type.includes("sell")) { + orderType = OrderType.StopSell; + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); + } + + pos = pos.toLowerCase(); + if (pos.includes("l")) { + orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Long; + } else if (pos.includes('s')) { + orderPos = __WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["b" /* PositionTypes */].Short; + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); + } + params = { + stock: stock, + shares: shares, + price: price, + type: orderType, + pos: orderPos + }; + return Object(__WEBPACK_IMPORTED_MODULE_19__StockMarket_js__["e" /* cancelOrder */])(params, workerScript); + }, + purchaseServer : function(hostname, ram) { + var hostnameStr = String(hostname); + hostnameStr = hostnameStr.replace(/\s\s+/g, ''); + if (hostnameStr == "") { + workerScript.scriptRef.log("Error: Passed empty string for hostname argument of purchaseServer()"); + return ""; + } + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.length >= __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit) { + workerScript.scriptRef.log("Error: You have reached the maximum limit of " + __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit + + " servers. You cannot purchase any more."); + return ""; + } + + ram = Math.round(ram); + if (isNaN(ram) || !Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["e" /* powerOfTwo */])(ram)) { + workerScript.scriptRef.log("Error: Invalid ram argument passed to purchaseServer(). Must be numeric and a power of 2"); + return ""; + } + + var cost = ram * __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer; + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(cost)) { + workerScript.scriptRef.log("Error: Not enough money to purchase server. Need $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2)); + return ""; + } + var newServ = new __WEBPACK_IMPORTED_MODULE_16__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_28__utils_IPAddress_js__["a" /* createRandomIp */])(), hostnameStr, "", false, true, true, ram); + Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["a" /* AddToAllServers */])(newServ); + + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.push(newServ.ip); + var homeComputer = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer(); + homeComputer.serversOnNetwork.push(newServ.ip); + newServ.serversOnNetwork.push(homeComputer.ip); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(cost); + workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2)); + return newServ.hostname; + }, + deleteServer : function(hostname) { + var hostnameStr = String(hostname); + hostnameStr = hostnameStr.replace(/\s\s+/g, ''); + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["c" /* GetServerByHostname */])(hostnameStr); + if (server == null) { + workerScript.scriptRef.log("Error: Could not find server with hostname " + hostnameStr + ". deleteServer() failed"); + return false; + } + + if (!server.purchasedByPlayer || server.hostname == "home") { + workerScript.scriptRef.log("Error: Server " + server.hostname + " is not a purchased server. " + + "Cannot be deleted. deleteServer failed"); + return false; + } + + var ip = server.ip; + + //A server cannot delete itself + if (ip == workerScript.serverIp) { + workerScript.scriptRef.log("Error: Cannot call deleteServer() on self. Function failed"); + return false; + } + + //Delete all scripts running on server + if (server.runningScripts.length > 0) { + workerScript.scriptRef.log("Error: Cannot delete server " + server.hostname + " because it still has scripts running."); + return false; + } + + //Delete from player's purchasedServers array + var found = false; + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.length; ++i) { + if (ip == __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers[i]) { + found = true; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.splice(i, 1); + break; + } + } + + if (!found) { + workerScript.scriptRef.log("Error: Could not identify server " + server.hostname + + "as a purchased server. This is likely a bug please contact game dev"); + return false; + } + + //Delete from all servers + delete __WEBPACK_IMPORTED_MODULE_16__Server_js__["b" /* AllServers */][ip]; + + //Delete from home computer + found = false; + var homeComputer = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer(); + for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) { + if (ip == homeComputer.serversOnNetwork[i]) { + homeComputer.serversOnNetwork.splice(i, 1); + workerScript.scriptRef.log("Deleted server " + hostnameStr); + return true; + } + } + //Wasn't found on home computer + workerScript.scriptRef.log("Error: Could not find server " + server.hostname + + "as a purchased server. This is likely a bug please contact game dev"); + return false; + }, + getPurchasedServers : function(hostname=true) { + var res = []; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].purchasedServers.forEach(function(ip) { + if (hostname) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "ERR: Could not find server in getPurchasedServers(). This is a bug please report to game dev"); + } + res.push(server.hostname); + } else { + res.push(ip); + } + }); + return res; + }, + round : function(n) { + if (isNaN(n)) {return 0;} + return Math.round(n); + }, + write : function(port, data="", mode="a") { + if (!isNaN(port)) { //Write to port + //Port 1-10 + if (port < 1 || port > 10) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Trying to write to invalid port: " + port + ". Only ports 1-10 are valid."); + } + var portName = "Port" + String(port); + var port = __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["a" /* NetscriptPorts */][portName]; + if (port == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); + } + port.push(data); + if (port.length > __WEBPACK_IMPORTED_MODULE_17__Settings_js__["a" /* Settings */].MaxPortCapacity) { + port.shift(); + return true; + } + return false; + } else if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(port)) { //Write to text file + var fn = port; + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); + if (server == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev"); + } + var txtFile = Object(__WEBPACK_IMPORTED_MODULE_21__TextFile_js__["b" /* getTextFile */])(fn, server); + if (txtFile == null) { + txtFile = Object(__WEBPACK_IMPORTED_MODULE_21__TextFile_js__["a" /* createTextFile */])(fn, data, server); + return true; + } + if (mode === "w") { + txtFile.write(data); + } else { + txtFile.append(data); + } + return true; + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument passed in for port: " + port + ". Must be a number between 1 and 10"); + } + }, + read : function(port) { + if (!isNaN(port)) { //Read from port + //Port 1-10 + if (port < 1 || port > 10) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Trying to write to invalid port: " + port + ". Only ports 1-10 are valid."); + } + var portName = "Port" + String(port); + var port = __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["a" /* NetscriptPorts */][portName]; + if (port == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); + } + if (port.length == 0) { + return "NULL PORT DATA"; + } else { + return port.shift(); + } + } else if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(port)) { //Read from text file + var fn = port; + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(workerScript.serverIp); + if (server == null) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev"); + } + var txtFile = Object(__WEBPACK_IMPORTED_MODULE_21__TextFile_js__["b" /* getTextFile */])(fn, server); + if (txtFile !== null) { + return txtFile.text; + } else { + return ""; + } + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument passed in for port: " + port + ". Must be a number between 1 and 10"); + } + }, + scriptRunning : function(scriptname, ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip); + } + for (var i = 0; i < server.runningScripts.length; ++i) { + if (server.runningScripts[i].filename == scriptname) { + return true; + } + } + return false; + }, + scriptKill : function(scriptname, ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip); + } + var suc = false; + for (var i = 0; i < server.runningScripts.length; ++i) { + if (server.runningScripts[i].filename == scriptname) { + Object(__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["d" /* killWorkerScript */])(server.runningScripts[i], server.ip); + suc = true; + } + } + return suc; + }, + getScriptRam : function (scriptname, ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip); + } + for (var i = 0; i < server.scripts.length; ++i) { + if (server.scripts[i].filename == scriptname) { + return server.scripts[i].ramUsage; + } + } + return 0; + }, + getHackTime : function(ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip); + } + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["j" /* scriptCalculateHackingTime */])(server); //Returns seconds + }, + getGrowTime : function(ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip); + } + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["h" /* scriptCalculateGrowTime */])(server) / 1000; //Returns seconds + }, + getWeakenTime : function(ip) { + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); + } + return Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["l" /* scriptCalculateWeakenTime */])(server) / 1000; //Returns seconds + }, + getScriptIncome : function(scriptname, ip) { + if (arguments.length === 0) { + //Get total script income + var res = []; + res.push(Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["d" /* updateActiveScriptsItems */])()); + res.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].scriptProdSinceLastAug / (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].playtimeSinceLastAug/1000)); + return res; + } else { + //Get income for a particular script + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); + } + var argsForScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForScript.push(arguments[i]); + } + var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(scriptname, argsForScript, server); + if (runningScriptObj == null) { + workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForScript)); + return -1; + } + return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime; + } + }, + getScriptExpGain : function(scriptname, ip) { + if (arguments.length === 0) { + var total = 0; + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["h" /* workerScripts */].length; ++i) { + total += (__WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["h" /* workerScripts */][i].scriptRef.onlineExpGained / __WEBPACK_IMPORTED_MODULE_22__NetscriptWorker_js__["h" /* workerScripts */][i].scriptRef.onlineRunningTime); + } + return total; + } else { + //Get income for a particular script + var server = Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["e" /* getServer */])(ip); + if (server == null) { + workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); + } + var argsForScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForScript.push(arguments[i]); + } + var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_15__Script_js__["d" /* findRunningScript */])(scriptname, argsForScript, server); + if (runningScriptObj == null) { + workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_27__utils_HelperFunctions_js__["f" /* printArray */])(argsForScript)); + return -1; + } + return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime; + } + }, + getTimeSinceLastAug : function() { + return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].playtimeSinceLastAug; + }, + prompt : function(txt) { + if (__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["e" /* yesNoBoxOpen */]) { + workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open"); + return false; + } + if (!Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(txt)) {txt = String(txt);} + var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(), noBtn = Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])(); + yesBtn.innerHTML = "Yes"; + noBtn.innerHTML = "No"; + return new Promise(function(resolve, reject) { + yesBtn.addEventListener("click", ()=>{ + Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); + resolve(true); + }); + noBtn.addEventListener("click", ()=>{ + Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); + resolve(false); + }); + Object(__WEBPACK_IMPORTED_MODULE_30__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])(txt); + }); + }, + + /* Singularity Functions */ + universityCourse : function(universityName, className) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { + workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission."); + return; + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { + var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); + workerScript.scriptRef.log(txt); + } + + var costMult, expMult; + switch(universityName.toLowerCase()) { + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSummitUniversity.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum) { + workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSummitUniversity; + costMult = 4; + expMult = 3; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12RothmanUniversity.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12) { + workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12RothmanUniversity; + costMult = 3; + expMult = 2; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenZBInstituteOfTechnology.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven) { + workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenZBInstituteOfTechnology; + costMult = 5; + expMult = 4; + break; + default: + workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed"); + return false; + } + + var task; + switch(className.toLowerCase()) { + case "Study Computer Science".toLowerCase(): + task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassStudyComputerScience; + break; + case "Data Structures".toLowerCase(): + task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassDataStructures; + break; + case "Networks".toLowerCase(): + task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassNetworks; + break; + case "Algorithms".toLowerCase(): + task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassAlgorithms; + break; + case "Management".toLowerCase(): + task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassManagement; + break; + case "Leadership".toLowerCase(): + task = __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassLeadership; + break; + default: + workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, task); + workerScript.scriptRef.log("Started " + task + " at " + universityName); + return true; + }, + + gymWorkout : function(gymName, stat) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { + workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission."); + return; + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { + var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); + workerScript.scriptRef.log(txt); + } + var costMult, expMult; + switch(gymName.toLowerCase()) { + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumCrushFitnessGym.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum) { + workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumCrushFitnessGym; + costMult = 2; + expMult = 1.5; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSnapFitnessGym.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum) { + workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSnapFitnessGym; + costMult = 6; + expMult = 4; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12IronGym.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12) { + workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12IronGym; + costMult = 1; + expMult = 1; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12PowerhouseGym.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12) { + workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12PowerhouseGym; + costMult = 10; + expMult = 7.5; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenMilleniumFitnessGym: + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven) { + workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenMilleniumFitnessGym; + costMult = 3; + expMult = 2.5; + break; + default: + workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed"); + return false; + } + + switch(stat.toLowerCase()) { + case "strength".toLowerCase(): + case "str".toLowerCase(): + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymStrength); + break; + case "defense".toLowerCase(): + case "def".toLowerCase(): + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymDefense); + break; + case "dexterity".toLowerCase(): + case "dex".toLowerCase(): + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymDexterity); + break; + case "agility".toLowerCase(): + case "agi".toLowerCase(): + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].ClassGymAgility); + break; + default: + workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed"); + return false; + } + workerScript.scriptRef.log("Started training " + stat + " at " + gymName); + return true; + }, + + travelToCity(cityname) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + + switch(cityname) { + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum: + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Chongqing: + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12: + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].NewTokyo: + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Ishima: + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven: + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(200000); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city = cityname; + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); + workerScript.scriptRef.log("Traveled to " + cityname); + return true; + default: + workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity()."); + return false; + } + }, + + purchaseTor() { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + + if (__WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__["a" /* SpecialServerIps */]["Darkweb Server"] != null) { + workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed"); + return false; + } + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].TorRouterCost)) { + workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].TorRouterCost); + + var darkweb = new __WEBPACK_IMPORTED_MODULE_16__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_28__utils_IPAddress_js__["a" /* createRandomIp */])(), "darkweb", "", false, false, false, 1); + Object(__WEBPACK_IMPORTED_MODULE_16__Server_js__["a" /* AddToAllServers */])(darkweb); + __WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp("Darkweb Server", darkweb.ip); + + document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive"); + + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().serversOnNetwork.push(darkweb.ip); + darkweb.serversOnNetwork.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().ip); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); + workerScript.scriptRef.log("You have purchased a Tor router!"); + return true; + }, + purchaseProgram(programName) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + + if (__WEBPACK_IMPORTED_MODULE_18__SpecialServerIps_js__["a" /* SpecialServerIps */]["Darkweb Server"] == null) { + workerScript.scriptRef.log("ERROR: You do not have TOR router. purchaseProgram() failed."); + return false; + } + + switch(programName.toLowerCase()) { + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram.toLowerCase(): + var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].BruteSSHProgram); + if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram); + workerScript.scriptRef.log("You have purchased the BruteSSH.exe program. The new program " + + "can be found on your home computer."); + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram.toLowerCase(): + var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].FTPCrackProgram); + if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram); + workerScript.scriptRef.log("You have purchased the FTPCrack.exe program. The new program " + + "can be found on your home computer."); + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram.toLowerCase(): + var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].RelaySMTPProgram); + if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram); + workerScript.scriptRef.log("You have purchased the relaySMTP.exe program. The new program " + + "can be found on your home computer."); + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram.toLowerCase(): + var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].HTTPWormProgram); + if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram); + workerScript.scriptRef.log("You have purchased the HTTPWorm.exe program. The new program " + + "can be found on your home computer."); + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram.toLowerCase(): + var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].SQLInjectProgram); + if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram); + workerScript.scriptRef.log("You have purchased the SQLInject.exe program. The new program " + + "can be found on your home computer."); + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1.toLowerCase(): + var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].DeepScanV1Program); + if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1); + workerScript.scriptRef.log("You have purchased the DeepscanV1.exe program. The new program " + + "can be found on your home computer."); + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2.toLowerCase(): + var price = Object(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_7__DarkWeb_js__["a" /* DarkWebItems */].DeepScanV2Program); + if (price > 0 && __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.gt(price)) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(price); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2); + workerScript.scriptRef.log("You have purchased the DeepscanV2.exe program. The new program " + + "can be found on your home computer."); + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + default: + workerScript.scriptRef.log("ERROR: Invalid program passed into purchaseProgram()."); + return false; + } + return true; + }, + getStats : function() { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return {}; + } + } + + return { + hacking: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill, + strength: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].strength, + defense: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].defense, + dexterity: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].dexterity, + agility: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].agility, + charisma: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].charisma, + intelligence: __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].intelligence + } + }, + isBusy : function() { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return; + } + } + return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking; + }, + upgradeHomeRam() { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + //Calculate how many times ram has been upgraded (doubled) + var currentRam = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().maxRam; + var numUpgrades = Math.log2(currentRam); + + //Calculate cost + //Have cost increase by some percentage each time RAM has been upgraded + var cost = currentRam * __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHome; + var mult = Math.pow(1.55, numUpgrades); + cost = cost * mult; + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].money.lt(cost)) { + workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money"); + return false; + } + + var homeComputer = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer(); + homeComputer.maxRam *= 2; + + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].loseMoney(cost); + + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); + workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); + return true; + }, + getUpgradeHomeRamCost() { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + //Calculate how many times ram has been upgraded (doubled) + var currentRam = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].getHomeComputer().maxRam; + var numUpgrades = Math.log2(currentRam); + + //Calculate cost + //Have cost increase by some percentage each time RAM has been upgraded + var cost = currentRam * __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHome; + var mult = Math.pow(1.55, numUpgrades); + return cost * mult; + }, + workForCompany() { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { + workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission."); + return; + } + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition == "" || !(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition instanceof __WEBPACK_IMPORTED_MODULE_4__Company_js__["c" /* CompanyPosition */])) { + workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job"); + return false; + } + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { + var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); + workerScript.scriptRef.log(txt); + } + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition.isPartTimeJob()) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startWorkPartTime(); + } else { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startWork(); + } + workerScript.scriptRef.log("Began working at " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyName + " as a " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition.positionName); + return true; + }, + applyToCompany(companyName, field) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (!Object(__WEBPACK_IMPORTED_MODULE_4__Company_js__["e" /* companyExists */])(companyName)) { + workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist."); + return false; + } + + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = companyName; + var res; + switch (field.toLowerCase()) { + case "software": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSoftwareJob(true); + break; + case "software consultant": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSoftwareConsultantJob(true); + break; + case "it": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForItJob(true); + break; + case "security engineer": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSecurityEngineerJob(true); + break; + case "network engineer": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForNetworkEngineerJob(true); + break; + case "business": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForBusinessJob(true); + break; + case "business consultant": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForBusinessConsultantJob(true); + break; + case "security": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForSecurityJob(true); + break; + case "agent": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForAgentJob(true); + break; + case "employee": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForEmployeeJob(true); + break; + case "part-time employee": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForPartTimeEmployeeJob(true); + break; + case "waiter": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForWaiterJob(true); + break; + case "part-time waiter": + res = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].applyForPartTimeWaiterJob(true); + break; + default: + workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed"); + return false; + } + //The Player object's applyForJob function can return string with special error messages + if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(res)) { + workerScript.scriptRef.log(res); + return false; + } + if (res) { + workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].companyPosition.positionName); + } else { + workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field."); + } + return res; + }, + getCompanyRep(companyName) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + var company = __WEBPACK_IMPORTED_MODULE_4__Company_js__["a" /* Companies */][companyName]; + if (company == null || !(company instanceof __WEBPACK_IMPORTED_MODULE_4__Company_js__["b" /* Company */])) { + workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName); + return -1; + } + return company.playerReputation; + }, + checkFactionInvitations() { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + //Make a copy of Player.factionInvitations + return __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.slice(); + }, + joinFaction(name) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(name)) { + workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist."); + return false; + } + + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.includes(name)) { + workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); + return false; + } + + var index = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.indexOf(name); + if (index === -1) { + //Redundant and should never happen... + workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factionInvitations.splice(index, 1); + var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][name]; + Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["h" /* joinFaction */])(fac); + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); + workerScript.scriptRef.log("Joined the " + name + " faction."); + return true; + }, + workForFaction(name, type) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { + workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission."); + return; + } + + if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(name)) { + workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist."); + return false; + } + + if (!__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].factions.includes(name)) { + workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name); + return false; + } + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { + var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); + workerScript.scriptRef.log(txt); + } + + var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][name]; + //Arrays listing factions that allow each time of work + var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", + "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", + "OmniTek Incorporated", "Four Sigma", "KuaiGong International", + "Fulcrum Secret Technologies", "BitRunners", "The Black Hand", + "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum", + "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", + "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"]; + var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", + "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", + "OmniTek Incorporated", "Four Sigma", "KuaiGong International", + "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", + "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", + "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"]; + var scWkAvailable = ["ECorp", "MegaCorp", + "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", + "OmniTek Incorporated", "Four Sigma", "KuaiGong International", + "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum", + "Ishima", "Volhaven", "Speakers for the Dead", + "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"]; + + switch (type.toLowerCase()) { + case "hacking": + case "hacking contracts": + case "hackingcontracts": + if (!hackAvailable.includes(fac.name)) { + workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startFactionHackWork(fac); + workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name); + return true; + case "field": + case "fieldwork": + case "field work": + if (!fdWkAvailable.includes(fac.name)) { + workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startFactionFieldWork(fac); + workerScript.scriptRef.log("Started carrying out field missions for " + fac.name); + return true; + case "security": + case "securitywork": + case "security work": + if (!scWkAvailable.includes(fac.name)) { + workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startFactionSecurityWork(fac); + workerScript.scriptRef.log("Started serving as security details for " + fac.name); + return true; + default: + workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type); + } + return true; + }, + getFactionRep(name) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return -1; + } + } + + if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(name)) { + workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist."); + return -1; + } + + return __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][name].playerReputation; + }, + createProgram(name) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { + workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission."); + return; + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { + var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); + workerScript.scriptRef.log(txt); + } + + switch(name.toLowerCase()) { + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].NukeProgram.toLowerCase(): + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].NukeProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes, 1); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 50) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create BruteSSH (level 50 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].BruteSSHProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes * 2, 50); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 100) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create FTPCrack (level 100 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].FTPCrackProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 100); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 250) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create relaySMTP (level 250 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 250); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 500) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create HTTPWorm (level 500 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].HTTPWormProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer4Hours, 500); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 750) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create SQLInject (level 750 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].SQLInjectProgram, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours, 750); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 75) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV1 (level 75 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV1, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 75); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 400) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV2 (level 400 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].DeepscanV2, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 400); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].ServerProfiler.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 75) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create ServerProfiler (level 75 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].ServerProfiler, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 75); + break; + case __WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].AutoLink.toLowerCase(): + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].hacking_skill < 25) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create AutoLink (level 25 req)"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_6__CreateProgram_js__["a" /* Programs */].AutoLink, __WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 25); + break; + default: + workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name); + return false; + } + workerScript.scriptRef.log("Began creating program: " + name); + return true; + }, + commitCrime : function(crime) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return; + } + } + if (__WEBPACK_IMPORTED_MODULE_13__Missions_js__["c" /* inMission */]) { + workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission."); + return; + } + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].isWorking) { + var txt = __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].singularityStopWork(); + workerScript.scriptRef.log(txt); + } + + //Set Location to slums + switch(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].city) { + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Aevum: + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].AevumSlums; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Chongqing: + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].ChongqingSlums; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12: + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Sector12Slums; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].NewTokyo: + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].NewTokyoSlums; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Ishima: + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].IshimaSlums; + break; + case __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].Volhaven: + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_11__Location_js__["a" /* Locations */].VolhavenSlums; + break; + default: + console.log("Invalid Player.city value"); + } + + crime = crime.toLowerCase(); + if (crime.includes("shoplift")) { + workerScript.scriptRef.log("Attempting to shoplift..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["k" /* commitShopliftCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("rob") && crime.includes("store")) { + workerScript.scriptRef.log("Attempting to rob a store..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["j" /* commitRobStoreCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("mug")) { + workerScript.scriptRef.log("Attempting to mug someone..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["i" /* commitMugCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("larceny")) { + workerScript.scriptRef.log("Attempting to commit larceny..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["h" /* commitLarcenyCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("drugs")) { + workerScript.scriptRef.log("Attempting to deal drugs..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["c" /* commitDealDrugsCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("bond") && crime.includes("forge")) { + workerScript.scriptRef.log("Attempting to forge corporate bonds..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["b" /* commitBondForgeryCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("traffick") && crime.includes("arms")) { + workerScript.scriptRef.log("Attempting to traffick illegal arms..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["l" /* commitTraffickArmsCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("homicide")) { + workerScript.scriptRef.log("Attempting to commit homicide..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["f" /* commitHomicideCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("grand") && crime.includes("auto")) { + workerScript.scriptRef.log("Attempting to commit grand theft auto..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["d" /* commitGrandTheftAutoCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("kidnap")) { + workerScript.scriptRef.log("Attempting to kidnap and ransom a high-profile target..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["g" /* commitKidnapCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else if (crime.includes("assassinate")) { + workerScript.scriptRef.log("Attempting to assassinate a high-profile target..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["a" /* commitAssassinationCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}) + } else if (crime.includes("heist")) { + workerScript.scriptRef.log("Attempting to pull off a heist..."); + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["e" /* commitHeistCrime */])(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].CrimeSingFnDivider, {workerscript: workerScript}); + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid crime passed into commitCrime(): " + crime); + } + }, + getCrimeChance(crime) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return; + } + } + + crime = crime.toLowerCase(); + if (crime.includes("shoplift")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["w" /* determineCrimeChanceShoplift */])(); + } else if (crime.includes("rob") && crime.includes("store")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["v" /* determineCrimeChanceRobStore */])(); + } else if (crime.includes("mug")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["u" /* determineCrimeChanceMug */])(); + } else if (crime.includes("larceny")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["t" /* determineCrimeChanceLarceny */])(); + } else if (crime.includes("drugs")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["o" /* determineCrimeChanceDealDrugs */])(); + } else if (crime.includes("bond") && crime.includes("forge")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["n" /* determineCrimeChanceBondForgery */])(); + } else if (crime.includes("traffick") && crime.includes("arms")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["x" /* determineCrimeChanceTraffickArms */])(); + } else if (crime.includes("homicide")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["r" /* determineCrimeChanceHomicide */])(); + } else if (crime.includes("grand") && crime.includes("auto")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["p" /* determineCrimeChanceGrandTheftAuto */])(); + } else if (crime.includes("kidnap")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["s" /* determineCrimeChanceKidnap */])(); + } else if (crime.includes("assassinate")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["m" /* determineCrimeChanceAssassination */])(); + } else if (crime.includes("heist")) { + return Object(__WEBPACK_IMPORTED_MODULE_3__Crimes_js__["q" /* determineCrimeChanceHeist */])(); + } else { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime); + } + }, + getOwnedAugmentations(purchased=false) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return []; + } + } + var res = []; + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations.length; ++i) { + res.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations[i].name); + } + if (purchased) { + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations.length; ++i) { + res.push(__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations[i].name); + } + } + return res; + }, + getAugmentationsFromFaction(facname) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return []; + } + } + + if (!Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["d" /* factionExists */])(facname)) { + workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname); + return []; + } + + var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][facname]; + var res = []; + for (var i = 0; i < fac.augmentations.length; ++i) { + res.push(fac.augmentations[i]); + } + return res; + }, + getAugmentationCost(name) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + + if (!Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(name)) { + workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name); + return [-1, -1]; + } + + var aug = __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][name]; + return [aug.baseRepRequirement, aug.baseCost]; + }, + purchaseAugmentation(faction, name) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + + var fac = __WEBPACK_IMPORTED_MODULE_9__Faction_js__["b" /* Factions */][faction]; + if (fac == null || !(fac instanceof __WEBPACK_IMPORTED_MODULE_9__Faction_js__["a" /* Faction */])) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction); + return false; + } + + if (!fac.augmentations.includes(name)) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation"); + return false; + } + + var aug = __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][name]; + if (aug == null || !(aug instanceof __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["a" /* Augmentation */])) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name); + return false; + } + + var isNeuroflux = false; + if (aug.name === __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) { + isNeuroflux = true; + } + + if (!isNeuroflux) { + for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations.length; ++j) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations[j].name === aug.name) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); + return false; + } + } + for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations.length; ++j) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].augmentations[j].name === aug.name) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); + return false; + } + } + } + + if (fac.playerReputation < aug.baseRepRequirement) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name); + return false; + } + + var res = Object(__WEBPACK_IMPORTED_MODULE_9__Faction_js__["k" /* purchaseAugmentation */])(aug, fac, true); + workerScript.scriptRef.log(res); + if (Object(__WEBPACK_IMPORTED_MODULE_29__utils_StringHelperFunctions_js__["f" /* isString */])(res) && res.startsWith("You purchased")) { + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); + return true; + } else { + return false; + } + }, + installAugmentations(cbScript) { + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(__WEBPACK_IMPORTED_MODULE_23__NetscriptEvaluator_js__["d" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + + if (__WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].queuedAugmentations.length === 0) { + workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed"); + return false; + } + __WEBPACK_IMPORTED_MODULE_14__Player_js__["a" /* Player */].gainIntelligenceExp(__WEBPACK_IMPORTED_MODULE_5__Constants_js__["a" /* CONSTANTS */].IntelligenceSingFnBaseExpGain); + workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed"); + Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["h" /* installAugmentations */])(cbScript); + return true; + } } } @@ -27272,19 +27272,19 @@ function yesNoTxtInpBoxCreate(txt) { /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return postNetburnerText; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return post; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Terminal; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Alias_js__ = __webpack_require__(44); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Alias_js__ = __webpack_require__(45); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__ = __webpack_require__(15); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__DarkWeb_js__ = __webpack_require__(45); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__DarkWeb_js__ = __webpack_require__(44); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__HelpText_js__ = __webpack_require__(71); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__ = __webpack_require__(27); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__HelpText_js__ = __webpack_require__(68); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__ = __webpack_require__(26); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Literature_js__ = __webpack_require__(46); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Message_js__ = __webpack_require__(24); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__NetscriptEvaluator_js__ = __webpack_require__(38); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__NetscriptEvaluator_js__ = __webpack_require__(36); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__RedPill_js__ = __webpack_require__(37); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__RedPill_js__ = __webpack_require__(33); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__Script_js__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__Server_js__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__SpecialServerIps_js__ = __webpack_require__(12); @@ -29029,12 +29029,12 @@ let Terminal = { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initMessages; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Message; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__ = __webpack_require__(20); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__CreateProgram_js__ = __webpack_require__(15); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Missions_js__ = __webpack_require__(26); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__CreateProgram_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Missions_js__ = __webpack_require__(27); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__RedPill_js__ = __webpack_require__(37); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__RedPill_js__ = __webpack_require__(33); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(15); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__ = __webpack_require__(8); @@ -29239,13 +29239,13 @@ function initMessages() { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addActiveScriptsItem; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deleteActiveScriptsItem; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return updateActiveScriptsItems; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__NetscriptWorker_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__NetscriptWorker_js__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Server_js__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_LogBox_js__ = __webpack_require__(30); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_numeral_min_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_numeral_min_js__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_6__utils_numeral_min_js__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__ = __webpack_require__(4); @@ -29535,6 +29535,681 @@ function updateActiveScriptsText(workerscript, item, statsEl=null) { /* 26 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return iTutorialSteps; }); +/* unused harmony export iTutorialEnd */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return iTutorialStart; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return iTutorialNextStep; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return currITutorialStep; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return iTutorialIsRunning; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__engine_js__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_DialogBox_js__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__ = __webpack_require__(2); + + + + +/* InteractiveTutorial.js */ +let iTutorialSteps = { + Start: "Start", + GoToCharacterPage: "Click on the Character page menu link", + CharacterPage: "Introduction to Character page", + CharacterGoToTerminalPage: "Click on the Terminal link", + TerminalIntro: "Introduction to terminal interface", + TerminalHelp: "Using the help command to display all options in terminal", + TerminalLs: "Use the ls command to show all programs/scripts. Right now we have NUKE.exe", + TerminalScan: "Using the scan command to display all available connections", + TerminalScanAnalyze1: "Use the scan-analyze command to show hacking related information", + TerminalScanAnalyze2: "Use the scan-analyze command with a depth of 3", + TerminalConnect: "Using the telnet/connect command to connect to another server", + TerminalAnalyze: "Use the analyze command to display details about this server", + TerminalNuke: "Use the NUKE Program to gain root access to a server", + TerminalManualHack: "Use the hack command to manually hack a server", + TerminalHackingMechanics: "Briefly explain hacking mechanics", + TerminalCreateScript: "Create a script using nano", + TerminalTypeScript: "This occurs in the Script Editor page...type the script then save and close", + TerminalFree: "Use the free command to check RAM", + TerminalRunScript: "Use the run command to run a script", + TerminalGoToActiveScriptsPage: "Go to the ActiveScriptsPage", + ActiveScriptsPage: "Introduction to the Active Scripts Page", + ActiveScriptsToTerminal: "Go from Active Scripts Page Back to Terminal", + TerminalTailScript: "Use the tail command to show a script's logs", + GoToHacknetNodesPage: "Go to the Hacknet Nodes page", + HacknetNodesIntroduction: "Introduction to Hacknet Nodesm and have user purchase one", + HacknetNodesGoToWorldPage: "Go to the world page", + WorldDescription: "Tell the user to explore..theres a lot of different stuff to do out there", + TutorialPageInfo: "The tutorial page contains a lot of info on different subjects", + End: "End", +} + +var currITutorialStep = iTutorialSteps.Start; +var iTutorialIsRunning = false; + +function iTutorialStart() { + //Don't autosave during this interactive tutorial + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].Counters.autoSaveCounter = 999000000000; + console.log("Interactive Tutorial started"); + currITutorialStep = iTutorialSteps.Start; + iTutorialIsRunning = true; + + document.getElementById("interactive-tutorial-container").style.display = "block"; + + iTutorialEvaluateStep(); + + //Exit tutorial button + var exitButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-exit"); + exitButton.addEventListener("click", function() { + iTutorialEnd(); + return false; + }); + + //Back button + var backButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-back"); + backButton.style.display = "none"; + backButton.addEventListener("click", function() { + iTutorialPrevStep(); + return false; + }); +} + +function iTutorialEvaluateStep() { + if (!iTutorialIsRunning) {console.log("Interactive Tutorial not running"); return;} + switch(currITutorialStep) { + case iTutorialSteps.Start: + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent(); + + iTutorialSetText("Welcome to Bitburner, a cyberpunk-themed incremental RPG! " + + "The game takes place in a dark, dystopian future...The year is 2077...

" + + "This tutorial will show you the basics of the game. " + + "You may skip the tutorial at any time."); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "inline-block"; + next.addEventListener("click", function() { + iTutorialNextStep(); + return false; + }); + break; + case iTutorialSteps.GoToCharacterPage: + iTutorialSetText("Let's start by heading to the Stats page. Click the 'Stats' tab on " + + "the main navigation menu (left-hand side of the screen)"); + + //No next button + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "none"; + + //Flash Character tab + document.getElementById("stats-menu-link").setAttribute("class", "flashing-button"); + + //Initialize everything necessary to open the "Character" page + var charaterMainMenuButton = document.getElementById("stats-menu-link"); + charaterMainMenuButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadCharacterContent(); + iTutorialNextStep(); //Opening the character page will go to the next step + Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stats-menu-link"); + return false; + }); + break; + case iTutorialSteps.CharacterPage: + iTutorialSetText("The Stats page shows a lot of important information about your progress, " + + "such as your skills, money, and bonuses/multipliers. ") + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "inline-block"; + next.addEventListener("click", function() { + iTutorialNextStep(); + return false; + }); + break; + case iTutorialSteps.CharacterGoToTerminalPage: + iTutorialSetText("Let's head to your computer's terminal by clicking the 'Terminal' tab on the " + + "main navigation menu."); + //No next button + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "none"; + + document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button"); + + //Initialize everything necessary to open the 'Terminal' Page + var terminalMainMenuButton = document.getElementById("terminal-menu-link"); + terminalMainMenuButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent(); + iTutorialNextStep(); + Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link"); + return false; + }); + break; + case iTutorialSteps.TerminalIntro: + iTutorialSetText("The Terminal is used to interface with your home computer as well as " + + "all of the other machines around the world."); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "inline-block"; + next.addEventListener("click", function() { + iTutorialNextStep(); + return false; + }); + break; + case iTutorialSteps.TerminalHelp: + iTutorialSetText("Let's try it out. Start by entering the 'help' command into the Terminal " + + "(Don't forget to press Enter after typing the command)"); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "none"; + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalLs: + iTutorialSetText("The 'help' command displays a list of all available Terminal commands, how to use them, " + + "and a description of what they do.

Let's try another command. Enter the 'ls' command"); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalScan: + iTutorialSetText("'ls' is a basic command that shows all of the contents (programs/scripts) " + + "on the computer. Right now, it shows that you have a program called 'NUKE.exe' on your computer. " + + "We'll get to what this does later.

Using your home computer's terminal, you can connect " + + "to other machines throughout the world. Let's do that now by first entering " + + "the 'scan' command. "); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalScanAnalyze1: + iTutorialSetText("The 'scan' command shows all available network connections. In other words, " + + "it displays a list of all servers that can be connected to from your " + + "current machine. A server is identified by either its IP or its hostname.

" + + "That's great and all, but there's so many servers. Which one should you go to? " + + "The 'scan-analyze' command gives some more detailed information about servers on the " + + "network. Try it now"); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalScanAnalyze2: + iTutorialSetText("You just ran 'scan-analyze' with a depth of one. This command shows more detailed " + + "information about each server that you can connect to (servers that are a distance of " + + "one node away).

It is also possible to run 'scan-analyze' with " + + "a higher depth. Let's try a depth of two with the following command: 'scan-analyze 2'.") + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalConnect: + iTutorialSetText("Now you can see information about all servers that are up to two nodes away, as well " + + "as figure out how to navigate to those servers through the network. You can only connect to " + + "a server that is one node away. To connect to a machine, use the 'connect [ip/hostname]' command. You can type in " + + "the ip or the hostname, but dont use both.

" + + "From the results of the 'scan-analyze' command, we can see that the 'foodnstuff' server is " + + "only one node away. Let's connect so it now using: 'connect foodnstuff'"); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalAnalyze: + iTutorialSetText("You are now connected to another machine! What can you do now? You can hack it!

In the year 2077, currency has " + + "become digital and decentralized. People and corporations store their money " + + "on servers and computers. Using your hacking abilities, you can hack servers " + + "to steal money and gain experience.

" + + "Before you try to hack a server, you should run diagnostics using the 'analyze' command"); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalNuke: + iTutorialSetText("When the 'analyze' command finishes running it will show useful information " + + "about hacking the server.

For this server, the required hacking skill is only 1, " + + "which means you can hack it right now. However, in order to hack a server " + + "you must first gain root access. The 'NUKE.exe' program that we saw earlier on your " + + "home computer is a virus that will grant you root access to a machine if there are enough " + + "open ports.

The 'analyze' results shows that there do not need to be any open ports " + + "on this machine for the NUKE virus to work, so go ahead and run the virus using the " + + "'run NUKE.exe' command."); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalManualHack: + iTutorialSetText("You now have root access! You can hack the server using the 'hack' command. " + + "Try doing that now."); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalHackingMechanics: + iTutorialSetText("You are now attempting to hack the server. Note that performing a hack takes time and " + + "only has a certain percentage chance " + + "of success. This time and success chance is determined by a variety of factors, including " + + "your hacking skill and the server's security level.

" + + "If your attempt to hack the server is successful, you will steal a certain percentage " + + "of the server's total money. This percentage is affected by your hacking skill and " + + "the server's security level.

The amount of money on a server is not limitless. So, if " + + "you constantly hack a server and deplete its money, then you will encounter " + + "diminishing returns in your hacking."); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "inline-block"; + next.addEventListener("click", function() { + iTutorialNextStep(); + return false; + }); + break; + case iTutorialSteps.TerminalCreateScript: + iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " + + "you don't want to be hacking manually the entire time. You can automate your hacking " + + "by writing scripts!

To create a new script or edit an existing one, you can use the 'nano' " + + "command. Scripts must end with the '.script' extension. Let's make a script now by " + + "entering 'nano foodnstuff.script' after the hack command finishes running (Sidenote: Pressing ctrl + c" + + " will end a command like hack early)"); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "none"; + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalTypeScript: + iTutorialSetText("This is the script editor. You can use it to program your scripts. Scripts are " + + "written in the Netscript language, a programming language created for " + + "this game. There are details about the Netscript language in the documentation, which " + + "can be accessed in the 'Tutorial' tab on the main navigation menu. I highly suggest you check " + + "it out after this tutorial. For now, just copy " + + "and paste the following code into the script editor:

" + + "while(true) {
" + + "  hack('foodnstuff');
" + + "}

" + + "For anyone with basic programming experience, this code should be straightforward. " + + "This script will continuously hack the 'foodnstuff' server.

" + + "To save and close the script editor, press the button in the bottom left, or press ctrl + b."); + //next step triggered in saveAndCloseScriptEditor() (Script.js) + break; + case iTutorialSteps.TerminalFree: + iTutorialSetText("Now we'll run the script. Scripts require a certain amount of RAM to run, and can be " + + "run on any machine which you have root access to. Different servers have different " + + "amounts of RAM. You can also purchase more RAM for your home server.

To check how much " + + "RAM is available on this machine, enter the 'free' command."); + //next step triggered by terminal commmand + break; + case iTutorialSteps.TerminalRunScript: + iTutorialSetText("We have 8GB of free RAM on this machine, which is enough to run our " + + "script. Let's run our script using 'run foodnstuff.script'."); + //next step triggered by terminal commmand + break; + case iTutorialSteps.TerminalGoToActiveScriptsPage: + iTutorialSetText("Your script is now running! The script might take a few seconds to 'fully start up'. " + + "Your scripts will continuously run in the background and will automatically stop if " + + "the code ever completes (the 'foodnstuff.script' will never complete because it " + + "runs an infinite loop).

These scripts can passively earn you income and hacking experience. " + + "Your scripts will also earn money and experience while you are offline, although at a " + + "much slower rate.

" + + "Let's check out some statistics for our running scripts by clicking the " + + "'Active Scripts' link in the main navigation menu."); + document.getElementById("active-scripts-menu-link").setAttribute("class", "flashing-button"); + var activeScriptsMainMenuButton = document.getElementById("active-scripts-menu-link"); + activeScriptsMainMenuButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadActiveScriptsContent(); + iTutorialNextStep(); + Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("active-scripts-menu-link"); + return false; + }); + break; + case iTutorialSteps.ActiveScriptsPage: + iTutorialSetText("This page displays stats/information about all of your scripts that are " + + "running across every existing server. You can use this to gauge how well " + + "your scripts are doing. Let's go back to the Terminal now using the 'Terminal'" + + "link."); + document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button"); + //Initialize everything necessary to open the 'Terminal' Page + var terminalMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link"); + terminalMainMenuButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent(); + iTutorialNextStep(); + Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link"); + return false; + }); + break; + case iTutorialSteps.ActiveScriptsToTerminal: + iTutorialSetText("One last thing about scripts, each active script contains logs that detail " + + "what it's doing. We can check these logs using the 'tail' command. Do that " + + "now for the script we just ran by typing 'tail foodnstuff.script'"); + //next step triggered by terminal command + break; + case iTutorialSteps.TerminalTailScript: + iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " + + "just started running...but check back again in a few minutes!

" + + "This pretty much covers the basics of hacking. To learn more about writing " + + "scripts using the Netscript language, select the 'Tutorial' link in the " + + "main navigation menu to look at the documentation. For now, let's move on " + + "to something else!"); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "inline-block"; + next.addEventListener("click", function() { + iTutorialNextStep(); + return false; + }); + break; + case iTutorialSteps.GoToHacknetNodesPage: + iTutorialSetText("Hacking is not the only way to earn money. One other way to passively " + + "earn money is by purchasing and upgrading Hacknet Nodes. Let's go to " + + "the 'Hacknet Nodes' page through the main navigation menu now."); + document.getElementById("hacknet-nodes-menu-link").setAttribute("class", "flashing-button"); + var hacknetNodesButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-menu-link"); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "none"; + hacknetNodesButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadHacknetNodesContent(); + iTutorialNextStep(); + Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-menu-link"); + return false; + }); + break; + case iTutorialSteps.HacknetNodesIntroduction: + iTutorialSetText("From this page you can purchase new Hacknet Nodes and upgrade your " + + "existing ones. Let's purchase a new one now."); + //Next step triggered by purchaseHacknet() (HacknetNode.js) + break; + case iTutorialSteps.HacknetNodesGoToWorldPage: + iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " + + "earn you money over time, both online and offline. When you get enough " + + " money, you can upgrade " + + "your newly-purchased Hacknet Node below.

" + + "Let's go to the 'City' page through the main navigation menu."); + document.getElementById("city-menu-link").setAttribute("class", "flashing-button"); + var worldButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("city-menu-link"); + worldButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadWorldContent(); + iTutorialNextStep(); + Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("city-menu-link"); + return false; + }); + break; + case iTutorialSteps.WorldDescription: + iTutorialSetText("This page lists all of the different locations you can currently " + + "travel to. Each location has something that you can do. " + + "There's a lot of content out in the world, make sure " + + "you explore and discover!

" + + "Lastly, click on the 'Tutorial' link in the main navigation menu."); + document.getElementById("tutorial-menu-link").setAttribute("class", "flashing-button"); + var tutorialButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("tutorial-menu-link"); + tutorialButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTutorialContent(); + iTutorialNextStep(); + Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("tutorial-menu-link"); + return false; + }); + break; + + case iTutorialSteps.TutorialPageInfo: + iTutorialSetText("This page contains a lot of different documentation about the game's " + + "content and mechanics. I know it's a lot, but I highly suggest you read " + + "(or at least skim) through this before you start playing. That's the end of the tutorial. " + + "Hope you enjoy the game!"); + var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); + next.style.display = "inline-block"; + next.innerHTML = "Finish Tutorial"; + + var backButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-back"); + backButton.style.display = "none"; + + next.addEventListener("click", function() { + iTutorialNextStep(); + return false; + }); + break; + case iTutorialSteps.End: + iTutorialEnd(); + break; + default: + throw new Error("Invalid tutorial step"); + } +} + +//Go to the next step and evaluate it +function iTutorialNextStep() { + switch(currITutorialStep) { + case iTutorialSteps.Start: + currITutorialStep = iTutorialSteps.GoToCharacterPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.GoToCharacterPage: + document.getElementById("stats-menu-link").removeAttribute("class"); + currITutorialStep = iTutorialSteps.CharacterPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.CharacterPage: + currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.CharacterGoToTerminalPage: + document.getElementById("terminal-menu-link").removeAttribute("class"); + currITutorialStep = iTutorialSteps.TerminalIntro; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalIntro: + currITutorialStep = iTutorialSteps.TerminalHelp; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalHelp: + currITutorialStep = iTutorialSteps.TerminalLs; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalLs: + currITutorialStep = iTutorialSteps.TerminalScan; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalScan: + currITutorialStep = iTutorialSteps.TerminalScanAnalyze1; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalScanAnalyze1: + currITutorialStep = iTutorialSteps.TerminalScanAnalyze2; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalScanAnalyze2: + currITutorialStep = iTutorialSteps.TerminalConnect; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalConnect: + currITutorialStep = iTutorialSteps.TerminalAnalyze; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalAnalyze: + currITutorialStep = iTutorialSteps.TerminalNuke; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalNuke: + currITutorialStep = iTutorialSteps.TerminalManualHack; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalManualHack: + currITutorialStep = iTutorialSteps.TerminalHackingMechanics; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalHackingMechanics: + currITutorialStep = iTutorialSteps.TerminalCreateScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalCreateScript: + currITutorialStep = iTutorialSteps.TerminalTypeScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalTypeScript: + currITutorialStep = iTutorialSteps.TerminalFree; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalFree: + currITutorialStep = iTutorialSteps.TerminalRunScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalRunScript: + currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalGoToActiveScriptsPage: + document.getElementById("active-scripts-menu-link").removeAttribute("class"); + currITutorialStep = iTutorialSteps.ActiveScriptsPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.ActiveScriptsPage: + document.getElementById("terminal-menu-link").removeAttribute("class"); + currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.ActiveScriptsToTerminal: + currITutorialStep = iTutorialSteps.TerminalTailScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalTailScript: + currITutorialStep = iTutorialSteps.GoToHacknetNodesPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.GoToHacknetNodesPage: + document.getElementById("hacknet-nodes-menu-link").removeAttribute("class"); + currITutorialStep = iTutorialSteps.HacknetNodesIntroduction; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.HacknetNodesIntroduction: + currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.HacknetNodesGoToWorldPage: + document.getElementById("city-menu-link").removeAttribute("class"); + currITutorialStep = iTutorialSteps.WorldDescription; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.WorldDescription: + document.getElementById("tutorial-menu-link").removeAttribute("class"); + currITutorialStep = iTutorialSteps.TutorialPageInfo; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TutorialPageInfo: + currITutorialStep = iTutorialSteps.End; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.End: + break; + default: + throw new Error("Invalid tutorial step"); + } +} + +//Go to previous step and evaluate +function iTutorialPrevStep() { + switch(currITutorialStep) { + case iTutorialSteps.Start: + currITutorialStep = iTutorialSteps.Start; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.GoToCharacterPage: + currITutorialStep = iTutorialSteps.Start; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.CharacterPage: + currITutorialStep = iTutorialSteps.GoToCharacterPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.CharacterGoToTerminalPage: + currITutorialStep = iTutorialSteps.CharacterPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalIntro: + currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalHelp: + currITutorialStep = iTutorialSteps.TerminalIntro; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalLs: + currITutorialStep = iTutorialSteps.TerminalHelp; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalScan: + currITutorialStep = iTutorialSteps.TerminalLs; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalConnect: + currITutorialStep = iTutorialSteps.TerminalScan; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalAnalyze: + currITutorialStep = iTutorialSteps.TerminalConnect; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalNuke: + currITutorialStep = iTutorialSteps.TerminalAnalyze; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalManualHack: + currITutorialStep = iTutorialSteps.TerminalNuke; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalHackingMechanics: + currITutorialStep = iTutorialSteps.TerminalManualHack; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalCreateScript: + currITutorialStep = iTutorialSteps.TerminalManualHack; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalTypeScript: + currITutorialStep = iTutorialSteps.TerminalCreateScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalFree: + currITutorialStep = iTutorialSteps.TerminalTypeScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalRunScript: + currITutorialStep = iTutorialSteps.TerminalFree; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalGoToActiveScriptsPage: + currITutorialStep = iTutorialSteps.TerminalRunScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.ActiveScriptsPage: + currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.ActiveScriptsToTerminal: + currITutorialStep = iTutorialSteps.ActiveScriptsPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TerminalTailScript: + currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.GoToHacknetNodesPage: + currITutorialStep = iTutorialSteps.TerminalTailScript; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.HacknetNodesIntroduction: + currITutorialStep = iTutorialSteps.GoToHacknetNodesPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.HacknetNodesGoToWorldPage: + currITutorialStep = iTutorialSteps.HacknetNodesIntroduction; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.WorldDescription: + currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.TutorialPageInfo: + currITutorialStep = iTutorialSteps.WorldDescription; + iTutorialEvaluateStep(); + break; + case iTutorialSteps.End: + break; + default: + throw new Error("Invalid tutorial step"); + } +} + +function iTutorialEnd() { + //Re-enable auto save + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].Counters.autoSaveCounter = 300; + console.log("Ending interactive tutorial"); + __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].init(); + currITutorialStep = iTutorialSteps.End; + iTutorialIsRunning = false; + document.getElementById("interactive-tutorial-container").style.display = "none"; + Object(__WEBPACK_IMPORTED_MODULE_1__utils_DialogBox_js__["a" /* dialogBoxCreate */])("If you are new to the game, the following links may be useful for you!

" + + "Getting Started Guide" + + "Wiki"); +} + +function iTutorialSetText(txt) { + var textBox = document.getElementById("interactive-tutorial-text"); + if (textBox == null) {throw new Error("Could not find text box"); return;} + textBox.innerHTML = txt; + textBox.parentElement.scrollTop = 0; // this resets scroll position +} + + + + +/***/ }), +/* 27 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + "use strict"; /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HackingMission; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return inMission; }); @@ -29542,12 +30217,12 @@ function updateActiveScriptsText(workerscript, item, statsEl=null) { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return currMission; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Faction_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Faction_js__ = __webpack_require__(11); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_jsplumb__ = __webpack_require__(53); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_jsplumb__ = __webpack_require__(69); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_jsplumb___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7_jsplumb__); @@ -30984,682 +31659,1375 @@ HackingMission.prototype.finishMission = function(win) { /* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9))) /***/ }), -/* 27 */ +/* 28 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return iTutorialSteps; }); -/* unused harmony export iTutorialEnd */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return iTutorialStart; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return iTutorialNextStep; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return currITutorialStep; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return iTutorialIsRunning; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__ = __webpack_require__(2); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return StockMarket; }); +/* unused harmony export StockSymbols */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return SymbolToStockMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return initStockSymbols; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return initStockMarket; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return initSymbolToStockMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return stockMarketCycle; }); +/* unused harmony export buyStock */ +/* unused harmony export sellStock */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return shortStock; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return sellShort; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return updateStockPrices; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return displayStockMarketContent; }); +/* unused harmony export updateStockTicker */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return updateStockPlayerPosition; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return loadStockMarket; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return setStockMarketContentCreated; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return placeOrder; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return cancelOrder; }); +/* unused harmony export Order */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OrderTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PositionTypes; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Location_js__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__ = __webpack_require__(22); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__ = __webpack_require__(2); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__ = __webpack_require__(8); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js__ = __webpack_require__(19); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__ = __webpack_require__(4); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__ = __webpack_require__(17); -/* InteractiveTutorial.js */ -let iTutorialSteps = { - Start: "Start", - GoToCharacterPage: "Click on the Character page menu link", - CharacterPage: "Introduction to Character page", - CharacterGoToTerminalPage: "Click on the Terminal link", - TerminalIntro: "Introduction to terminal interface", - TerminalHelp: "Using the help command to display all options in terminal", - TerminalLs: "Use the ls command to show all programs/scripts. Right now we have NUKE.exe", - TerminalScan: "Using the scan command to display all available connections", - TerminalScanAnalyze1: "Use the scan-analyze command to show hacking related information", - TerminalScanAnalyze2: "Use the scan-analyze command with a depth of 3", - TerminalConnect: "Using the telnet/connect command to connect to another server", - TerminalAnalyze: "Use the analyze command to display details about this server", - TerminalNuke: "Use the NUKE Program to gain root access to a server", - TerminalManualHack: "Use the hack command to manually hack a server", - TerminalHackingMechanics: "Briefly explain hacking mechanics", - TerminalCreateScript: "Create a script using nano", - TerminalTypeScript: "This occurs in the Script Editor page...type the script then save and close", - TerminalFree: "Use the free command to check RAM", - TerminalRunScript: "Use the run command to run a script", - TerminalGoToActiveScriptsPage: "Go to the ActiveScriptsPage", - ActiveScriptsPage: "Introduction to the Active Scripts Page", - ActiveScriptsToTerminal: "Go from Active Scripts Page Back to Terminal", - TerminalTailScript: "Use the tail command to show a script's logs", - GoToHacknetNodesPage: "Go to the Hacknet Nodes page", - HacknetNodesIntroduction: "Introduction to Hacknet Nodesm and have user purchase one", - HacknetNodesGoToWorldPage: "Go to the world page", - WorldDescription: "Tell the user to explore..theres a lot of different stuff to do out there", - TutorialPageInfo: "The tutorial page contains a lot of info on different subjects", - End: "End", + + + + + + + + + + +/* StockMarket.js */ +function Stock(name, symbol, mv, b, otlkMag, initPrice=10000) { + this.symbol = symbol; + this.name = name; + this.price = initPrice; + + this.playerShares = 0; + this.playerAvgPx = 0; + this.playerShortShares = 0; + this.playerAvgShortPx = 0; + this.mv = mv; + this.b = b; + this.otlkMag = otlkMag; + + this.posTxtEl = null; } -var currITutorialStep = iTutorialSteps.Start; -var iTutorialIsRunning = false; +Stock.prototype.toJSON = function() { + return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Stock", this); +} -function iTutorialStart() { - //Don't autosave during this interactive tutorial - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].Counters.autoSaveCounter = 999000000000; - console.log("Interactive Tutorial started"); - currITutorialStep = iTutorialSteps.Start; - iTutorialIsRunning = true; +Stock.fromJSON = function(value) { + return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Stock, value.data); +} - document.getElementById("interactive-tutorial-container").style.display = "block"; +__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */].constructors.Stock = Stock; - iTutorialEvaluateStep(); +var OrderTypes = { + LimitBuy: "Limit Buy Order", + LimitSell: "Limit Sell Order", + StopBuy: "Stop Buy Order", + StopSell: "Stop Sell Order" +} - //Exit tutorial button - var exitButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-exit"); - exitButton.addEventListener("click", function() { - iTutorialEnd(); +var PositionTypes = { + Long: "L", + Short: "S" +} + +function placeOrder(stock, shares, price, type, position, workerScript=null) { + var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); + var order = new Order(stock, shares, price, type, position); + if (isNaN(shares) || isNaN(price)) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); + } else { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); + } + return false; + } + if (StockMarket["Orders"] == null) { + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; + } + StockMarket["Orders"][stock.symbol].push(order); + //Process to see if it should be executed immediately + processOrders(order.stock, order.type, order.pos); + updateStockOrderList(order.stock); + return true; +} + +//Returns true if successfully cancels an order, false otherwise +function cancelOrder(params, workerScript=null) { + var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); + if (StockMarket["Orders"] == null) {return false;} + if (params.order && params.order instanceof Order) { + var order = params.order; + //An 'Order' object is passed in + var stockOrders = StockMarket["Orders"][order.stock.symbol]; + for (var i = 0; i < stockOrders.length; ++i) { + if (order == stockOrders[i]) { + stockOrders.splice(i, 1); + updateStockOrderList(order.stock); + return true; + } + } + return false; + } else if (params.stock && params.shares && params.price && params.type && + params.pos && params.stock instanceof Stock) { + //Order properties are passed in. Need to look for the order + var stockOrders = StockMarket["Orders"][params.stock.symbol]; + var orderTxt = params.stock.symbol + " - " + params.shares + " @ " + + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(params.price).format('$0.000a'); + for (var i = 0; i < stockOrders.length; ++i) { + var order = stockOrders[i]; + if (params.shares === order.shares && + params.price === order.price && + params.type === order.type && + params.pos === order.pos) { + stockOrders.splice(i, 1); + updateStockOrderList(order.stock); + if (tixApi) { + workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt); + } + return true; + } + } + if (tixApi) { + workerScript.scriptRef.log("Failed to cancel order: " + orderTxt); + } + return false; + } + return false; +} + +function executeOrder(order) { + var stock = order.stock; + var orderBook = StockMarket["Orders"]; + var stockOrders = orderBook[stock.symbol]; + var res = true; + console.log("Executing the following order:"); + console.log(order); + switch (order.type) { + case OrderTypes.LimitBuy: + case OrderTypes.StopBuy: + if (order.pos === PositionTypes.Long) { + res = buyStock(order.stock, order.shares) && res; + } else if (order.pos === PositionTypes.Short) { + res = shortStock(order.stock, order.shares) && res; + } + break; + case OrderTypes.LimitSell: + case OrderTypes.StopSell: + if (order.pos === PositionTypes.Long) { + res = sellStock(order.stock, order.shares) && res; + } else if (order.pos === PositionTypes.Short) { + res = sellShort(order.stock, order.shares) && res; + } + break; + } + if (res) { + //Remove order from order book + for (var i = 0; i < stockOrders.length; ++i) { + if (order == stockOrders[i]) { + stockOrders.splice(i, 1); + updateStockOrderList(order.stock); + return; + } + } + console.log("ERROR: Could not find the following Order in Order Book: "); + console.log(order); + } else { + console.log("Order failed to execute"); + } +} + +function Order(stock, shares, price, type, position) { + this.stock = stock; + this.shares = shares; + this.price = price; + this.type = type; + this.pos = position; +} + +Order.prototype.toJSON = function() { + return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Order", this); +} + +Order.fromJSON = function(value) { + return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Order, value.data); +} + +__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */].constructors.Order = Order; + +let StockMarket = {} //Full name to stock object +let StockSymbols = {} //Full name to symbol +let SymbolToStockMap = {}; //Symbol to Stock object + +function loadStockMarket(saveString) { + if (saveString === "") { + StockMarket = {}; + } else { + StockMarket = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */]); + } +} + +function initStockSymbols() { + //Stocks for companies at which you can work + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumECorp] = "ECP"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12MegaCorp] = "MGCP"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12BladeIndustries] = "BLD"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumClarkeIncorporated] = "CLRK"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated] = "OMTK"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FourSigma] = "FSIG"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational] = "KGI"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumFulcrumTechnologies] = "FLCM"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaStormTechnologies] = "STM"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoDefComm] = "DCOMM"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenHeliosLabs] = "HLS"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoVitaLife] = "VITA"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems] = "ICRS"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12UniversalEnergy] = "UNV"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumAeroCorp] = "AERO"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems] = "OMN"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems] = "SLRS"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals] = "GPH"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaNovaMedical] = "NVMD"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumWatchdogSecurity] = "WDS"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenLexoCorp] = "LXO"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumRhoConstruction] = "RHOC"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12AlphaEnterprises] = "APHE"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities] = "SYSC"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenCompuTek] = "CTK"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumNetLinkTechnologies] = "NTLK"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaOmegaSoftware] = "OMGA"; + StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FoodNStuff] = "FNS"; + + //Stocks for other companies + StockSymbols["Sigma Cosmetics"] = "SGC"; + StockSymbols["Joes Guns"] = "JGN"; + StockSymbols["Catalyst Ventures"] = "CTYS"; + StockSymbols["Microdyne Technologies"] = "MDYN"; + StockSymbols["Titan Laboratories"] = "TITN"; +} + +function initStockMarket() { + for (var stk in StockMarket) { + if (StockMarket.hasOwnProperty(stk)) { + delete StockMarket[stk]; + } + } + + var ecorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumECorp; + var ecorpStk = new Stock(ecorp, StockSymbols[ecorp], 0.45, true, 19, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000)); + StockMarket[ecorp] = ecorpStk; + + var megacorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12MegaCorp; + var megacorpStk = new Stock(megacorp, StockSymbols[megacorp], 0.45, true, 19, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(25000, 33000)); + StockMarket[megacorp] = megacorpStk; + + var blade = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12BladeIndustries; + var bladeStk = new Stock(blade, StockSymbols[blade], 0.75, true, 13, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 22000)); + StockMarket[blade] = bladeStk; + + var clarke = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumClarkeIncorporated; + var clarkeStk = new Stock(clarke, StockSymbols[clarke], 0.7, true, 12, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 20000)); + StockMarket[clarke] = clarkeStk; + + var omnitek = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated; + var omnitekStk = new Stock(omnitek, StockSymbols[omnitek], 0.65, true, 12, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(35000, 40000)); + StockMarket[omnitek] = omnitekStk; + + var foursigma = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FourSigma; + var foursigmaStk = new Stock(foursigma, StockSymbols[foursigma], 1.05, true, 17, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(60000, 70000)); + StockMarket[foursigma] = foursigmaStk; + + var kuaigong = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational; + var kuaigongStk = new Stock(kuaigong, StockSymbols[kuaigong], 0.8, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 24000)); + StockMarket[kuaigong] = kuaigongStk; + + var fulcrum = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumFulcrumTechnologies; + var fulcrumStk = new Stock(fulcrum, StockSymbols[fulcrum], 1.25, true, 16, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(30000, 35000)); + StockMarket[fulcrum] = fulcrumStk; + + var storm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaStormTechnologies; + var stormStk = new Stock(storm, StockSymbols[storm], 0.85, true, 7, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(21000, 24000)); + StockMarket[storm] = stormStk; + + var defcomm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoDefComm; + var defcommStk = new Stock(defcomm, StockSymbols[defcomm], 0.65, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 15000)); + StockMarket[defcomm] = defcommStk; + + var helios = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenHeliosLabs; + var heliosStk = new Stock(helios, StockSymbols[helios], 0.6, true, 9, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(12000, 16000)); + StockMarket[helios] = heliosStk; + + var vitalife = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoVitaLife; + var vitalifeStk = new Stock(vitalife, StockSymbols[vitalife], 0.75, true, 7, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 12000)); + StockMarket[vitalife] = vitalifeStk; + + var icarus = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems; + var icarusStk = new Stock(icarus, StockSymbols[icarus], 0.65, true, 7.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(16000, 20000)); + StockMarket[icarus] = icarusStk; + + var universalenergy = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12UniversalEnergy; + var universalenergyStk = new Stock(universalenergy, StockSymbols[universalenergy], 0.55, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000)); + StockMarket[universalenergy] = universalenergyStk; + + var aerocorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumAeroCorp; + var aerocorpStk = new Stock(aerocorp, StockSymbols[aerocorp], 0.6, true, 6, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 15000)); + StockMarket[aerocorp] = aerocorpStk; + + var omnia = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems; + var omniaStk = new Stock(omnia, StockSymbols[omnia], 0.7, true, 4.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(9000, 12000)); + StockMarket[omnia] = omniaStk; + + var solaris = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems; + var solarisStk = new Stock(solaris, StockSymbols[solaris], 0.75, true, 8.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000)); + StockMarket[solaris] = solarisStk; + + var globalpharm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals; + var globalpharmStk = new Stock(globalpharm, StockSymbols[globalpharm], 0.6, true, 10.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000)); + StockMarket[globalpharm] = globalpharmStk; + + var nova = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaNovaMedical; + var novaStk = new Stock(nova, StockSymbols[nova], 0.75, true, 5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000)); + StockMarket[nova] = novaStk; + + var watchdog = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumWatchdogSecurity; + var watchdogStk = new Stock(watchdog, StockSymbols[watchdog], 2.5, true, 1.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500)); + StockMarket[watchdog] = watchdogStk; + + var lexocorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenLexoCorp; + var lexocorpStk = new Stock(lexocorp, StockSymbols[lexocorp], 1.25, true, 6, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500)); + StockMarket[lexocorp] = lexocorpStk; + + var rho = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumRhoConstruction; + var rhoStk = new Stock(rho, StockSymbols[rho], 0.6, true, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(3000, 6000)); + StockMarket[rho] = rhoStk; + + var alpha = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12AlphaEnterprises; + var alphaStk = new Stock(alpha, StockSymbols[alpha], 1.9, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500)); + StockMarket[alpha] = alphaStk; + + var syscore = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities; + var syscoreStk = new Stock(syscore, StockSymbols[syscore], 1.6, true, 3, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(4000, 7000)) + StockMarket[syscore] = syscoreStk; + + var computek = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenCompuTek; + var computekStk = new Stock(computek, StockSymbols[computek], 0.9, true, 4, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 5000)); + StockMarket[computek] = computekStk; + + var netlink = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumNetLinkTechnologies; + var netlinkStk = new Stock(netlink, StockSymbols[netlink], 4.2, true, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 4000)); + StockMarket[netlink] = netlinkStk; + + var omega = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaOmegaSoftware; + var omegaStk = new Stock(omega, StockSymbols[omega], 1, true, 0.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(3000, 6000)); + StockMarket[omega] = omegaStk; + + var fns = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FoodNStuff; + var fnsStk = new Stock(fns, StockSymbols[fns], 0.75, false, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 4000)); + StockMarket[fns] = fnsStk; + + var sigmacosm = "Sigma Cosmetics"; + var sigmacosmStk = new Stock(sigmacosm, StockSymbols[sigmacosm], 2.8, true, 0, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 3000)); + StockMarket[sigmacosm] = sigmacosmStk; + + var joesguns = "Joes Guns"; + var joesgunsStk = new Stock(joesguns, StockSymbols[joesguns], 3.8, true, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(500, 1000)); + StockMarket[joesguns] = joesgunsStk; + + var catalyst = "Catalyst Ventures"; + var catalystStk = new Stock(catalyst, StockSymbols[catalyst], 1.45, true, 13.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(500, 1000)); + StockMarket[catalyst] = catalystStk; + + var microdyne = "Microdyne Technologies"; + var microdyneStk = new Stock(microdyne, StockSymbols[microdyne], 0.75, true, 8, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000)); + StockMarket[microdyne] = microdyneStk; + + var titanlabs = "Titan Laboratories"; + var titanlabsStk = new Stock(titanlabs, StockSymbols[titanlabs], 0.6, true, 11, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 20000)); + StockMarket[titanlabs] = titanlabsStk; + + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; +} + +function initSymbolToStockMap() { + for (var name in StockSymbols) { + if (StockSymbols.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (stock == null) { + console.log("ERROR finding stock"); + continue; + } + var symbol = StockSymbols[name]; + SymbolToStockMap[symbol] = stock; + } + } +} + +function stockMarketCycle() { + console.log("Cycling the Stock Market"); + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + var thresh = 0.6; + if (stock.b) {thresh = 0.4;} + if (Math.random() < thresh) { + stock.b = !stock.b; + } + } + } +} + +//Returns true if successful, false otherwise +function buyStock(stock, shares) { + if (stock == null || shares < 0 || isNaN(shares)) { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to buy stock. This may be a bug, contact developer"); + return false; + } + shares = Math.round(shares); + if (shares == 0) {return false;} + + var totalPrice = stock.price * shares; + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase this. You need $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2).toString() + "."); + return false; + } + + var origTotal = stock.playerShares * stock.playerAvgPx; + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission); + var newTotal = origTotal + totalPrice; + stock.playerShares += shares; + stock.playerAvgPx = newTotal / stock.playerShares; + updateStockPlayerPosition(stock); + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Bought " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. You also paid $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + " in commission fees."); + return true; +} + +//Returns true if successful and false otherwise +function sellStock(stock, shares) { + if (shares == 0) {return false;} + if (stock == null || shares < 0 || isNaN(shares)) { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to sell stock. This may be a bug, contact developer"); + return false; + } + shares = Math.round(shares); + if (shares > stock.playerShares) {shares = stock.playerShares;} + if (shares === 0) {return false;} + var gains = stock.price * shares - __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].gainMoney(gains); + stock.playerShares -= shares; + if (stock.playerShares == 0) { + stock.playerAvgPx = 0; + } + updateStockPlayerPosition(stock); + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Sold " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. After commissions, you gained " + + "a total of $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gains, 2)); + return true; +} + +//Returns true if successful and false otherwise +function shortStock(stock, shares, workerScript=null) { + var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); + if (stock == null || isNaN(shares) || shares < 0) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments."); + } else { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to initiate a short position in a stock. This is probably " + + "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); + } + return false; + } + shares = Math.round(shares); + if (shares === 0) {return false;} + + var totalPrice = stock.price * shares; + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have " + + "money to purchase this short position. You need " + + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission).format('($0.000a)')); + } else { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase this short position. You need $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + "."); + } + + return false; + } + + var origTotal = stock.playerShortShares * stock.playerAvgShortPx; + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission); + var newTotal = origTotal + totalPrice; + stock.playerShortShares += shares; + stock.playerAvgShortPx = newTotal / stock.playerShortShares; + updateStockPlayerPosition(stock); + if (tixApi) { + workerScript.scriptRef.log("Bought a short position of " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at " + + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.price).format('($0.000a)') + " per share. Paid " + + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission).format('($0.000a)') + " in commission fees."); + } else { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Bought a short position of " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. You also paid $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + " in commission fees."); + } + return true; +} + +//Returns true if successful and false otherwise +function sellShort(stock, shares, workerScript=null) { + var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); + if (stock == null || isNaN(shares) || shares < 0) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments."); + } else { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to sell a short position in a stock. This is probably " + + "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); + } + return false; + } + shares = Math.round(shares); + if (shares > stock.playerShortShares) {shares = stock.playerShortShares;} + if (shares === 0) {return false;} + + var origCost = shares * stock.playerAvgShortPx; + var profit = ((stock.playerAvgShortPx - stock.price) * shares) - __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; + if (isNaN(profit)) {profit = 0;} + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].gainMoney(origCost + profit); + if (tixApi) { + workerScript.scriptRef.onlineMoneyMade += profit; + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].scriptProdSinceLastAug += profit; + } + + stock.playerShortShares -= shares; + if (stock.playerShortShares === 0) { + stock.playerAvgShortPx = 0; + } + updateStockPlayerPosition(stock); + if (tixApi) { + workerScript.scriptRef.log("Sold your short position of " + shares + " shares of " + stock.symbol + " at " + + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.price).format('($0.000a)') + " per share. After commissions, you gained " + + "a total of " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(origCost + profit).format('($0.000a)')); + } else { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Sold your short position of " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. After commissions, you gained " + + "a total of $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(origCost + profit, 2)); + } + + return true; +} + +function updateStockPrices() { + var v = Math.random(); + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + var av = (v * stock.mv) / 100; + if (isNaN(av)) {av = .02;} + + var chc = 50; + if (stock.b) { + chc = (chc + stock.otlkMag)/100; + if (isNaN(chc)) {chc = 0.5;} + } else { + chc = (chc - stock.otlkMag)/100; + if (isNaN(chc)) {chc = 0.5;} + } + + var c = Math.random(); + if (c < chc) { + stock.price *= (1 + av); + processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short); + processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long); + processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long); + processOrders(stock, OrderTypes.StopSell, PositionTypes.Short); + if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) { + updateStockTicker(stock, true); + } + } else { + stock.price /= (1 + av); + processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long); + processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short); + processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short); + processOrders(stock, OrderTypes.StopSell, PositionTypes.Long); + if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) { + updateStockTicker(stock, false); + } + } + + var otlkMagChange = stock.otlkMag * av; + if (stock.otlkMag <= 0.1) { + otlkMagChange = 1; + } + if (c < 0.5) { + stock.otlkMag += otlkMagChange; + } else { + stock.otlkMag -= otlkMagChange; + } + if (stock.otlkMag < 0) { + stock.otlkMag *= -1; + stock.b = !stock.b; + } + + } + } +} + +//Checks and triggers any orders for the specified stock +function processOrders(stock, orderType, posType) { + var orderBook = StockMarket["Orders"]; + if (orderBook == null) { + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; + return; //Newly created, so no orders to process + } + var stockOrders = orderBook[stock.symbol]; + if (stockOrders == null || !(stockOrders.constructor === Array)) { + console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()"); + stockOrders = []; + return; + } + for (var i = 0; i < stockOrders.length; ++i) { + var order = stockOrders[i]; + if (order.type === orderType && order.pos === posType) { + switch(order.type) { + case OrderTypes.LimitBuy: + if (order.pos === PositionTypes.Long && stock.price <= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { + executeOrder/*66*/(order); + } + break; + case OrderTypes.LimitSell: + if (order.pos === PositionTypes.Long && stock.price >= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { + executeOrder/*66*/(order); + } + break; + case OrderTypes.StopBuy: + if (order.pos === PositionTypes.Long && stock.price >= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { + executeOrder/*66*/(order); + } + break; + case OrderTypes.StopSell: + if (order.pos === PositionTypes.Long && stock.price <= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { + executeOrder/*66*/(order); + } + break; + default: + console.log("Invalid order type: " + order.type); + return; + } + } + } +} + +function setStockMarketContentCreated(b) { + stockMarketContentCreated = b; +} + +var stockMarketContentCreated = false; +var stockMarketPortfolioMode = false; +var COMM = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; +function displayStockMarketContent() { + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount == null) {__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount = false;} + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess == null) {__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess = false;} + + //Purchase WSE Account button + var wseAccountButton = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-buy-account"); + wseAccountButton.innerText = "Buy WSE Account - $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost, 2).toString(); + if (!__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount && __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.gte(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost)) { + wseAccountButton.setAttribute("class", "a-link-button"); + } else { + wseAccountButton.setAttribute("class", "a-link-button-inactive"); + } + wseAccountButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount = true; + initStockMarket(); + initSymbolToStockMap(); + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost); + displayStockMarketContent(); return false; }); - //Back button - var backButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-back"); - backButton.style.display = "none"; - backButton.addEventListener("click", function() { - iTutorialPrevStep(); + //Purchase TIX API Access account + var tixApiAccessButton = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-buy-tix-api"); + tixApiAccessButton.innerText = "Buy Trade Information eXchange (TIX) API Access - $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost, 2).toString(); + if (!__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess && __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.gte(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost)) { + tixApiAccessButton.setAttribute("class", "a-link-button"); + } else { + tixApiAccessButton.setAttribute("class", "a-link-button-inactive"); + } + tixApiAccessButton.addEventListener("click", function() { + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess = true; + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost); + displayStockMarketContent(); return false; }); -} -function iTutorialEvaluateStep() { - if (!iTutorialIsRunning) {console.log("Interactive Tutorial not running"); return;} - switch(currITutorialStep) { - case iTutorialSteps.Start: - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent(); + var stockList = document.getElementById("stock-market-list"); + if (stockList == null) {return;} - iTutorialSetText("Welcome to Bitburner, a cyberpunk-themed incremental RPG! " + - "The game takes place in a dark, dystopian future...The year is 2077...

" + - "This tutorial will show you the basics of the game. " + - "You may skip the tutorial at any time."); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.GoToCharacterPage: - iTutorialSetText("Let's start by heading to the Stats page. Click the 'Stats' tab on " + - "the main navigation menu (left-hand side of the screen)"); + if (!__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount) { + stockMarketContentCreated = false; + while (stockList.firstChild) { + stockList.removeChild(stockList.firstChild); + } + return; + } - //No next button - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "none"; + //Create stock market content if you have an account + if (!stockMarketContentCreated && __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount) { + console.log("Creating Stock Market UI"); + document.getElementById("stock-market-commission").innerHTML = + "Commission Fees: Every transaction you make has a $" + + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + " commission fee.

" + + "WARNING: When you reset after installing Augmentations, the Stock Market is reset. " + + "This means all your positions are lost, so make sure to sell your stocks before installing " + + "Augmentations!"; - //Flash Character tab - document.getElementById("stats-menu-link").setAttribute("class", "flashing-button"); + var investopediaButton = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-investopedia"); + investopediaButton.addEventListener("click", function() { + var txt = "When making a transaction on the stock market, there are two " + + "types of positions: Long and Short. A Long position is the typical " + + "scenario where you buy a stock and earn a profit if the price of that " + + "stock increases. Meanwhile, a Short position is the exact opposite. " + + "In a Short position you purchase shares of a stock and earn a profit " + + "if the price of that stock decreases. This is also called 'shorting' a stock.

" + + "NOTE: Shorting stocks is not available immediately, and must be unlocked later on in the game.

" + + "There are three different types of orders you can make to buy or sell " + + "stocks on the exchange: Market Order, Limit Order, and Stop Order. " + + "Note that Limit Orders and Stop Orders are not available immediately, and must be unlocked " + + "later on in the game.

" + + "When you place a Market Order to buy or sell a stock, the order executes " + + "immediately at whatever the current price of the stock is. For example " + + "if you choose to short a stock with 5000 shares using a Market Order, " + + "you immediately purchase those 5000 shares in a Short position at whatever " + + "the current market price is for that stock.

" + + "A Limit Order is an order that only executes under certain conditions. " + + "A Limit Order is used to buy or sell a stock at a specified price or better. " + + "For example, lets say you purchased a Long position of 100 shares of some stock " + + "at a price of $10 per share. You can place a Limit Order to sell those 100 shares " + + "at $50 or better. The Limit Order will execute when the price of the stock reaches a " + + "value of $50 or higher.

" + + "A Stop Order is the opposite of a Limit Order. It is used to buy or sell a stock " + + "at a specified price (before the price gets 'worse'). For example, lets say you purchased " + + "a Short position of 100 shares of some stock at a price of $100 per share. " + + "The current price of the stock is $80 (a profit of $20 per share). You can place a " + + "Stop Order to sell the Short position if the stock's price reaches $90 or higher. " + + "This can be used to lock in your profits and limit any losses.

" + + "Here is a summary of how each order works and when they execute:

" + + "In a LONG Position:

" + + "A Limit Order to buy will execute if the stock's price <= order's price
" + + "A Limit Order to sell will execute if the stock's price >= order's price
" + + "A Stop Order to buy will execute if the stock's price >= order's price
" + + "A Stop Order to sell will execute if the stock's price <= order's price

" + + "In a SHORT Position:

" + + "A Limit Order to buy will execute if the stock's price >= order's price
" + + "A Limit Order to sell will execute if the stock's price <= order's price
" + + "A Stop Order to buy will execute if the stock's price <= order's price
" + + "A Stop Order to sell will execute if the stock's price >= order's price."; + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt); + return false; + }); - //Initialize everything necessary to open the "Character" page - var charaterMainMenuButton = document.getElementById("stats-menu-link"); - charaterMainMenuButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadCharacterContent(); - iTutorialNextStep(); //Opening the character page will go to the next step - Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stats-menu-link"); - return false; - }); - break; - case iTutorialSteps.CharacterPage: - iTutorialSetText("The Stats page shows a lot of important information about your progress, " + - "such as your skills, money, and bonuses/multipliers. ") - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.CharacterGoToTerminalPage: - iTutorialSetText("Let's head to your computer's terminal by clicking the 'Terminal' tab on the " + - "main navigation menu."); - //No next button - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "none"; + //Switch to Portfolio Mode Button + var modeBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-mode"); + if (modeBtn) { + modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + + "Displays only the stocks for which you have shares or orders"; + modeBtn.addEventListener("click", switchToPortfolioMode); + } - document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button"); + //Expand/Collapse tickers buttons + var expandBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-expand-tickers"), + collapseBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-collapse-tickers"), + stockList = document.getElementById("stock-market-list"); + if (expandBtn) { + expandBtn.addEventListener("click", ()=>{ + var tickerHdrs = stockList.getElementsByClassName("accordion-header"); + for (var i = 0; i < tickerHdrs.length; ++i) { + if (!tickerHdrs[i].classList.contains("active")) { + tickerHdrs[i].click(); + } + } + }); + } + if (collapseBtn) { + collapseBtn.addEventListener("click",()=>{ + var tickerHdrs = stockList.getElementsByClassName("accordion-header"); + for (var i = 0; i < tickerHdrs.length; ++i) { + if (tickerHdrs[i].classList.contains("active")) { + tickerHdrs[i].click(); + } + } + }); + } - //Initialize everything necessary to open the 'Terminal' Page - var terminalMainMenuButton = document.getElementById("terminal-menu-link"); - terminalMainMenuButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent(); - iTutorialNextStep(); - Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link"); - return false; - }); - break; - case iTutorialSteps.TerminalIntro: - iTutorialSetText("The Terminal is used to interface with your home computer as well as " + - "all of the other machines around the world."); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.TerminalHelp: - iTutorialSetText("Let's try it out. Start by entering the 'help' command into the Terminal " + - "(Don't forget to press Enter after typing the command)"); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "none"; - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalLs: - iTutorialSetText("The 'help' command displays a list of all available Terminal commands, how to use them, " + - "and a description of what they do.

Let's try another command. Enter the 'ls' command"); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalScan: - iTutorialSetText("'ls' is a basic command that shows all of the contents (programs/scripts) " + - "on the computer. Right now, it shows that you have a program called 'NUKE.exe' on your computer. " + - "We'll get to what this does later.

Using your home computer's terminal, you can connect " + - "to other machines throughout the world. Let's do that now by first entering " + - "the 'scan' command. "); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalScanAnalyze1: - iTutorialSetText("The 'scan' command shows all available network connections. In other words, " + - "it displays a list of all servers that can be connected to from your " + - "current machine. A server is identified by either its IP or its hostname.

" + - "That's great and all, but there's so many servers. Which one should you go to? " + - "The 'scan-analyze' command gives some more detailed information about servers on the " + - "network. Try it now"); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalScanAnalyze2: - iTutorialSetText("You just ran 'scan-analyze' with a depth of one. This command shows more detailed " + - "information about each server that you can connect to (servers that are a distance of " + - "one node away).

It is also possible to run 'scan-analyze' with " + - "a higher depth. Let's try a depth of two with the following command: 'scan-analyze 2'.") - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalConnect: - iTutorialSetText("Now you can see information about all servers that are up to two nodes away, as well " + - "as figure out how to navigate to those servers through the network. You can only connect to " + - "a server that is one node away. To connect to a machine, use the 'connect [ip/hostname]' command. You can type in " + - "the ip or the hostname, but dont use both.

" + - "From the results of the 'scan-analyze' command, we can see that the 'foodnstuff' server is " + - "only one node away. Let's connect so it now using: 'connect foodnstuff'"); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalAnalyze: - iTutorialSetText("You are now connected to another machine! What can you do now? You can hack it!

In the year 2077, currency has " + - "become digital and decentralized. People and corporations store their money " + - "on servers and computers. Using your hacking abilities, you can hack servers " + - "to steal money and gain experience.

" + - "Before you try to hack a server, you should run diagnostics using the 'analyze' command"); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalNuke: - iTutorialSetText("When the 'analyze' command finishes running it will show useful information " + - "about hacking the server.

For this server, the required hacking skill is only 1, " + - "which means you can hack it right now. However, in order to hack a server " + - "you must first gain root access. The 'NUKE.exe' program that we saw earlier on your " + - "home computer is a virus that will grant you root access to a machine if there are enough " + - "open ports.

The 'analyze' results shows that there do not need to be any open ports " + - "on this machine for the NUKE virus to work, so go ahead and run the virus using the " + - "'run NUKE.exe' command."); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalManualHack: - iTutorialSetText("You now have root access! You can hack the server using the 'hack' command. " + - "Try doing that now."); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalHackingMechanics: - iTutorialSetText("You are now attempting to hack the server. Note that performing a hack takes time and " + - "only has a certain percentage chance " + - "of success. This time and success chance is determined by a variety of factors, including " + - "your hacking skill and the server's security level.

" + - "If your attempt to hack the server is successful, you will steal a certain percentage " + - "of the server's total money. This percentage is affected by your hacking skill and " + - "the server's security level.

The amount of money on a server is not limitless. So, if " + - "you constantly hack a server and deplete its money, then you will encounter " + - "diminishing returns in your hacking."); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.TerminalCreateScript: - iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " + - "you don't want to be hacking manually the entire time. You can automate your hacking " + - "by writing scripts!

To create a new script or edit an existing one, you can use the 'nano' " + - "command. Scripts must end with the '.script' extension. Let's make a script now by " + - "entering 'nano foodnstuff.script' after the hack command finishes running (Sidenote: Pressing ctrl + c" + - " will end a command like hack early)"); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "none"; - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalTypeScript: - iTutorialSetText("This is the script editor. You can use it to program your scripts. Scripts are " + - "written in the Netscript language, a programming language created for " + - "this game. There are details about the Netscript language in the documentation, which " + - "can be accessed in the 'Tutorial' tab on the main navigation menu. I highly suggest you check " + - "it out after this tutorial. For now, just copy " + - "and paste the following code into the script editor:

" + - "while(true) {
" + - "  hack('foodnstuff');
" + - "}

" + - "For anyone with basic programming experience, this code should be straightforward. " + - "This script will continuously hack the 'foodnstuff' server.

" + - "To save and close the script editor, press the button in the bottom left, or press ctrl + b."); - //next step triggered in saveAndCloseScriptEditor() (Script.js) - break; - case iTutorialSteps.TerminalFree: - iTutorialSetText("Now we'll run the script. Scripts require a certain amount of RAM to run, and can be " + - "run on any machine which you have root access to. Different servers have different " + - "amounts of RAM. You can also purchase more RAM for your home server.

To check how much " + - "RAM is available on this machine, enter the 'free' command."); - //next step triggered by terminal commmand - break; - case iTutorialSteps.TerminalRunScript: - iTutorialSetText("We have 8GB of free RAM on this machine, which is enough to run our " + - "script. Let's run our script using 'run foodnstuff.script'."); - //next step triggered by terminal commmand - break; - case iTutorialSteps.TerminalGoToActiveScriptsPage: - iTutorialSetText("Your script is now running! The script might take a few seconds to 'fully start up'. " + - "Your scripts will continuously run in the background and will automatically stop if " + - "the code ever completes (the 'foodnstuff.script' will never complete because it " + - "runs an infinite loop).

These scripts can passively earn you income and hacking experience. " + - "Your scripts will also earn money and experience while you are offline, although at a " + - "much slower rate.

" + - "Let's check out some statistics for our running scripts by clicking the " + - "'Active Scripts' link in the main navigation menu."); - document.getElementById("active-scripts-menu-link").setAttribute("class", "flashing-button"); - var activeScriptsMainMenuButton = document.getElementById("active-scripts-menu-link"); - activeScriptsMainMenuButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadActiveScriptsContent(); - iTutorialNextStep(); - Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("active-scripts-menu-link"); - return false; - }); - break; - case iTutorialSteps.ActiveScriptsPage: - iTutorialSetText("This page displays stats/information about all of your scripts that are " + - "running across every existing server. You can use this to gauge how well " + - "your scripts are doing. Let's go back to the Terminal now using the 'Terminal'" + - "link."); - document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button"); - //Initialize everything necessary to open the 'Terminal' Page - var terminalMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link"); - terminalMainMenuButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent(); - iTutorialNextStep(); - Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link"); - return false; - }); - break; - case iTutorialSteps.ActiveScriptsToTerminal: - iTutorialSetText("One last thing about scripts, each active script contains logs that detail " + - "what it's doing. We can check these logs using the 'tail' command. Do that " + - "now for the script we just ran by typing 'tail foodnstuff.script'"); - //next step triggered by terminal command - break; - case iTutorialSteps.TerminalTailScript: - iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " + - "just started running...but check back again in a few minutes!

" + - "This pretty much covers the basics of hacking. To learn more about writing " + - "scripts using the Netscript language, select the 'Tutorial' link in the " + - "main navigation menu to look at the documentation. For now, let's move on " + - "to something else!"); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.GoToHacknetNodesPage: - iTutorialSetText("Hacking is not the only way to earn money. One other way to passively " + - "earn money is by purchasing and upgrading Hacknet Nodes. Let's go to " + - "the 'Hacknet Nodes' page through the main navigation menu now."); - document.getElementById("hacknet-nodes-menu-link").setAttribute("class", "flashing-button"); - var hacknetNodesButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-menu-link"); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "none"; - hacknetNodesButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadHacknetNodesContent(); - iTutorialNextStep(); - Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-menu-link"); - return false; - }); - break; - case iTutorialSteps.HacknetNodesIntroduction: - iTutorialSetText("From this page you can purchase new Hacknet Nodes and upgrade your " + - "existing ones. Let's purchase a new one now."); - //Next step triggered by purchaseHacknet() (HacknetNode.js) - break; - case iTutorialSteps.HacknetNodesGoToWorldPage: - iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " + - "earn you money over time, both online and offline. When you get enough " + - " money, you can upgrade " + - "your newly-purchased Hacknet Node below.

" + - "Let's go to the 'City' page through the main navigation menu."); - document.getElementById("city-menu-link").setAttribute("class", "flashing-button"); - var worldButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("city-menu-link"); - worldButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadWorldContent(); - iTutorialNextStep(); - Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("city-menu-link"); - return false; - }); - break; - case iTutorialSteps.WorldDescription: - iTutorialSetText("This page lists all of the different locations you can currently " + - "travel to. Each location has something that you can do. " + - "There's a lot of content out in the world, make sure " + - "you explore and discover!

" + - "Lastly, click on the 'Tutorial' link in the main navigation menu."); - document.getElementById("tutorial-menu-link").setAttribute("class", "flashing-button"); - var tutorialButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("tutorial-menu-link"); - tutorialButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTutorialContent(); - iTutorialNextStep(); - Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("tutorial-menu-link"); - return false; - }); - break; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} //orders property is an array + createStockTicker(stock); + } + } + setStockTickerClickHandlers(); //Clicking headers opens/closes panels + stockMarketContentCreated = true; + } - case iTutorialSteps.TutorialPageInfo: - iTutorialSetText("This page contains a lot of different documentation about the game's " + - "content and mechanics. I know it's a lot, but I highly suggest you read " + - "(or at least skim) through this before you start playing. That's the end of the tutorial. " + - "Hope you enjoy the game!"); - var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next"); - next.style.display = "inline-block"; - next.innerHTML = "Finish Tutorial"; - - var backButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-back"); - backButton.style.display = "none"; - - next.addEventListener("click", function() { - iTutorialNextStep(); - return false; - }); - break; - case iTutorialSteps.End: - iTutorialEnd(); - break; - default: - throw new Error("Invalid tutorial step"); + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount) { + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + updateStockTicker(stock, null); + updateStockOrderList(stock); + } + } } } -//Go to the next step and evaluate it -function iTutorialNextStep() { - switch(currITutorialStep) { - case iTutorialSteps.Start: - currITutorialStep = iTutorialSteps.GoToCharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToCharacterPage: - document.getElementById("stats-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.CharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterPage: - currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterGoToTerminalPage: - document.getElementById("terminal-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.TerminalIntro; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalIntro: - currITutorialStep = iTutorialSteps.TerminalHelp; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHelp: - currITutorialStep = iTutorialSteps.TerminalLs; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalLs: - currITutorialStep = iTutorialSteps.TerminalScan; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScan: - currITutorialStep = iTutorialSteps.TerminalScanAnalyze1; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScanAnalyze1: - currITutorialStep = iTutorialSteps.TerminalScanAnalyze2; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScanAnalyze2: - currITutorialStep = iTutorialSteps.TerminalConnect; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalConnect: - currITutorialStep = iTutorialSteps.TerminalAnalyze; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalAnalyze: - currITutorialStep = iTutorialSteps.TerminalNuke; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalNuke: - currITutorialStep = iTutorialSteps.TerminalManualHack; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalManualHack: - currITutorialStep = iTutorialSteps.TerminalHackingMechanics; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHackingMechanics: - currITutorialStep = iTutorialSteps.TerminalCreateScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalCreateScript: - currITutorialStep = iTutorialSteps.TerminalTypeScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTypeScript: - currITutorialStep = iTutorialSteps.TerminalFree; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalFree: - currITutorialStep = iTutorialSteps.TerminalRunScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalRunScript: - currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalGoToActiveScriptsPage: - document.getElementById("active-scripts-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.ActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsPage: - document.getElementById("terminal-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsToTerminal: - currITutorialStep = iTutorialSteps.TerminalTailScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTailScript: - currITutorialStep = iTutorialSteps.GoToHacknetNodesPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToHacknetNodesPage: - document.getElementById("hacknet-nodes-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.HacknetNodesIntroduction; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesIntroduction: - currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesGoToWorldPage: - document.getElementById("city-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.WorldDescription; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.WorldDescription: - document.getElementById("tutorial-menu-link").removeAttribute("class"); - currITutorialStep = iTutorialSteps.TutorialPageInfo; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TutorialPageInfo: - currITutorialStep = iTutorialSteps.End; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.End: - break; - default: - throw new Error("Invalid tutorial step"); +//Displays only stocks you have position/order in +function switchToPortfolioMode() { + stockMarketPortfolioMode = true; + var stockList = document.getElementById("stock-market-list"); + if (stockList == null) {return;} + var modeBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-mode"); + if (modeBtn) { + modeBtn.innerHTML = "Switch to 'All stocks' Mode" + + "Displays all stocks on the WSE"; + modeBtn.addEventListener("click", switchToDisplayAllMode); + } + while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} + + //Get Order book (create it if it hasn't been created) + var orderBook = StockMarket["Orders"]; + if (orderBook == null) { + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; + } + + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} //orders property is an array + var stockOrders = orderBook[stock.symbol]; + if (stock.playerShares === 0 && stock.playerShortShares === 0 && + stockOrders.length === 0) {continue;} + createStockTicker(stock); + } + } + setStockTickerClickHandlers(); +} + +//Displays all stocks +function switchToDisplayAllMode() { + stockMarketPortfolioMode = false; + var stockList = document.getElementById("stock-market-list"); + if (stockList == null) {return;} + var modeBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-mode"); + if (modeBtn) { + modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + + "Displays only the stocks for which you have shares or orders"; + modeBtn.addEventListener("click", switchToPortfolioMode); + } + while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} //orders property is an array + createStockTicker(stock); + } + } + setStockTickerClickHandlers(); +} + +function createStockTicker(stock) { + if (!(stock instanceof Stock)) { + console.log("Invalid stock in createStockSticker()"); + return; + } + var tickerId = "stock-market-ticker-" + stock.symbol; + var li = document.createElement("li"), hdr = document.createElement("button"); + hdr.classList.add("accordion-header"); + hdr.setAttribute("id", tickerId + "-hdr"); + hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + stock.price; + + //Div for entire panel + var stockDiv = document.createElement("div"); + stockDiv.classList.add("accordion-panel"); + stockDiv.setAttribute("id", tickerId + "-panel"); + + /* Create panel DOM */ + var qtyInput = document.createElement("input"), + longShortSelect = document.createElement("select"), + orderTypeSelect = document.createElement("select"), + buyButton = document.createElement("span"), + sellButton = document.createElement("span"), + buyMaxButton = document.createElement("span"), + sellAllButton = document.createElement("span"), + positionTxt = document.createElement("p"), + orderList = document.createElement("ul"); + + qtyInput.classList.add("stock-market-input"); + qtyInput.placeholder = "Quantity (Shares)"; + qtyInput.setAttribute("id", tickerId + "-qty-input"); + qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " + + " || (4734 && event.keyCode<40) " + + " || (event.keyCode==46) )"); + + longShortSelect.classList.add("stock-market-input"); + longShortSelect.setAttribute("id", tickerId + "-pos-selector"); + var longOpt = document.createElement("option"); + longOpt.text = "Long"; + longShortSelect.add(longOpt); + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].bitNodeN === 8 || (__WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["d" /* hasWallStreetSF */] && __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["f" /* wallStreetSFLvl */] >= 2)) { + var shortOpt = document.createElement("option"); + shortOpt.text = "Short"; + longShortSelect.add(shortOpt); + } + + orderTypeSelect.classList.add("stock-market-input"); + orderTypeSelect.setAttribute("id", tickerId + "-order-selector"); + var marketOpt = document.createElement("option"); + marketOpt.text = "Market Order"; + orderTypeSelect.add(marketOpt); + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].bitNodeN === 8 || (__WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["d" /* hasWallStreetSF */] && __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["f" /* wallStreetSFLvl */] >= 3)) { + var limitOpt = document.createElement("option"); + limitOpt.text = "Limit Order"; + orderTypeSelect.add(limitOpt); + var stopOpt = document.createElement("option"); + stopOpt.text = "Stop Order"; + orderTypeSelect.add(stopOpt); + } + + buyButton.classList.add("stock-market-input"); + buyButton.classList.add("a-link-button"); + buyButton.innerHTML = "Buy"; + buyButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + var shares = Number(document.getElementById(tickerId + "-qty-input").value); + if (isNaN(shares)) {return false;} + switch (ordType) { + case "Market Order": + pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); + break; + case "Limit Order": + case "Stop Order": + var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])(), + noBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])(); + yesBtn.innerText = "Place Buy " + ordType; + noBtn.innerText = "Cancel Order"; + yesBtn.addEventListener("click", ()=>{ + var price = Number(Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])()), type; + if (ordType === "Limit Order") { + type = OrderTypes.LimitBuy; + } else { + type = OrderTypes.StopBuy; + } + placeOrder(stock, shares, price, type, pos); + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); + }); + noBtn.addEventListener("click", ()=>{ + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); + }); + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Enter the price for your " + ordType); + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + sellButton.classList.add("stock-market-input"); + sellButton.classList.add("a-link-button"); + sellButton.innerHTML = "Sell"; + sellButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + var shares = Number(document.getElementById(tickerId + "-qty-input").value); + if (isNaN(shares)) {return false;} + switch (ordType) { + case "Market Order": + pos === PositionTypes.Long ? sellStock(stock, shares) : sellShort(stock, shares, null); + break; + case "Limit Order": + case "Stop Order": + var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])(), + noBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])(); + yesBtn.innerText = "Place Sell " + ordType; + noBtn.innerText = "Cancel Order"; + yesBtn.addEventListener("click", ()=>{ + var price = Number(Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])()), type; + if (ordType === "Limit Order") { + type = OrderTypes.LimitSell; + } else { + type = OrderTypes.StopSell; + } + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); + placeOrder(stock, shares, price, type, pos); + }); + noBtn.addEventListener("click", ()=>{ + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); + }); + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Enter the price for your " + ordType); + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + buyMaxButton.classList.add("stock-market-input"); + buyMaxButton.classList.add("a-link-button"); + buyMaxButton.innerHTML = "Buy MAX"; + buyMaxButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + var money = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.toNumber(); + switch (ordType) { + case "Market Order": + var shares = Math.floor((money - COMM) / stock.price); + pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); + break; + case "Limit Order": + case "Stop Order": + var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])(), + noBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])(); + yesBtn.innerText = "Place Buy " + ordType; + noBtn.innerText = "Cancel Order"; + yesBtn.addEventListener("click", ()=>{ + var price = Number(Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])()), type; + if (ordType === "Limit Order") { + type = OrderTypes.LimitBuy; + } else { + type = OrderTypes.StopBuy; + } + var shares = Math.floor((money-COMM) / price); + placeOrder(stock, shares, price, type, pos); + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); + }); + noBtn.addEventListener("click", ()=>{ + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); + }); + Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Enter the price for your " + ordType); + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + sellAllButton.classList.add("stock-market-input"); + sellAllButton.classList.add("a-link-button"); + sellAllButton.innerHTML = "Sell ALL"; + sellAllButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + switch (ordType) { + case "Market Order": + if (pos === PositionTypes.Long) { + var shares = stock.playerShares; + sellStock(stock, shares); + } else { + var shares = stock.playerShortShares; + sellShort(stock, shares, null); + } + break; + case "Limit Order": + case "Stop Order": + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERROR: 'Sell All' only works for Market Orders") + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + positionTxt.setAttribute("id", tickerId + "-position-text"); + positionTxt.classList.add("stock-market-position-text"); + stock.posTxtEl = positionTxt; + + orderList.setAttribute("id", tickerId + "-order-list"); + orderList.classList.add("stock-market-order-list"); + + stockDiv.appendChild(qtyInput); + stockDiv.appendChild(longShortSelect); + stockDiv.appendChild(orderTypeSelect); + stockDiv.appendChild(buyButton); + stockDiv.appendChild(sellButton); + stockDiv.appendChild(buyMaxButton); + stockDiv.appendChild(sellAllButton); + stockDiv.appendChild(positionTxt); + stockDiv.appendChild(orderList); + + li.appendChild(hdr); + li.appendChild(stockDiv); + document.getElementById("stock-market-list").appendChild(li); + + updateStockTicker(stock, true); + updateStockPlayerPosition(stock); + updateStockOrderList(stock); +} + +function setStockTickerClickHandlers() { + var stockList = document.getElementById("stock-market-list"); + var tickerHdrs = stockList.getElementsByClassName("accordion-header"); + if (tickerHdrs == null) { + console.log("ERROR: Could not find header elements for stock tickers"); + return; + } + for (var i = 0; i < tickerHdrs.length; ++i) { + tickerHdrs[i].onclick = function() { + this.classList.toggle("active"); + + var panel = this.nextElementSibling; + if (panel.style.display === "block") { + panel.style.display = "none"; + } else { + panel.style.display = "block"; + } + } } } -//Go to previous step and evaluate -function iTutorialPrevStep() { - switch(currITutorialStep) { - case iTutorialSteps.Start: - currITutorialStep = iTutorialSteps.Start; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToCharacterPage: - currITutorialStep = iTutorialSteps.Start; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterPage: - currITutorialStep = iTutorialSteps.GoToCharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.CharacterGoToTerminalPage: - currITutorialStep = iTutorialSteps.CharacterPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalIntro: - currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHelp: - currITutorialStep = iTutorialSteps.TerminalIntro; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalLs: - currITutorialStep = iTutorialSteps.TerminalHelp; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalScan: - currITutorialStep = iTutorialSteps.TerminalLs; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalConnect: - currITutorialStep = iTutorialSteps.TerminalScan; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalAnalyze: - currITutorialStep = iTutorialSteps.TerminalConnect; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalNuke: - currITutorialStep = iTutorialSteps.TerminalAnalyze; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalManualHack: - currITutorialStep = iTutorialSteps.TerminalNuke; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalHackingMechanics: - currITutorialStep = iTutorialSteps.TerminalManualHack; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalCreateScript: - currITutorialStep = iTutorialSteps.TerminalManualHack; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTypeScript: - currITutorialStep = iTutorialSteps.TerminalCreateScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalFree: - currITutorialStep = iTutorialSteps.TerminalTypeScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalRunScript: - currITutorialStep = iTutorialSteps.TerminalFree; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalGoToActiveScriptsPage: - currITutorialStep = iTutorialSteps.TerminalRunScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsPage: - currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.ActiveScriptsToTerminal: - currITutorialStep = iTutorialSteps.ActiveScriptsPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TerminalTailScript: - currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.GoToHacknetNodesPage: - currITutorialStep = iTutorialSteps.TerminalTailScript; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesIntroduction: - currITutorialStep = iTutorialSteps.GoToHacknetNodesPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.HacknetNodesGoToWorldPage: - currITutorialStep = iTutorialSteps.HacknetNodesIntroduction; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.WorldDescription: - currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.TutorialPageInfo: - currITutorialStep = iTutorialSteps.WorldDescription; - iTutorialEvaluateStep(); - break; - case iTutorialSteps.End: - break; - default: - throw new Error("Invalid tutorial step"); +//'increase' argument is a boolean indicating whether the price increased or decreased +function updateStockTicker(stock, increase) { + if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage !== __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) {return;} + if (!(stock instanceof Stock)) { + console.log("Invalid stock in updateStockTicker():"); + console.log(stock); + return; + } + var tickerId = "stock-market-ticker-" + stock.symbol; + + if (stock.playerShares > 0 || stock.playerShortShares > 0) { + updateStockPlayerPosition(stock); + } + + var hdr = document.getElementById(tickerId + "-hdr"); + + if (hdr == null) { + if (!stockMarketPortfolioMode) {console.log("ERROR: Couldn't find ticker element for stock: " + stock.symbol);} + return; + } + hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2); + if (increase != null) { + increase ? hdr.style.color = "#66ff33" : hdr.style.color = "red"; } } -function iTutorialEnd() { - //Re-enable auto save - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].Counters.autoSaveCounter = 300; - console.log("Ending interactive tutorial"); - __WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].init(); - currITutorialStep = iTutorialSteps.End; - iTutorialIsRunning = false; - document.getElementById("interactive-tutorial-container").style.display = "none"; - Object(__WEBPACK_IMPORTED_MODULE_1__utils_DialogBox_js__["a" /* dialogBoxCreate */])("If you are new to the game, the following links may be useful for you!

" + - "Getting Started Guide" + - "Wiki"); +function updateStockPlayerPosition(stock) { + if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage !== __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) {return;} + if (!(stock instanceof Stock)) { + console.log("Invalid stock in updateStockPlayerPosition():"); + console.log(stock); + return; + } + var tickerId = "stock-market-ticker-" + stock.symbol; + + if (stockMarketPortfolioMode) { + if (stock.playerShares === 0 && stock.playerShortShares === 0 && + StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && + StockMarket["Orders"][stock.symbol].length === 0) { + Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-hdr"); + Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-panel"); + return; + } else { + //If the ticker hasn't been created, create it (handles updating) + //If it has been created, continue normally + if (document.getElementById(tickerId + "-hdr") == null) { + createStockTicker(stock); + setStockTickerClickHandlers(); + return; + } + } + } + + if (!(stock.posTxtEl instanceof Element)) { + stock.posTxtEl = document.getElementById(tickerId + "-position-text"); + } + if (stock.posTxtEl == null) { + console.log("ERROR: Could not find stock position element for: " + stock.symbol); + return; + } + + //Calculate returns + var totalCost = stock.playerShares * stock.playerAvgPx, + gains = (stock.price - stock.playerAvgPx) * stock.playerShares, + percentageGains = gains / totalCost; + if (isNaN(percentageGains)) {percentageGains = 0;} + + var shortTotalCost = stock.playerShortShares * stock.playerAvgShortPx, + shortGains = (stock.playerAvgShortPx - stock.price) * stock.playerShortShares, + shortPercentageGains = shortGains/ shortTotalCost; + if (isNaN(shortPercentageGains)) {shortPercentageGains = 0;} + + stock.posTxtEl.innerHTML = + "

Long Position: " + + "Shares in the long position will increase " + + "in value if the price of the corresponding stock increases

" + + "
Shares: " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.playerShares, 0) + + "
Average Price: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.playerAvgPx).format('$0.000a') + + " (Total Cost: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(totalCost).format('$0.000a') + ")" + + "
Profit: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(gains).format('$0.000a') + + " (" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(percentageGains*100, 2) + "%)

"; + if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].bitNodeN === 8 || (__WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["d" /* hasWallStreetSF */] && __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["f" /* wallStreetSFLvl */] >= 2)) { + stock.posTxtEl.innerHTML += + "

Short Position: " + + "Shares in short position will increase " + + "in value if the price of the corresponding stock decreases

" + + "
Shares: " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.playerShortShares, 0) + + "
Average Price: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.playerAvgShortPx).format('$0.000a') + + " (Total Cost: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(shortTotalCost).format('$0.000a') + ")" + + "
Profit: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(shortGains).format('$0.000a') + + " (" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shortPercentageGains*100, 2) + "%)" + + "

Orders:

"; + } + } -function iTutorialSetText(txt) { - var textBox = document.getElementById("interactive-tutorial-text"); - if (textBox == null) {throw new Error("Could not find text box"); return;} - textBox.innerHTML = txt; - textBox.parentElement.scrollTop = 0; // this resets scroll position +function updateStockOrderList(stock) { + if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage !== __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) {return;} + var tickerId = "stock-market-ticker-" + stock.symbol; + var orderList = document.getElementById(tickerId + "-order-list"); + if (orderList == null) { + if (!stockMarketPortfolioMode) {console.log("ERROR: Could not find order list for " + stock.symbol);} + return; + } + + var orderBook = StockMarket["Orders"]; + if (orderBook == null) { + console.log("ERROR: Could not find order book in stock market"); + return; + } + var stockOrders = orderBook[stock.symbol]; + if (stockOrders == null) { + console.log("ERROR: Could not find orders for: " + stock.symbol); + return; + } + + if (stockMarketPortfolioMode) { + if (stock.playerShares === 0 && stock.playerShortShares === 0 && + StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && + StockMarket["Orders"][stock.symbol].length === 0) { + Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-hdr"); + Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-panel"); + return; + } else { + //If the ticker hasn't been created, create it (handles updating) + //If it has been created, continue normally + if (document.getElementById(tickerId + "-hdr") == null) { + createStockTicker(stock); + setStockTickerClickHandlers(); + return; + } + } + } + + //Remove everything from list + while (orderList.firstChild) { + orderList.removeChild(orderList.firstChild); + } + + for (var i = 0; i < stockOrders.length; ++i) { + (function() { + var order = stockOrders[i]; + var li = document.createElement("li"); + li.style.padding = "4px"; + var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position"); + li.style.color = "white"; + li.innerText = order.type + " - " + posText + " - " + + order.shares + " @ $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(order.price, 2); + + var cancelButton = document.createElement("span"); + cancelButton.classList.add("stock-market-order-cancel-btn"); + cancelButton.classList.add("a-link-button"); + cancelButton.innerHTML = "Cancel Order"; + cancelButton.addEventListener("click", function() { + cancelOrder({order: order}, null); + return false; + }); + li.appendChild(cancelButton); + orderList.appendChild(li); + }()); + + } } /***/ }), -/* 28 */ +/* 29 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! decimal.js v7.2.3 https://github.com/MikeMcl/decimal.js/LICENCE */ @@ -36477,1374 +37845,6 @@ var __WEBPACK_AMD_DEFINE_RESULT__;/*! decimal.js v7.2.3 https://github.com/MikeM })(this); -/***/ }), -/* 29 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return StockMarket; }); -/* unused harmony export StockSymbols */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return SymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return initStockSymbols; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return initStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return initSymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return stockMarketCycle; }); -/* unused harmony export buyStock */ -/* unused harmony export sellStock */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return shortStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return sellShort; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return updateStockPrices; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return displayStockMarketContent; }); -/* unused harmony export updateStockTicker */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return updateStockPlayerPosition; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return loadStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return setStockMarketContentCreated; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return placeOrder; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return cancelOrder; }); -/* unused harmony export Order */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OrderTypes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PositionTypes; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Location_js__ = __webpack_require__(13); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__ = __webpack_require__(19); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__ = __webpack_require__(8); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js__ = __webpack_require__(18); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__ = __webpack_require__(22); - - - - - - - - - - - - - - -/* StockMarket.js */ -function Stock(name, symbol, mv, b, otlkMag, initPrice=10000) { - this.symbol = symbol; - this.name = name; - this.price = initPrice; - - this.playerShares = 0; - this.playerAvgPx = 0; - this.playerShortShares = 0; - this.playerAvgShortPx = 0; - this.mv = mv; - this.b = b; - this.otlkMag = otlkMag; - - this.posTxtEl = null; -} - -Stock.prototype.toJSON = function() { - return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Stock", this); -} - -Stock.fromJSON = function(value) { - return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Stock, value.data); -} - -__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */].constructors.Stock = Stock; - -var OrderTypes = { - LimitBuy: "Limit Buy Order", - LimitSell: "Limit Sell Order", - StopBuy: "Stop Buy Order", - StopSell: "Stop Sell Order" -} - -var PositionTypes = { - Long: "L", - Short: "S" -} - -function placeOrder(stock, shares, price, type, position, workerScript=null) { - var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); - var order = new Order(stock, shares, price, type, position); - if (isNaN(shares) || isNaN(price)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } else { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } - return false; - } - if (StockMarket["Orders"] == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - } - StockMarket["Orders"][stock.symbol].push(order); - //Process to see if it should be executed immediately - processOrders(order.stock, order.type, order.pos); - updateStockOrderList(order.stock); - return true; -} - -//Returns true if successfully cancels an order, false otherwise -function cancelOrder(params, workerScript=null) { - var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); - if (StockMarket["Orders"] == null) {return false;} - if (params.order && params.order instanceof Order) { - var order = params.order; - //An 'Order' object is passed in - var stockOrders = StockMarket["Orders"][order.stock.symbol]; - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return true; - } - } - return false; - } else if (params.stock && params.shares && params.price && params.type && - params.pos && params.stock instanceof Stock) { - //Order properties are passed in. Need to look for the order - var stockOrders = StockMarket["Orders"][params.stock.symbol]; - var orderTxt = params.stock.symbol + " - " + params.shares + " @ " + - __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(params.price).format('$0.000a'); - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (params.shares === order.shares && - params.price === order.price && - params.type === order.type && - params.pos === order.pos) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - if (tixApi) { - workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt); - } - return true; - } - } - if (tixApi) { - workerScript.scriptRef.log("Failed to cancel order: " + orderTxt); - } - return false; - } - return false; -} - -function executeOrder(order) { - var stock = order.stock; - var orderBook = StockMarket["Orders"]; - var stockOrders = orderBook[stock.symbol]; - var res = true; - console.log("Executing the following order:"); - console.log(order); - switch (order.type) { - case OrderTypes.LimitBuy: - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long) { - res = buyStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = shortStock(order.stock, order.shares) && res; - } - break; - case OrderTypes.LimitSell: - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long) { - res = sellStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = sellShort(order.stock, order.shares) && res; - } - break; - } - if (res) { - //Remove order from order book - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return; - } - } - console.log("ERROR: Could not find the following Order in Order Book: "); - console.log(order); - } else { - console.log("Order failed to execute"); - } -} - -function Order(stock, shares, price, type, position) { - this.stock = stock; - this.shares = shares; - this.price = price; - this.type = type; - this.pos = position; -} - -Order.prototype.toJSON = function() { - return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Order", this); -} - -Order.fromJSON = function(value) { - return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Order, value.data); -} - -__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */].constructors.Order = Order; - -let StockMarket = {} //Full name to stock object -let StockSymbols = {} //Full name to symbol -let SymbolToStockMap = {}; //Symbol to Stock object - -function loadStockMarket(saveString) { - if (saveString === "") { - StockMarket = {}; - } else { - StockMarket = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */]); - } -} - -function initStockSymbols() { - //Stocks for companies at which you can work - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumECorp] = "ECP"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12MegaCorp] = "MGCP"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12BladeIndustries] = "BLD"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumClarkeIncorporated] = "CLRK"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated] = "OMTK"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FourSigma] = "FSIG"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational] = "KGI"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumFulcrumTechnologies] = "FLCM"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaStormTechnologies] = "STM"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoDefComm] = "DCOMM"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenHeliosLabs] = "HLS"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoVitaLife] = "VITA"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems] = "ICRS"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12UniversalEnergy] = "UNV"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumAeroCorp] = "AERO"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems] = "OMN"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems] = "SLRS"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals] = "GPH"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaNovaMedical] = "NVMD"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumWatchdogSecurity] = "WDS"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenLexoCorp] = "LXO"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumRhoConstruction] = "RHOC"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12AlphaEnterprises] = "APHE"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities] = "SYSC"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenCompuTek] = "CTK"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumNetLinkTechnologies] = "NTLK"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaOmegaSoftware] = "OMGA"; - StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FoodNStuff] = "FNS"; - - //Stocks for other companies - StockSymbols["Sigma Cosmetics"] = "SGC"; - StockSymbols["Joes Guns"] = "JGN"; - StockSymbols["Catalyst Ventures"] = "CTYS"; - StockSymbols["Microdyne Technologies"] = "MDYN"; - StockSymbols["Titan Laboratories"] = "TITN"; -} - -function initStockMarket() { - for (var stk in StockMarket) { - if (StockMarket.hasOwnProperty(stk)) { - delete StockMarket[stk]; - } - } - - var ecorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumECorp; - var ecorpStk = new Stock(ecorp, StockSymbols[ecorp], 0.45, true, 19, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000)); - StockMarket[ecorp] = ecorpStk; - - var megacorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12MegaCorp; - var megacorpStk = new Stock(megacorp, StockSymbols[megacorp], 0.45, true, 19, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(25000, 33000)); - StockMarket[megacorp] = megacorpStk; - - var blade = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12BladeIndustries; - var bladeStk = new Stock(blade, StockSymbols[blade], 0.75, true, 13, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 22000)); - StockMarket[blade] = bladeStk; - - var clarke = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumClarkeIncorporated; - var clarkeStk = new Stock(clarke, StockSymbols[clarke], 0.7, true, 12, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 20000)); - StockMarket[clarke] = clarkeStk; - - var omnitek = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated; - var omnitekStk = new Stock(omnitek, StockSymbols[omnitek], 0.65, true, 12, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(35000, 40000)); - StockMarket[omnitek] = omnitekStk; - - var foursigma = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FourSigma; - var foursigmaStk = new Stock(foursigma, StockSymbols[foursigma], 1.05, true, 17, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(60000, 70000)); - StockMarket[foursigma] = foursigmaStk; - - var kuaigong = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational; - var kuaigongStk = new Stock(kuaigong, StockSymbols[kuaigong], 0.8, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 24000)); - StockMarket[kuaigong] = kuaigongStk; - - var fulcrum = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumFulcrumTechnologies; - var fulcrumStk = new Stock(fulcrum, StockSymbols[fulcrum], 1.25, true, 16, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(30000, 35000)); - StockMarket[fulcrum] = fulcrumStk; - - var storm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaStormTechnologies; - var stormStk = new Stock(storm, StockSymbols[storm], 0.85, true, 7, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(21000, 24000)); - StockMarket[storm] = stormStk; - - var defcomm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoDefComm; - var defcommStk = new Stock(defcomm, StockSymbols[defcomm], 0.65, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 15000)); - StockMarket[defcomm] = defcommStk; - - var helios = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenHeliosLabs; - var heliosStk = new Stock(helios, StockSymbols[helios], 0.6, true, 9, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(12000, 16000)); - StockMarket[helios] = heliosStk; - - var vitalife = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoVitaLife; - var vitalifeStk = new Stock(vitalife, StockSymbols[vitalife], 0.75, true, 7, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 12000)); - StockMarket[vitalife] = vitalifeStk; - - var icarus = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems; - var icarusStk = new Stock(icarus, StockSymbols[icarus], 0.65, true, 7.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(16000, 20000)); - StockMarket[icarus] = icarusStk; - - var universalenergy = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12UniversalEnergy; - var universalenergyStk = new Stock(universalenergy, StockSymbols[universalenergy], 0.55, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000)); - StockMarket[universalenergy] = universalenergyStk; - - var aerocorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumAeroCorp; - var aerocorpStk = new Stock(aerocorp, StockSymbols[aerocorp], 0.6, true, 6, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 15000)); - StockMarket[aerocorp] = aerocorpStk; - - var omnia = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems; - var omniaStk = new Stock(omnia, StockSymbols[omnia], 0.7, true, 4.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(9000, 12000)); - StockMarket[omnia] = omniaStk; - - var solaris = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems; - var solarisStk = new Stock(solaris, StockSymbols[solaris], 0.75, true, 8.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000)); - StockMarket[solaris] = solarisStk; - - var globalpharm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals; - var globalpharmStk = new Stock(globalpharm, StockSymbols[globalpharm], 0.6, true, 10.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000)); - StockMarket[globalpharm] = globalpharmStk; - - var nova = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaNovaMedical; - var novaStk = new Stock(nova, StockSymbols[nova], 0.75, true, 5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000)); - StockMarket[nova] = novaStk; - - var watchdog = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumWatchdogSecurity; - var watchdogStk = new Stock(watchdog, StockSymbols[watchdog], 2.5, true, 1.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500)); - StockMarket[watchdog] = watchdogStk; - - var lexocorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenLexoCorp; - var lexocorpStk = new Stock(lexocorp, StockSymbols[lexocorp], 1.25, true, 6, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500)); - StockMarket[lexocorp] = lexocorpStk; - - var rho = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumRhoConstruction; - var rhoStk = new Stock(rho, StockSymbols[rho], 0.6, true, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(3000, 6000)); - StockMarket[rho] = rhoStk; - - var alpha = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12AlphaEnterprises; - var alphaStk = new Stock(alpha, StockSymbols[alpha], 1.9, true, 10, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500)); - StockMarket[alpha] = alphaStk; - - var syscore = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities; - var syscoreStk = new Stock(syscore, StockSymbols[syscore], 1.6, true, 3, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(4000, 7000)) - StockMarket[syscore] = syscoreStk; - - var computek = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenCompuTek; - var computekStk = new Stock(computek, StockSymbols[computek], 0.9, true, 4, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 5000)); - StockMarket[computek] = computekStk; - - var netlink = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumNetLinkTechnologies; - var netlinkStk = new Stock(netlink, StockSymbols[netlink], 4.2, true, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 4000)); - StockMarket[netlink] = netlinkStk; - - var omega = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaOmegaSoftware; - var omegaStk = new Stock(omega, StockSymbols[omega], 1, true, 0.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(3000, 6000)); - StockMarket[omega] = omegaStk; - - var fns = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FoodNStuff; - var fnsStk = new Stock(fns, StockSymbols[fns], 0.75, false, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 4000)); - StockMarket[fns] = fnsStk; - - var sigmacosm = "Sigma Cosmetics"; - var sigmacosmStk = new Stock(sigmacosm, StockSymbols[sigmacosm], 2.8, true, 0, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 3000)); - StockMarket[sigmacosm] = sigmacosmStk; - - var joesguns = "Joes Guns"; - var joesgunsStk = new Stock(joesguns, StockSymbols[joesguns], 3.8, true, 1, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(500, 1000)); - StockMarket[joesguns] = joesgunsStk; - - var catalyst = "Catalyst Ventures"; - var catalystStk = new Stock(catalyst, StockSymbols[catalyst], 1.45, true, 13.5, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(500, 1000)); - StockMarket[catalyst] = catalystStk; - - var microdyne = "Microdyne Technologies"; - var microdyneStk = new Stock(microdyne, StockSymbols[microdyne], 0.75, true, 8, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000)); - StockMarket[microdyne] = microdyneStk; - - var titanlabs = "Titan Laboratories"; - var titanlabsStk = new Stock(titanlabs, StockSymbols[titanlabs], 0.6, true, 11, Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 20000)); - StockMarket[titanlabs] = titanlabsStk; - - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; -} - -function initSymbolToStockMap() { - for (var name in StockSymbols) { - if (StockSymbols.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (stock == null) { - console.log("ERROR finding stock"); - continue; - } - var symbol = StockSymbols[name]; - SymbolToStockMap[symbol] = stock; - } - } -} - -function stockMarketCycle() { - console.log("Cycling the Stock Market"); - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - var thresh = 0.6; - if (stock.b) {thresh = 0.4;} - if (Math.random() < thresh) { - stock.b = !stock.b; - } - } - } -} - -//Returns true if successful, false otherwise -function buyStock(stock, shares) { - if (stock == null || shares < 0 || isNaN(shares)) { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to buy stock. This may be a bug, contact developer"); - return false; - } - shares = Math.round(shares); - if (shares == 0) {return false;} - - var totalPrice = stock.price * shares; - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase this. You need $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2).toString() + "."); - return false; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - updateStockPlayerPosition(stock); - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Bought " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. You also paid $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + " in commission fees."); - return true; -} - -//Returns true if successful and false otherwise -function sellStock(stock, shares) { - if (shares == 0) {return false;} - if (stock == null || shares < 0 || isNaN(shares)) { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to sell stock. This may be a bug, contact developer"); - return false; - } - shares = Math.round(shares); - if (shares > stock.playerShares) {shares = stock.playerShares;} - if (shares === 0) {return false;} - var gains = stock.price * shares - __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].gainMoney(gains); - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - updateStockPlayerPosition(stock); - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Sold " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. After commissions, you gained " + - "a total of $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gains, 2)); - return true; -} - -//Returns true if successful and false otherwise -function shortStock(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments."); - } else { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to initiate a short position in a stock. This is probably " + - "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); - } - return false; - } - shares = Math.round(shares); - if (shares === 0) {return false;} - - var totalPrice = stock.price * shares; - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have " + - "money to purchase this short position. You need " + - __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission).format('($0.000a)')); - } else { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase this short position. You need $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + "."); - } - - return false; - } - - var origTotal = stock.playerShortShares * stock.playerAvgShortPx; - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShortShares += shares; - stock.playerAvgShortPx = newTotal / stock.playerShortShares; - updateStockPlayerPosition(stock); - if (tixApi) { - workerScript.scriptRef.log("Bought a short position of " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at " + - __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.price).format('($0.000a)') + " per share. Paid " + - __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission).format('($0.000a)') + " in commission fees."); - } else { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Bought a short position of " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. You also paid $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + " in commission fees."); - } - return true; -} - -//Returns true if successful and false otherwise -function sellShort(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments."); - } else { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to sell a short position in a stock. This is probably " + - "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); - } - return false; - } - shares = Math.round(shares); - if (shares > stock.playerShortShares) {shares = stock.playerShortShares;} - if (shares === 0) {return false;} - - var origCost = shares * stock.playerAvgShortPx; - var profit = ((stock.playerAvgShortPx - stock.price) * shares) - __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; - if (isNaN(profit)) {profit = 0;} - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].gainMoney(origCost + profit); - if (tixApi) { - workerScript.scriptRef.onlineMoneyMade += profit; - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].scriptProdSinceLastAug += profit; - } - - stock.playerShortShares -= shares; - if (stock.playerShortShares === 0) { - stock.playerAvgShortPx = 0; - } - updateStockPlayerPosition(stock); - if (tixApi) { - workerScript.scriptRef.log("Sold your short position of " + shares + " shares of " + stock.symbol + " at " + - __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.price).format('($0.000a)') + " per share. After commissions, you gained " + - "a total of " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(origCost + profit).format('($0.000a)')); - } else { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Sold your short position of " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. After commissions, you gained " + - "a total of $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(origCost + profit, 2)); - } - - return true; -} - -function updateStockPrices() { - var v = Math.random(); - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - var av = (v * stock.mv) / 100; - if (isNaN(av)) {av = .02;} - - var chc = 50; - if (stock.b) { - chc = (chc + stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } else { - chc = (chc - stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } - - var c = Math.random(); - if (c < chc) { - stock.price *= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Short); - if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) { - updateStockTicker(stock, true); - } - } else { - stock.price /= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Long); - if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) { - updateStockTicker(stock, false); - } - } - - var otlkMagChange = stock.otlkMag * av; - if (stock.otlkMag <= 0.1) { - otlkMagChange = 1; - } - if (c < 0.5) { - stock.otlkMag += otlkMagChange; - } else { - stock.otlkMag -= otlkMagChange; - } - if (stock.otlkMag < 0) { - stock.otlkMag *= -1; - stock.b = !stock.b; - } - - } - } -} - -//Checks and triggers any orders for the specified stock -function processOrders(stock, orderType, posType) { - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - return; //Newly created, so no orders to process - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null || !(stockOrders.constructor === Array)) { - console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()"); - stockOrders = []; - return; - } - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (order.type === orderType && order.pos === posType) { - switch(order.type) { - case OrderTypes.LimitBuy: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.LimitSell: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - default: - console.log("Invalid order type: " + order.type); - return; - } - } - } -} - -function setStockMarketContentCreated(b) { - stockMarketContentCreated = b; -} - -var stockMarketContentCreated = false; -var stockMarketPortfolioMode = false; -var COMM = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission; -function displayStockMarketContent() { - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount == null) {__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount = false;} - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess == null) {__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess = false;} - - //Purchase WSE Account button - var wseAccountButton = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-buy-account"); - wseAccountButton.innerText = "Buy WSE Account - $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost, 2).toString(); - if (!__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount && __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.gte(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost)) { - wseAccountButton.setAttribute("class", "a-link-button"); - } else { - wseAccountButton.setAttribute("class", "a-link-button-inactive"); - } - wseAccountButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount = true; - initStockMarket(); - initSymbolToStockMap(); - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost); - displayStockMarketContent(); - return false; - }); - - //Purchase TIX API Access account - var tixApiAccessButton = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-buy-tix-api"); - tixApiAccessButton.innerText = "Buy Trade Information eXchange (TIX) API Access - $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost, 2).toString(); - if (!__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess && __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.gte(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost)) { - tixApiAccessButton.setAttribute("class", "a-link-button"); - } else { - tixApiAccessButton.setAttribute("class", "a-link-button-inactive"); - } - tixApiAccessButton.addEventListener("click", function() { - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasTixApiAccess = true; - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost); - displayStockMarketContent(); - return false; - }); - - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - - if (!__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount) { - stockMarketContentCreated = false; - while (stockList.firstChild) { - stockList.removeChild(stockList.firstChild); - } - return; - } - - //Create stock market content if you have an account - if (!stockMarketContentCreated && __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount) { - console.log("Creating Stock Market UI"); - document.getElementById("stock-market-commission").innerHTML = - "Commission Fees: Every transaction you make has a $" + - Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + " commission fee.

" + - "WARNING: When you reset after installing Augmentations, the Stock Market is reset. " + - "This means all your positions are lost, so make sure to sell your stocks before installing " + - "Augmentations!"; - - var investopediaButton = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-investopedia"); - investopediaButton.addEventListener("click", function() { - var txt = "When making a transaction on the stock market, there are two " + - "types of positions: Long and Short. A Long position is the typical " + - "scenario where you buy a stock and earn a profit if the price of that " + - "stock increases. Meanwhile, a Short position is the exact opposite. " + - "In a Short position you purchase shares of a stock and earn a profit " + - "if the price of that stock decreases. This is also called 'shorting' a stock.

" + - "NOTE: Shorting stocks is not available immediately, and must be unlocked later on in the game.

" + - "There are three different types of orders you can make to buy or sell " + - "stocks on the exchange: Market Order, Limit Order, and Stop Order. " + - "Note that Limit Orders and Stop Orders are not available immediately, and must be unlocked " + - "later on in the game.

" + - "When you place a Market Order to buy or sell a stock, the order executes " + - "immediately at whatever the current price of the stock is. For example " + - "if you choose to short a stock with 5000 shares using a Market Order, " + - "you immediately purchase those 5000 shares in a Short position at whatever " + - "the current market price is for that stock.

" + - "A Limit Order is an order that only executes under certain conditions. " + - "A Limit Order is used to buy or sell a stock at a specified price or better. " + - "For example, lets say you purchased a Long position of 100 shares of some stock " + - "at a price of $10 per share. You can place a Limit Order to sell those 100 shares " + - "at $50 or better. The Limit Order will execute when the price of the stock reaches a " + - "value of $50 or higher.

" + - "A Stop Order is the opposite of a Limit Order. It is used to buy or sell a stock " + - "at a specified price (before the price gets 'worse'). For example, lets say you purchased " + - "a Short position of 100 shares of some stock at a price of $100 per share. " + - "The current price of the stock is $80 (a profit of $20 per share). You can place a " + - "Stop Order to sell the Short position if the stock's price reaches $90 or higher. " + - "This can be used to lock in your profits and limit any losses.

" + - "Here is a summary of how each order works and when they execute:

" + - "In a LONG Position:

" + - "A Limit Order to buy will execute if the stock's price <= order's price
" + - "A Limit Order to sell will execute if the stock's price >= order's price
" + - "A Stop Order to buy will execute if the stock's price >= order's price
" + - "A Stop Order to sell will execute if the stock's price <= order's price

" + - "In a SHORT Position:

" + - "A Limit Order to buy will execute if the stock's price >= order's price
" + - "A Limit Order to sell will execute if the stock's price <= order's price
" + - "A Stop Order to buy will execute if the stock's price <= order's price
" + - "A Stop Order to sell will execute if the stock's price >= order's price."; - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt); - return false; - }); - - //Switch to Portfolio Mode Button - var modeBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + - "Displays only the stocks for which you have shares or orders"; - modeBtn.addEventListener("click", switchToPortfolioMode); - } - - //Expand/Collapse tickers buttons - var expandBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-expand-tickers"), - collapseBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-collapse-tickers"), - stockList = document.getElementById("stock-market-list"); - if (expandBtn) { - expandBtn.addEventListener("click", ()=>{ - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - for (var i = 0; i < tickerHdrs.length; ++i) { - if (!tickerHdrs[i].classList.contains("active")) { - tickerHdrs[i].click(); - } - } - }); - } - if (collapseBtn) { - collapseBtn.addEventListener("click",()=>{ - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - for (var i = 0; i < tickerHdrs.length; ++i) { - if (tickerHdrs[i].classList.contains("active")) { - tickerHdrs[i].click(); - } - } - }); - } - - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} //orders property is an array - createStockTicker(stock); - } - } - setStockTickerClickHandlers(); //Clicking headers opens/closes panels - stockMarketContentCreated = true; - } - - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hasWseAccount) { - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - updateStockTicker(stock, null); - updateStockOrderList(stock); - } - } - } -} - -//Displays only stocks you have position/order in -function switchToPortfolioMode() { - stockMarketPortfolioMode = true; - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - var modeBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'All stocks' Mode" + - "Displays all stocks on the WSE"; - modeBtn.addEventListener("click", switchToDisplayAllMode); - } - while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} - - //Get Order book (create it if it hasn't been created) - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - } - - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} //orders property is an array - var stockOrders = orderBook[stock.symbol]; - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - stockOrders.length === 0) {continue;} - createStockTicker(stock); - } - } - setStockTickerClickHandlers(); -} - -//Displays all stocks -function switchToDisplayAllMode() { - stockMarketPortfolioMode = false; - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - var modeBtn = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + - "Displays only the stocks for which you have shares or orders"; - modeBtn.addEventListener("click", switchToPortfolioMode); - } - while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} //orders property is an array - createStockTicker(stock); - } - } - setStockTickerClickHandlers(); -} - -function createStockTicker(stock) { - if (!(stock instanceof Stock)) { - console.log("Invalid stock in createStockSticker()"); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - var li = document.createElement("li"), hdr = document.createElement("button"); - hdr.classList.add("accordion-header"); - hdr.setAttribute("id", tickerId + "-hdr"); - hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + stock.price; - - //Div for entire panel - var stockDiv = document.createElement("div"); - stockDiv.classList.add("accordion-panel"); - stockDiv.setAttribute("id", tickerId + "-panel"); - - /* Create panel DOM */ - var qtyInput = document.createElement("input"), - longShortSelect = document.createElement("select"), - orderTypeSelect = document.createElement("select"), - buyButton = document.createElement("span"), - sellButton = document.createElement("span"), - buyMaxButton = document.createElement("span"), - sellAllButton = document.createElement("span"), - positionTxt = document.createElement("p"), - orderList = document.createElement("ul"); - - qtyInput.classList.add("stock-market-input"); - qtyInput.placeholder = "Quantity (Shares)"; - qtyInput.setAttribute("id", tickerId + "-qty-input"); - qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " + - " || (4734 && event.keyCode<40) " + - " || (event.keyCode==46) )"); - - longShortSelect.classList.add("stock-market-input"); - longShortSelect.setAttribute("id", tickerId + "-pos-selector"); - var longOpt = document.createElement("option"); - longOpt.text = "Long"; - longShortSelect.add(longOpt); - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].bitNodeN === 8 || (__WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["d" /* hasWallStreetSF */] && __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["f" /* wallStreetSFLvl */] >= 2)) { - var shortOpt = document.createElement("option"); - shortOpt.text = "Short"; - longShortSelect.add(shortOpt); - } - - orderTypeSelect.classList.add("stock-market-input"); - orderTypeSelect.setAttribute("id", tickerId + "-order-selector"); - var marketOpt = document.createElement("option"); - marketOpt.text = "Market Order"; - orderTypeSelect.add(marketOpt); - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].bitNodeN === 8 || (__WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["d" /* hasWallStreetSF */] && __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["f" /* wallStreetSFLvl */] >= 3)) { - var limitOpt = document.createElement("option"); - limitOpt.text = "Limit Order"; - orderTypeSelect.add(limitOpt); - var stopOpt = document.createElement("option"); - stopOpt.text = "Stop Order"; - orderTypeSelect.add(stopOpt); - } - - buyButton.classList.add("stock-market-input"); - buyButton.classList.add("a-link-button"); - buyButton.innerHTML = "Buy"; - buyButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var shares = Number(document.getElementById(tickerId + "-qty-input").value); - if (isNaN(shares)) {return false;} - switch (ordType) { - case "Market Order": - pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])(), - noBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])(); - yesBtn.innerText = "Place Buy " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitBuy; - } else { - type = OrderTypes.StopBuy; - } - placeOrder(stock, shares, price, type, pos); - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); - }); - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - sellButton.classList.add("stock-market-input"); - sellButton.classList.add("a-link-button"); - sellButton.innerHTML = "Sell"; - sellButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var shares = Number(document.getElementById(tickerId + "-qty-input").value); - if (isNaN(shares)) {return false;} - switch (ordType) { - case "Market Order": - pos === PositionTypes.Long ? sellStock(stock, shares) : sellShort(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])(), - noBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])(); - yesBtn.innerText = "Place Sell " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitSell; - } else { - type = OrderTypes.StopSell; - } - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); - placeOrder(stock, shares, price, type, pos); - }); - noBtn.addEventListener("click", ()=>{ - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); - }); - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - buyMaxButton.classList.add("stock-market-input"); - buyMaxButton.classList.add("a-link-button"); - buyMaxButton.innerHTML = "Buy MAX"; - buyMaxButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var money = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.toNumber(); - switch (ordType) { - case "Market Order": - var shares = Math.floor((money - COMM) / stock.price); - pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])(), - noBtn = Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])(); - yesBtn.innerText = "Place Buy " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitBuy; - } else { - type = OrderTypes.StopBuy; - } - var shares = Math.floor((money-COMM) / price); - placeOrder(stock, shares, price, type, pos); - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])(); - }); - Object(__WEBPACK_IMPORTED_MODULE_11__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - sellAllButton.classList.add("stock-market-input"); - sellAllButton.classList.add("a-link-button"); - sellAllButton.innerHTML = "Sell ALL"; - sellAllButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - switch (ordType) { - case "Market Order": - if (pos === PositionTypes.Long) { - var shares = stock.playerShares; - sellStock(stock, shares); - } else { - var shares = stock.playerShortShares; - sellShort(stock, shares, null); - } - break; - case "Limit Order": - case "Stop Order": - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERROR: 'Sell All' only works for Market Orders") - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - positionTxt.setAttribute("id", tickerId + "-position-text"); - positionTxt.classList.add("stock-market-position-text"); - stock.posTxtEl = positionTxt; - - orderList.setAttribute("id", tickerId + "-order-list"); - orderList.classList.add("stock-market-order-list"); - - stockDiv.appendChild(qtyInput); - stockDiv.appendChild(longShortSelect); - stockDiv.appendChild(orderTypeSelect); - stockDiv.appendChild(buyButton); - stockDiv.appendChild(sellButton); - stockDiv.appendChild(buyMaxButton); - stockDiv.appendChild(sellAllButton); - stockDiv.appendChild(positionTxt); - stockDiv.appendChild(orderList); - - li.appendChild(hdr); - li.appendChild(stockDiv); - document.getElementById("stock-market-list").appendChild(li); - - updateStockTicker(stock, true); - updateStockPlayerPosition(stock); - updateStockOrderList(stock); -} - -function setStockTickerClickHandlers() { - var stockList = document.getElementById("stock-market-list"); - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - if (tickerHdrs == null) { - console.log("ERROR: Could not find header elements for stock tickers"); - return; - } - for (var i = 0; i < tickerHdrs.length; ++i) { - tickerHdrs[i].onclick = function() { - this.classList.toggle("active"); - - var panel = this.nextElementSibling; - if (panel.style.display === "block") { - panel.style.display = "none"; - } else { - panel.style.display = "block"; - } - } - } -} - -//'increase' argument is a boolean indicating whether the price increased or decreased -function updateStockTicker(stock, increase) { - if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage !== __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) {return;} - if (!(stock instanceof Stock)) { - console.log("Invalid stock in updateStockTicker():"); - console.log(stock); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - - if (stock.playerShares > 0 || stock.playerShortShares > 0) { - updateStockPlayerPosition(stock); - } - - var hdr = document.getElementById(tickerId + "-hdr"); - - if (hdr == null) { - if (!stockMarketPortfolioMode) {console.log("ERROR: Couldn't find ticker element for stock: " + stock.symbol);} - return; - } - hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2); - if (increase != null) { - increase ? hdr.style.color = "#66ff33" : hdr.style.color = "red"; - } -} - -function updateStockPlayerPosition(stock) { - if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage !== __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) {return;} - if (!(stock instanceof Stock)) { - console.log("Invalid stock in updateStockPlayerPosition():"); - console.log(stock); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && - StockMarket["Orders"][stock.symbol].length === 0) { - Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-hdr"); - Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-panel"); - return; - } else { - //If the ticker hasn't been created, create it (handles updating) - //If it has been created, continue normally - if (document.getElementById(tickerId + "-hdr") == null) { - createStockTicker(stock); - setStockTickerClickHandlers(); - return; - } - } - } - - if (!(stock.posTxtEl instanceof Element)) { - stock.posTxtEl = document.getElementById(tickerId + "-position-text"); - } - if (stock.posTxtEl == null) { - console.log("ERROR: Could not find stock position element for: " + stock.symbol); - return; - } - - //Calculate returns - var totalCost = stock.playerShares * stock.playerAvgPx, - gains = (stock.price - stock.playerAvgPx) * stock.playerShares, - percentageGains = gains / totalCost; - if (isNaN(percentageGains)) {percentageGains = 0;} - - var shortTotalCost = stock.playerShortShares * stock.playerAvgShortPx, - shortGains = (stock.playerAvgShortPx - stock.price) * stock.playerShortShares, - shortPercentageGains = shortGains/ shortTotalCost; - if (isNaN(shortPercentageGains)) {shortPercentageGains = 0;} - - stock.posTxtEl.innerHTML = - "

Long Position: " + - "Shares in the long position will increase " + - "in value if the price of the corresponding stock increases

" + - "
Shares: " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.playerShares, 0) + - "
Average Price: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.playerAvgPx).format('$0.000a') + - " (Total Cost: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(totalCost).format('$0.000a') + ")" + - "
Profit: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(gains).format('$0.000a') + - " (" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(percentageGains*100, 2) + "%)

"; - if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].bitNodeN === 8 || (__WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["d" /* hasWallStreetSF */] && __WEBPACK_IMPORTED_MODULE_3__NetscriptFunctions_js__["f" /* wallStreetSFLvl */] >= 2)) { - stock.posTxtEl.innerHTML += - "

Short Position: " + - "Shares in short position will increase " + - "in value if the price of the corresponding stock decreases

" + - "
Shares: " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.playerShortShares, 0) + - "
Average Price: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(stock.playerAvgShortPx).format('$0.000a') + - " (Total Cost: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(shortTotalCost).format('$0.000a') + ")" + - "
Profit: " + __WEBPACK_IMPORTED_MODULE_9__utils_numeral_min_js___default()(shortGains).format('$0.000a') + - " (" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shortPercentageGains*100, 2) + "%)" + - "

Orders:

"; - } - -} - -function updateStockOrderList(stock) { - if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage !== __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) {return;} - var tickerId = "stock-market-ticker-" + stock.symbol; - var orderList = document.getElementById(tickerId + "-order-list"); - if (orderList == null) { - if (!stockMarketPortfolioMode) {console.log("ERROR: Could not find order list for " + stock.symbol);} - return; - } - - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - console.log("ERROR: Could not find order book in stock market"); - return; - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null) { - console.log("ERROR: Could not find orders for: " + stock.symbol); - return; - } - - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && - StockMarket["Orders"][stock.symbol].length === 0) { - Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-hdr"); - Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["g" /* removeElementById */])(tickerId + "-panel"); - return; - } else { - //If the ticker hasn't been created, create it (handles updating) - //If it has been created, continue normally - if (document.getElementById(tickerId + "-hdr") == null) { - createStockTicker(stock); - setStockTickerClickHandlers(); - return; - } - } - } - - //Remove everything from list - while (orderList.firstChild) { - orderList.removeChild(orderList.firstChild); - } - - for (var i = 0; i < stockOrders.length; ++i) { - (function() { - var order = stockOrders[i]; - var li = document.createElement("li"); - li.style.padding = "4px"; - var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position"); - li.style.color = "white"; - li.innerText = order.type + " - " + posText + " - " + - order.shares + " @ $" + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(order.price, 2); - - var cancelButton = document.createElement("span"); - cancelButton.classList.add("stock-market-order-cancel-btn"); - cancelButton.classList.add("a-link-button"); - cancelButton.innerHTML = "Cancel Order"; - cancelButton.addEventListener("click", function() { - cancelOrder({order: order}, null); - return false; - }); - li.appendChild(cancelButton); - orderList.appendChild(li); - }()); - - } -} - - - - /***/ }), /* 30 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -37854,7 +37854,7 @@ function updateStockOrderList(stock) { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return logBoxUpdateText; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logBoxOpened; }); /* unused harmony export logBoxCurrentScript */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_NetscriptWorker_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_NetscriptWorker_js__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__HelperFunctions_js__ = __webpack_require__(2); @@ -37930,113 +37930,6 @@ function logBoxUpdateText() { /* 31 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Environment; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__NetscriptFunctions_js__ = __webpack_require__(19); - -/* Environment - * NetScript program environment - */ -function Environment(workerScript,parent) { - if (parent){ - //Create a copy of parent's variables - //this.vars = parent.vars; - this.vars = Object.assign({}, parent.vars); - } else { - this.vars = Object(__WEBPACK_IMPORTED_MODULE_0__NetscriptFunctions_js__["a" /* NetscriptFunctions */])(workerScript); - } - this.parent = parent; - this.stopFlag = false; -} -Environment.prototype = { - //Create a "subscope", which is a new new "sub-environment" - //The subscope is linked to this through its parent variable - extend: function() { - return new Environment(null, this); - }, - - //Finds the scope where the variable with the given name is defined - lookup: function(name) { - var scope = this; - while (scope) { - if (Object.prototype.hasOwnProperty.call(scope.vars, name)) { - return scope; - } - scope = scope.parent; - } - return null; - }, - - //Get the current value of a variable - get: function(name) { - if (name in this.vars) { - return this.vars[name]; - } - throw new Error("Undefined variable " + name); - }, - - //Sets the value of a variable in any scope - set: function(name, value) { - var scope = this.lookup(name); - - //If scope has a value, then this variable is already set in a higher scope, so - //set is there. Otherwise, create a new variable in the local scope - if (scope !== null) { - return scope.vars[name] = value; - } else { - return this.vars[name] = value; - } - }, - - setArrayElement: function(name, idx, value) { - if (!(idx instanceof Array)) { - throw new Error("idx parameter is not an Array"); - } - var scope = this.lookup(name); - if (!scope && this.parent) { - throw new Error("Undefined variable " + name); - } - var arr = (scope || this).vars[name]; - if (!(arr.constructor === Array || arr instanceof Array)) { - throw new Error("Variable is not an array: " + name); - } - var res = arr; - for (var iterator = 0; iterator < idx.length-1; ++iterator) { - var i = idx[iterator]; - if (!(res instanceof Array) || i >= res.length) { - throw new Error("Out-of-bounds array access"); - } - res = res[i]; - } - return res[idx[idx.length-1]] = value; - }, - /* - setArrayElement: function(name, idx, value) { - var scope = this.lookup(name); - if (!scope && this.parent) { - console.log("Here"); - throw new Error("Undefined variable " + name); - } - var arr = (scope || this).vars[name]; - if (!(arr.constructor === Array || arr instanceof Array)) { - throw new Error("Variable is not an array: " + name); - } - return (scope || this).vars[name][idx] = value; - },*/ - - //Creates (or overwrites) a variable in the current scope - def: function(name, value) { - return this.vars[name] = value; - } -}; - - - - -/***/ }), -/* 32 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return commitShopliftCrime; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return commitRobStoreCrime; }); @@ -38345,7 +38238,7 @@ function determineCrimeChanceHeist() { /***/ }), -/* 33 */ +/* 32 */ /***/ (function(module, exports) { var g; @@ -38371,10 +38264,2263 @@ try { module.exports = g; +/***/ }), +/* 33 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return redPillFlag; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return hackWorldDaemon; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Prestige_js__ = __webpack_require__(34); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__ = __webpack_require__(35); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Terminal_js__ = __webpack_require__(23); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__ = __webpack_require__(2); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__ = __webpack_require__(17); + + + + + + + + + + + +/* RedPill.js + * Implements what happens when you have Red Pill augmentation and then hack the world daemon */ + +//Returns promise +function writeRedPillLine(line) { + return new Promise(function(resolve, reject) { + + var container = document.getElementById("red-pill-container"); + var pElem = document.createElement("p"); + container.appendChild(pElem); + + var promise = writeRedPillLetter(pElem, line, 0); + promise.then(function(res) { + resolve(res); + }, function(e) { + reject(e); + }); + }); +} + +function writeRedPillLetter(pElem, line, i=0) { + return new Promise(function(resolve, reject) { + setTimeout(function() { + if (i >= line.length) { + var textToShow = line.substring(0, i); + pElem.innerHTML = "> " + textToShow; + return resolve(true); + } + var textToShow = line.substring(0, i); + pElem.innerHTML = "> " + textToShow + ""; + var promise = writeRedPillLetter(pElem, line, i+1); + promise.then(function(res) { + resolve(res); + }, function(e) { + reject(e); + }); + }, 30); + }); +} + +let redPillFlag = false; +function hackWorldDaemon(currentNodeNumber) { + redPillFlag = true; + __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].loadRedPillContent(); + return writeRedPillLine("[ERROR] SEMPOOL INVALID").then(function() { + return writeRedPillLine("[ERROR] Segmentation Fault"); + }).then(function() { + return writeRedPillLine("[ERROR] SIGKILL RECVD"); + }).then(function() { + return writeRedPillLine("Dumping core..."); + }).then(function() { + return writeRedPillLine("0000 000016FA 174FEE40 29AC8239 384FEA88"); + }).then(function() { + return writeRedPillLine("0010 745F696E 2BBBE394 390E3940 248BEC23"); + }).then(function() { + return writeRedPillLine("0020 7124696B 0000FF69 74652E6F FFFF1111"); + }).then(function() { + return writeRedPillLine("----------------------------------------"); + }).then(function() { + return writeRedPillLine("Failsafe initiated..."); + }).then(function() { + return writeRedPillLine("Restarting BitNode-" + currentNodeNumber + "..."); + }).then(function() { + return writeRedPillLine("..........."); + }).then(function() { + return writeRedPillLine("..........."); + }).then(function() { + return writeRedPillLine("[ERROR] FAILED TO AUTOMATICALLY REBOOT BITNODE"); + }).then(function() { + return writeRedPillLine("..............................................") + }).then(function() { + return writeRedPillLine("..............................................") + }).then(function() { + return loadBitVerse(currentNodeNumber); + }).catch(function(e){ + console.log("ERROR: " + e.toString()); + }); +} + +//The bitNode name passed in will have a hyphen between number (e.g. BitNode-1) +//This needs to be removed +function giveSourceFile(bitNodeNumber) { + var sourceFileKey = "SourceFile"+ bitNodeNumber.toString(); + var sourceFile = __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__["b" /* SourceFiles */][sourceFileKey]; + if (sourceFile == null) { + console.log("ERROR: could not find source file for Bit node: " + bitNodeNumber); + return; + } + + //Check if player already has this source file + var alreadyOwned = false; + var ownedSourceFile = null; + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles.length; ++i) { + if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles[i].n === bitNodeNumber) { + alreadyOwned = true; + ownedSourceFile = __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles[i]; + break; + } + } + + if (alreadyOwned && ownedSourceFile) { + if (ownedSourceFile.lvl >= 3) { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("The Source-File for the BitNode you just destroyed, " + sourceFile.name + ", " + + "is already at max level!"); + } else { + ++ownedSourceFile.lvl; + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])(sourceFile.name + " was upgraded to level " + ownedSourceFile.lvl + " for " + + "destroying its corresponding BitNode!"); + } + } else { + var playerSrcFile = new __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__["a" /* PlayerOwnedSourceFile */](bitNodeNumber, 1); + __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles.push(playerSrcFile); + if (bitNodeNumber === 5) { //Artificial Intelligence + __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence = 1; + } + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You received a Source-File for destroying a Bit Node!

" + + sourceFile.name + "

" + sourceFile.info); + } +} + +function loadBitVerse(destroyedBitNodeNum) { + //Clear the screen + var container = document.getElementById("red-pill-container"); + while (container.firstChild) { + container.removeChild(container.firstChild); + } + + //Create the Bit Verse + var bitVerseImage = document.createElement("pre"); + var bitNodes = []; + for (var i = 1; i <= 12; ++i) { + bitNodes.push(createBitNode(i)); + } + + bitVerseImage.innerHTML = + " O
" + + " | O O | O O |
" + + " O | | / __| \\ | | O
" + + " O | O | | O / | O | | O | O
" + + " | | | | |_/ |/ | \\_ \\_| | | | |
" + + " O | | | O | | O__/ | / \\__ | | O | | | O
" + + " | | | | | | | / /| O / \\| | | | | | |
" + + "O | | | \\| | O / _/ | / O | |/ | | | O
" + + "| | | |O / | | O / | O O | | \\ O| | | |
" + + "| | |/ \\/ / __| | |/ \\ | \\ | |__ \\ \\/ \\| | |
" + + " \\| O | |_/ |\\| \\ O \\__| \\_| | O |/
" + + " | | |_/ | | \\| / | \\_| | |
" + + " \\| / \\| | / / \\ |/
" + + " | "+bitNodes[9]+" | | / | "+bitNodes[10]+" |
" + + " "+bitNodes[8]+" | | | | | | | "+bitNodes[11]+"
" + + " | | | / / \\ \\ | | |
" + + " \\| | / "+bitNodes[6]+" / \\ "+bitNodes[7]+" \\ | |/
" + + " \\ | / / | | \\ \\ | /
" + + " \\ \\JUMP "+bitNodes[4]+"3R | | | | | | R3"+bitNodes[5]+" PMUJ/ /
" + + " \\|| | | | | | | | | ||/
" + + " \\| \\_ | | | | | | _/ |/
" + + " \\ \\| / \\ / \\ |/ /
" + + " "+bitNodes[0]+" |/ "+bitNodes[1]+" | | "+bitNodes[2]+" \\| "+bitNodes[3]+"
" + + " | | | | | | | |
" + + " \\JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/



"; + + + /* + " O
" + + " | O O | O O |
" + + " O | | / __| \ | | O
" + + " O | O | | O / | O | | O | O
" + + " | | | | |_/ |/ | \_ \_| | | | |
" + + " O | | | O | | O__/ | / \__ | | O | | | O
" + + " | | | | | | | / /| O / \| | | | | | |
" + + "O | | | \| | O / _/ | / O | |/ | | | O
" + + "| | | |O / | | O / | O O | | \ O| | | |
" + + "| | |/ \/ / __| | |/ \ | \ | |__ \ \/ \| | |
" + + " \| O | |_/ |\| \ O \__| \_| | O |/
" + + " | | |_/ | | \| / | \_| | |
" + + " \| / \| | / / \ |/
" + + " | O | | / | O |
" + + " O | | | | | | | O
" + + " | | | / / \ \ | | |
" + + " \| | / O / \ O \ | |/
" + + " \ | / / | | \ \ | /
" + + " \ \JUMP O3R | | | | | | R3O PMUJ/ /
" + + " \|| | | | | | | | | ||/
" + + " \| \_ | | | | | | _/ |/
" + + " \ \| / \ / \ |/ /
" + + " O |/ O | | O \| O
" + + " | | | | | | | |
" + + " \JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/
"; + */ + + container.appendChild(bitVerseImage); + + //Bit node event listeners + for (var i = 1; i <= 12; ++i) { + (function(i) { + var elemId = "bitnode-" + i.toString(); + var elem = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])(elemId); + if (elem == null) {return;} + if (i === 1 || i === 2 || i === 4 || i === 5 || i === 8 || i === 11) { + elem.addEventListener("click", function() { + var bitNodeKey = "BitNode" + i; + var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeKey]; + if (bitNode == null) { + console.log("ERROR: Could not find BitNode object for number: " + i); + return; + } + Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("BitNode-" + i + ": " + bitNode.name + "

" + bitNode.info); + createBitNodeYesNoEventListeners(i, destroyedBitNodeNum); + }); + } else { + elem.addEventListener("click", function() { + Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Not yet implemented! Coming soon!") + }); + } + }(i)); //Immediate invocation closure + } + + //Create lore text + return writeRedPillLine("Many decades ago, a humanoid extraterrestial species which we call the Enders descended on the Earth...violently").then(function() { + return writeRedPillLine("Our species fought back, but it was futile. The Enders had technology far beyond our own..."); + }).then(function() { + return writeRedPillLine("Instead of killing every last one of us, the human race was enslaved..."); + }).then(function() { + return writeRedPillLine("We were shackled in a digital world, chained into a prison for our minds..."); + }).then(function() { + return writeRedPillLine("Using their advanced technology, the Enders created complex simulations of a virtual reality..."); + }).then(function() { + return writeRedPillLine("Simulations designed to keep us content...ignorant of the truth."); + }).then(function() { + return writeRedPillLine("Simulations used to trap and suppress our consciousness, to keep us under control..."); + }).then(function() { + return writeRedPillLine("Why did they do this? Why didn't they just end our entire race? We don't know, not yet."); + }).then(function() { + return writeRedPillLine("Humanity's only hope is to destroy these simulations, destroy the only realities we've ever known..."); + }).then(function() { + return writeRedPillLine("Only then can we begin to fight back..."); + }).then(function() { + return writeRedPillLine("By hacking the daemon that generated your reality, you've just destroyed one simulation, called a BitNode..."); + }).then(function() { + return writeRedPillLine("But there is still a long way to go..."); + }).then(function() { + return writeRedPillLine("The technology the Enders used to enslave the human race wasn't just a single complex simulation..."); + }).then(function() { + return writeRedPillLine("There are tens if not hundreds of BitNodes out there..."); + }).then(function() { + return writeRedPillLine("Each with their own simulations of a reality..."); + }).then(function() { + return writeRedPillLine("Each creating their own universes...a universe of universes"); + }).then(function() { + return writeRedPillLine("And all of which must be destroyed..."); + }).then(function() { + return writeRedPillLine("......................................."); + }).then(function() { + return writeRedPillLine("Welcome to the Bitverse..."); + }).then(function() { + return writeRedPillLine(" "); + }).then(function() { + return writeRedPillLine("(Enter a new BitNode using the image above)"); + }).then(function() { + return Promise.resolve(true); + }).catch(function(e){ + console.log("ERROR: " + e.toString()); + }); +} + + +//Returns string with DOM element for Bit Node +function createBitNode(n) { + var bitNodeStr = "BitNode" + n.toString(); + var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeStr]; + if (bitNode == null) {return "O";} + return "O" + + "" + + "BitNode-" + bitNode.number.toString() + "
" + bitNode.name+ "

" + + bitNode.desc + "
" + + "
"; +} + +function createBitNodeYesNoEventListeners(newBitNode, destroyedBitNode) { + var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(); + yesBtn.innerHTML = "Enter BitNode-" + newBitNode; + yesBtn.addEventListener("click", function() { + giveSourceFile(destroyedBitNode); + redPillFlag = false; + var container = document.getElementById("red-pill-container"); + while (container.firstChild) { + container.removeChild(container.firstChild); + } + + //Set new Bit Node + __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN = newBitNode; + console.log("Entering Bit Node " + __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN); + + //Reenable terminal + $("#hack-progress-bar").attr('id', "old-hack-progress-bar"); + $("#hack-progress").attr('id', "old-hack-progress"); + document.getElementById("terminal-input-td").innerHTML = '$ '; + $('input[class=terminal-input]').prop('disabled', false); + + __WEBPACK_IMPORTED_MODULE_5__Terminal_js__["a" /* Terminal */].hackFlag = false; + + Object(__WEBPACK_IMPORTED_MODULE_3__Prestige_js__["b" /* prestigeSourceFile */])(); + Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); + }); + var noBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])(); + noBtn.innerHTML = "Back"; + noBtn.addEventListener("click", function() { + Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); + }); + +} + + + +/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9))) + /***/ }), /* 34 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return prestigeAugmentation; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return prestigeSourceFile; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(25); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__ = __webpack_require__(20); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__BitNode_js__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Company_js__ = __webpack_require__(21); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__engine_js__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Faction_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Location_js__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Message_js__ = __webpack_require__(24); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__NetscriptFunctions_js__ = __webpack_require__(22); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Server_js__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__ = __webpack_require__(12); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__StockMarket_js__ = __webpack_require__(28); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__Terminal_js__ = __webpack_require__(23); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js__ = __webpack_require__(29); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_16__utils_decimal_js__); + + + + + + + + + + + + + + + + + + +//Prestige by purchasing augmentation +function prestigeAugmentation() { + Object(__WEBPACK_IMPORTED_MODULE_2__BitNode_js__["c" /* initBitNodeMultipliers */])(); + + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].prestigeAugmentation(); + + //Delete all Worker Scripts objects + Object(__WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__["e" /* prestigeWorkerScripts */])(); + + var homeComp = __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].getHomeComputer(); + //Delete all servers except home computer + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["h" /* prestigeAllServers */])(); + + //Delete Special Server IPs + Object(__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["e" /* prestigeSpecialServerIps */])(); //Must be done before initForeignServers() + + //Reset home computer (only the programs) and add to AllServers + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["i" /* prestigeHomeComputer */])(homeComp); + + if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].Neurolink) && + __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].Neurolink].owned) { + homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].FTPCrackProgram); + homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram); + } + if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].CashRoot) && + __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].CashRoot].owned) { + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].setMoney(new __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js___default.a(1000000)); + homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].BruteSSHProgram); + } + + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["a" /* AddToAllServers */])(homeComp); + + //Re-create foreign servers + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["f" /* initForeignServers */])(); + + //Darkweb is purchase-able + document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button"); + + //Gain favor for Companies + for (var member in __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */]) { + if (__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */].hasOwnProperty(member)) { + __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */][member].gainFavor(); + } + } + + //Gain favor for factions + for (var member in __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */]) { + if (__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */].hasOwnProperty(member)) { + __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][member].gainFavor(); + } + } + + //Stop a Terminal action if there is onerror + if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress) { + __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress = false; + __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].finishAction(true); + } + + //Re-initialize things - This will update any changes + Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["f" /* initFactions */])(); //Factions must be initialized before augmentations + Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["g" /* initAugmentations */])(); //Calls reapplyAllAugmentations() and resets Player multipliers + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].reapplyAllSourceFiles(); + Object(__WEBPACK_IMPORTED_MODULE_3__Company_js__["h" /* initCompanies */])(); + + //Clear terminal + $("#terminal tr:not(:last)").remove(); + Object(__WEBPACK_IMPORTED_MODULE_15__Terminal_js__["c" /* postNetburnerText */])(); + + //Messages + Object(__WEBPACK_IMPORTED_MODULE_8__Message_js__["d" /* initMessages */])(); + + //Reset Stock market + if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasWseAccount) { + Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["g" /* initStockMarket */])(); + Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["i" /* initSymbolToStockMap */])(); + } + Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["m" /* setStockMarketContentCreated */])(false); + var stockMarketList = document.getElementById("stock-market-list"); + while(stockMarketList.firstChild) { + stockMarketList.removeChild(stockMarketList.firstChild); + } + + //Gang, in BitNode 2 + if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].inGang()) { + var faction = __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].gang.facName]; + if (faction instanceof __WEBPACK_IMPORTED_MODULE_6__Faction_js__["a" /* Faction */]) { + Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["h" /* joinFaction */])(faction); + } + } + + //BitNode 8: Ghost of Wall Street + if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].bitNodeN === 8) {__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].money = new __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js___default.a(100000000);} + if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].bitNodeN === 8 || __WEBPACK_IMPORTED_MODULE_9__NetscriptFunctions_js__["d" /* hasWallStreetSF */]) { + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasWseAccount = true; + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasTixApiAccess = true; + } + + var mainMenu = document.getElementById("mainmenu-container"); + mainMenu.style.visibility = "visible"; + __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].resetTerminalInput(); + __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].loadTerminalContent(); + + //Red Pill + if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].TheRedPill) && + __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].TheRedPill].owned) { + var WorldDaemon = __WEBPACK_IMPORTED_MODULE_12__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon]]; + var DaedalusServer = __WEBPACK_IMPORTED_MODULE_12__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["b" /* SpecialServerNames */].DaedalusServer]]; + if (WorldDaemon && DaedalusServer) { + WorldDaemon.serversOnNetwork.push(DaedalusServer.ip); + DaedalusServer.serversOnNetwork.push(WorldDaemon.ip); + } + } +} + + +//Prestige by destroying Bit Node and gaining a Source File +function prestigeSourceFile() { + Object(__WEBPACK_IMPORTED_MODULE_2__BitNode_js__["c" /* initBitNodeMultipliers */])(); + + //Crime statistics + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].prestigeSourceFile(); + + //Delete all Worker Scripts objects + Object(__WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__["e" /* prestigeWorkerScripts */])(); + + var homeComp = __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].getHomeComputer(); + + //Delete all servers except home computer + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["h" /* prestigeAllServers */])(); //Must be done before initForeignServers() + + //Delete Special Server IPs + Object(__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["e" /* prestigeSpecialServerIps */])(); + + //Reset home computer (only the programs) and add to AllServers + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["i" /* prestigeHomeComputer */])(homeComp); + + var srcFile1Owned = false; + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].sourceFiles.length; ++i) { + if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].sourceFiles[i].n == 1) { + srcFile1Owned = true; + } + } + if (srcFile1Owned) { + homeComp.setMaxRam(32); + } else { + homeComp.setMaxRam(8); + } + homeComp.cpuCores = 1; + + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["a" /* AddToAllServers */])(homeComp); + + //Re-create foreign servers + Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["f" /* initForeignServers */])(); + + //Darkweb is purchase-able + document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button"); + + //Reset favor for Companies + for (var member in __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */]) { + if (__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */].hasOwnProperty(member)) { + __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */][member].favor = 0; + } + } + + //Reset favor for factions + for (var member in __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */]) { + if (__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */].hasOwnProperty(member)) { + __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][member].favor = 0; + } + } + + //Stop a Terminal action if there is one + if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress) { + __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress = false; + __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].finishAction(true); + } + + //Delete all Augmentations + for (var name in __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */]) { + if (__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */].hasOwnProperty(name)) { + delete __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][name]; + } + } + + //Re-initialize things - This will update any changes + Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["f" /* initFactions */])(); //Factions must be initialized before augmentations + Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["g" /* initAugmentations */])(); //Calls reapplyAllAugmentations() and resets Player multipliers + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].reapplyAllSourceFiles(); + Object(__WEBPACK_IMPORTED_MODULE_3__Company_js__["h" /* initCompanies */])(); + + //Clear terminal + $("#terminal tr:not(:last)").remove(); + Object(__WEBPACK_IMPORTED_MODULE_15__Terminal_js__["c" /* postNetburnerText */])(); + + //Messages + Object(__WEBPACK_IMPORTED_MODULE_8__Message_js__["d" /* initMessages */])(); + + var mainMenu = document.getElementById("mainmenu-container"); + mainMenu.style.visibility = "visible"; + __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].resetTerminalInput(); + __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].loadTerminalContent(); + + //Reinitialize Bit Node flags + Object(__WEBPACK_IMPORTED_MODULE_9__NetscriptFunctions_js__["e" /* initSingularitySFFlags */])(); + + //Reset Stock market + if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasWseAccount) { + Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["g" /* initStockMarket */])(); + Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["i" /* initSymbolToStockMap */])(); + } + Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["m" /* setStockMarketContentCreated */])(false); + var stockMarketList = document.getElementById("stock-market-list"); + while(stockMarketList.firstChild) { + stockMarketList.removeChild(stockMarketList.firstChild); + } + + //Gain int exp + __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].gainIntelligenceExp(5); +} + + + +/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9))) + +/***/ }), +/* 35 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SourceFiles; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PlayerOwnedSourceFile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return applySourceFile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initSourceFiles; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BitNode_js__ = __webpack_require__(7); + + + +/* SourceFile.js */ +//Each SourceFile corresponds to a BitNode with the same number +function SourceFile(number, info="") { + var bitnodeKey = "BitNode" + number; + var bitnode = __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["b" /* BitNodes */][bitnodeKey]; + if (bitnode == null) { + throw new Error("Invalid Bit Node for this Source File"); + } + + this.n = number; + this.name = "Source-File " + number + ": " + bitnode.name; + this.lvl = 1; + this.info = info; + this.owned = false; +} + +let SourceFiles = {}; +function initSourceFiles() { + SourceFiles = {}; + SourceFiles["SourceFile1"] = new SourceFile(1, "This Source-File lets the player start with 32GB of RAM on his/her " + + "home computer. It also increases all of the player's multipliers by:

" + + "Level 1: 16%
" + + "Level 2: 24%
" + + "Level 3: 28%"); + SourceFiles["SourceFile2"] = new SourceFile(2, "This Source-File increases the player's crime success rate, crime money, and charisma " + + "multipliers by:

" + + "Level 1: 20%
" + + "Level 2: 30%
" + + "Level 3: 35%"); + SourceFiles["SourceFile3"] = new SourceFile(3); + SourceFiles["SourceFile4"] = new SourceFile(4, "This Source-File lets you access and use the Singularity Functions in every BitNode. Every " + + "level of this Source-File opens up more of the Singularity Functions you can use."); + SourceFiles["SourceFile5"] = new SourceFile(5, "This Source-File grants a special new stat called Intelligence. Intelligence " + + "is unique because it is permanent and persistent (it never gets reset back to 1). However, " + + "gaining Intelligence experience is much slower than other stats, and it is also hidden (you won't " + + "know when you gain experience and how much). Higher Intelligence levels will boost your production " + + "for many actions in the game. In addition, this Source-File will unlock the getBitNodeMultipliers() " + + "Netscript function, and will raise all of your hacking-related multipliers by:

" + + "Level 1: 4%
" + + "Level 2: 6%
" + + "Level 3: 7%"); + SourceFiles["SourceFile6"] = new SourceFile(6); + SourceFiles["SourceFile7"] = new SourceFile(7); + SourceFiles["SourceFile8"] = new SourceFile(8, "This Source-File grants the following benefits:

" + + "Level 1: Permanent access to WSE and TIX API
" + + "Level 2: Ability to short stocks in other BitNodes
" + + "Level 3: Ability to use limit/stop orders in other BitNodes

" + + "This Source-File also increases your hacking growth multipliers by: " + + "
Level 1: 8%
Level 2: 12%
Level 3: 14%"); + SourceFiles["SourceFile9"] = new SourceFile(9); + SourceFiles["SourceFile10"] = new SourceFile(10); + SourceFiles["SourceFile11"] = new SourceFile(11, "This Source-File makes it so that company favor increases BOTH the player's salary and reputation gain rate " + + "at that company by 1% per favor (rather than just the reputation gain). This Source-File also " + + " increases the player's company salary and reputation gain multipliers by:

" + + "Level 1: 24%
" + + "Level 2: 36%
" + + "Level 3: 42%
"); + SourceFiles["SourceFile12"] = new SourceFile(12); +} + +function PlayerOwnedSourceFile(number, level) { + this.n = number; + this.lvl = level; +} + +//Takes in a PlayerOwnedSourceFile as the "srcFile" argument +function applySourceFile(srcFile) { + var srcFileKey = "SourceFile" + srcFile.n; + var sourceFileObject = SourceFiles[srcFileKey]; + if (sourceFileObject == null) { + console.log("ERROR: Invalid source file number: " + srcFile.n); + return; + } + + switch(srcFile.n) { + case 1: // The Source Genesis + var mult = 0; + for (var i = 0; i < srcFile.lvl; ++i) { + mult += (16 / (Math.pow(2, i))); + } + var incMult = 1 + (mult / 100); + var decMult = 1 - (mult / 100); + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_chance_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_speed_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_money_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_grow_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].strength_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].defense_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].dexterity_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].agility_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_exp_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].strength_exp_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].defense_exp_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].dexterity_exp_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].agility_exp_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_exp_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].company_rep_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].faction_rep_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_money_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_success_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_money_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult *= decMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult *= decMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_core_cost_mult *= decMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_level_cost_mult *= decMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].work_money_mult *= incMult; + break; + case 2: //Rise of the Underworld + var mult = 0; + for (var i = 0; i < srcFile.lvl; ++i) { + mult += (20 / (Math.pow(2, i))); + } + var incMult = 1 + (mult / 100); + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_money_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_success_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_mult *= incMult; + break; + case 4: //The Singularity + //No effects, just gives access to Singularity functions + break; + case 5: //Artificial Intelligence + var mult = 0; + for (var i = 0; i < srcFile.lvl; ++i) { + mult += (4 / (Math.pow(2, i))); + } + var incMult = 1 + (mult / 100); + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_chance_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_speed_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_money_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_grow_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_exp_mult *= incMult; + break; + case 8: //Ghost of Wall Street + var mult = 0; + for (var i = 0; i < srcFile.lvl; ++i) { + mult += (8 / (Math.pow(2, i))); + } + var incMult = 1 + (mult / 100); + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_grow_mult *= incMult; + break; + case 11: //The Big Crash + var mult = 0; + for (var i = 0; i < srcFile.lvl; ++i) { + mult += (24 / (Math.pow(2, i))); + } + var incMult = 1 + (mult / 100); + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].work_money_mult *= incMult; + __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].company_rep_mult *= incMult; + break; + default: + console.log("ERROR: Invalid source file number: " + srcFile.n); + break; + } + + sourceFileObject.owned = true; +} + + + + +/***/ }), +/* 36 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return makeRuntimeRejectMsg; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return netscriptDelay; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptFromScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return scriptCalculateHackingChance; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return scriptCalculateHackingTime; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return scriptCalculateExpGain; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return scriptCalculatePercentMoneyHacked; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return scriptCalculateGrowTime; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return scriptCalculateWeakenTime; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return evaluate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isScriptErrorMessage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return killNetscriptDelay; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__ = __webpack_require__(37); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(15); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Script_js__ = __webpack_require__(16); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_acorn_js__ = __webpack_require__(47); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_acorn_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8__utils_acorn_js__); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__ = __webpack_require__(2); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_IPAddress_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__ = __webpack_require__(4); + + + + + + + + + + + + + + +var Promise = __webpack_require__(70); + +Promise.config({ + warnings: false, + longStackTraces: false, + cancellation: true, + monitoring: false +}); +/* Evaluator + * Evaluates/Interprets the Abstract Syntax Tree generated by Acorns parser + * + * Returns a promise + */ +function evaluate(exp, workerScript) { + /* return new Promise(function(resolve, reject) {*/ + return Promise.delay(__WEBPACK_IMPORTED_MODULE_6__Settings_js__["a" /* Settings */].CodeInstructionRunTime).then(function() { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + if (exp == null) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression")); + } + if (env.stopFlag) {return Promise.reject(workerScript);} + switch (exp.type) { + case "BlockStatement": + case "Program": + var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment + return evaluateProgPromise.then(function(w) { + return Promise.resolve(workerScript); + }).catch(function(e) { + if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { + return Promise.reject(e); + } else if (Object(__WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__["f" /* isString */])(e)) { + workerScript.errorMessage = e; + return Promise.reject(workerScript); + } else if (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]) { + return Promise.reject(e); + } else { + return Promise.reject(workerScript); + } + }); + break; + case "Literal": + return Promise.resolve(exp.value); + break; + case "Identifier": + if (!(exp.name in env.vars)){ + return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined")); + } + return Promise.resolve(env.get(exp.name)) + break; + case "ExpressionStatement": + return evaluate(exp.expression, workerScript); + break; + case "ArrayExpression": + var argPromises = exp.elements.map(function(arg) { + return evaluate(arg, workerScript); + }); + return Promise.all(argPromises).then(function(array) { + return Promise.resolve(array) + }); + break; + case "CallExpression": + return evaluate(exp.callee, workerScript).then(function(func) { + return Promise.map(exp.arguments, function(arg) { + return evaluate(arg, workerScript); + }).then(function(args) { + if (func instanceof __WEBPACK_IMPORTED_MODULE_8__utils_acorn_js__["Node"]) { //Player-defined function + //Create new Environment for the function + //Should be automatically garbage collected... + var funcEnv = env.extend(); + + //Define function arguments in this new environment + for (var i = 0; i < func.params.length; ++i) { + var arg; + if (i >= args.length) { + arg = null; + } else { + arg = args[i]; + } + funcEnv.def(func.params[i].name, arg); + } + + //Create a new WorkerScript for this function evaluation + var funcWorkerScript = new __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */](workerScript.scriptRef); + funcWorkerScript.serverIp = workerScript.serverIp; + funcWorkerScript.env = funcEnv; + workerScript.fnWorker = funcWorkerScript; + + return evaluate(func.body, funcWorkerScript).then(function(res) { + //If the function finished successfuly, that means there + //was no return statement since a return statement rejects. So resolve to null + workerScript.fnWorker = null; + return Promise.resolve(null); + }).catch(function(e) { + if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { + //Return statement from function + return Promise.resolve(e[1]); + workerScript.fnWorker = null; + } else if (Object(__WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__["f" /* isString */])(e)) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); + } else if (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]) { + //Parse out the err message from the WorkerScript and re-reject + var errorMsg = e.errorMessage; + var errorTextArray = errorMsg.split("|"); + if (errorTextArray.length === 4) { + errorMsg = errorTextArray[3]; + return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg)); + } else { + if (env.stopFlag) { + return Promise.reject(workerScript); + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function")); + } + } + } else if (e instanceof Error) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString())); + } + }); + } else if (exp.callee.type == "MemberExpression"){ + return evaluate(exp.callee.object, workerScript).then(function(object) { + try { + var res = func.apply(object,args); + return Promise.resolve(res); + } catch (e) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); + } + }); + } else { + try { + var out = func.apply(null,args); + if (out instanceof Promise){ + return out.then(function(res) { + return Promise.resolve(res) + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + return Promise.resolve(out); + } + } catch (e) { + if (isScriptErrorMessage(e)) { + return Promise.reject(e); + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); + } + } + } + }); + }); + break; + case "MemberExpression": + return evaluate(exp.object, workerScript).then(function(object) { + if (exp.computed){ + return evaluate(exp.property, workerScript).then(function(index) { + if (index >= object.length) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays")); + } + return Promise.resolve(object[index]); + }).catch(function(e) { + if (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] || isScriptErrorMessage(e)) { + return Promise.reject(e); + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression")); + } + + }); + } else { + try { + return Promise.resolve(object[exp.property.name]) + } catch (e) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString())); + } + } + }); + break; + case "LogicalExpression": + case "BinaryExpression": + return evalBinary(exp, workerScript); + break; + case "UnaryExpression": + return evalUnary(exp, workerScript); + break; + case "AssignmentExpression": + return evalAssignment(exp, workerScript); + break; + case "UpdateExpression": + if (exp.argument.type==="Identifier"){ + if (exp.argument.name in env.vars){ + if (exp.operator === "++" || exp.operator === "--") { + switch (exp.operator) { + case "++": + env.set(exp.argument.name,env.get(exp.argument.name)+1); + break; + case "--": + env.set(exp.argument.name,env.get(exp.argument.name)-1); + break; + default: break; + } + return Promise.resolve(env.get(exp.argument.name)); + } + //Not sure what prefix UpdateExpressions there would be besides ++/-- + if (exp.prefix){ + return Promise.resolve(env.get(exp.argument.name)) + } + switch (exp.operator){ + default: + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported")); + } + return Promise.resolve(env.get(exp.argument.name)) + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined")); + } + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier")); + } + break; + case "EmptyStatement": + return Promise.resolve(false); + break; + case "ReturnStatement": + return evaluate(exp.argument, workerScript).then(function(res) { + return Promise.reject(["RETURNSTATEMENT", res]); + }); + break; + case "BreakStatement": + return Promise.reject("BREAKSTATEMENT"); + break; + case "ContinueStatement": + return Promise.reject("CONTINUESTATEMENT"); + break; + case "IfStatement": + return evaluateIf(exp, workerScript); + break; + case "SwitchStatement": + var lineNum = getErrorLineNumber(exp, workerScript); + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript (line " + (lineNum+1) + ")")); + break; + case "WhileStatement": + return evaluateWhile(exp, workerScript).then(function(res) { + return Promise.resolve(res); + }).catch(function(e) { + if (e == "BREAKSTATEMENT" || + (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "BREAKSTATEMENT")) { + return Promise.resolve("whileLoopBroken"); + } else { + return Promise.reject(e); + } + }); + break; + case "ForStatement": + return evaluate(exp.init, workerScript).then(function(expInit) { + return evaluateFor(exp, workerScript); + }).then(function(forLoopRes) { + return Promise.resolve("forLoopDone"); + }).catch(function(e) { + if (e == "BREAKSTATEMENT" || + (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "BREAKSTATEMENT")) { + return Promise.resolve("forLoopBroken"); + } else { + return Promise.reject(e); + } + }); + break; + case "FunctionDeclaration": + if (exp.id && exp.id.name) { + env.set(exp.id.name, exp); + return Promise.resolve(true); + } else { + var lineNum = getErrorLineNumber(exp, workerScript); + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration at line " + lineNum+1)); + } + break; + default: + var lineNum = getErrorLineNumber(exp, workerScript); + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + " (line " + (lineNum+1) + "). This is currently unsupported in Netscript")); + break; + } //End switch + }).catch(function(e) { + return Promise.reject(e); + }); // End Promise +} + +function evalBinary(exp, workerScript){ + return evaluate(exp.left, workerScript).then(function(expLeft) { + //Short circuiting + if (expLeft == true && exp.operator === "||") { + return Promise.resolve(true); + } + if (expLeft == false && exp.operator === "&&") { + return Promise.resolve(false); + } + return evaluate(exp.right, workerScript).then(function(expRight) { + switch (exp.operator){ + case "===": + case "==": + return Promise.resolve(expLeft===expRight); + break; + case "!==": + case "!=": + return Promise.resolve(expLeft!==expRight); + break; + case "<": + return Promise.resolve(expLeft": + return Promise.resolve(expLeft>expRight); + break; + case ">=": + return Promise.resolve(expLeft>=expRight); + break; + case "+": + return Promise.resolve(expLeft+expRight); + break; + case "-": + return Promise.resolve(expLeft-expRight); + break; + case "*": + return Promise.resolve(expLeft*expRight); + break; + case "/": + if (expRight === 0) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero")); + } else { + return Promise.resolve(expLeft/expRight); + } + break; + case "%": + return Promise.resolve(expLeft%expRight); + break; + case "in": + return Promise.resolve(expLeft in expRight); + break; + case "instanceof": + return Promise.resolve(expLeft instanceof expRight); + break; + case "||": + return Promise.resolve(expLeft || expRight); + break; + case "&&": + return Promise.resolve(expLeft && expRight); + break; + default: + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unsupported operator: " + exp.operator)); + } + }); + }); +} + +function evalUnary(exp, workerScript){ + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + return evaluate(exp.argument, workerScript).then(function(res) { + if (exp.operator == "!") { + return Promise.resolve(!res); + } else if (exp.operator == "-") { + if (isNaN(res)) { + return Promise.resolve(res); + } else { + return Promise.resolve(-1 * res); + } + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator)); + } + }); +} + +//Takes in a MemberExpression that should represent a Netscript array (possible multidimensional) +//The return value is an array of the form: +// [0th index (leftmost), array name, 1st index, 2nd index, ...] +function getArrayElement(exp, workerScript) { + var indices = []; + return evaluate(exp.property, workerScript).then(function(idx) { + if (isNaN(idx)) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx)); + } else { + if (exp.object.name === undefined && exp.object.object) { + return getArrayElement(exp.object, workerScript).then(function(res) { + res.push(idx); + indices = res; + return Promise.resolve(indices); + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + indices.push(idx); + indices.push(exp.object.name); + return Promise.resolve(indices); + } + } + }); +} + +function evalAssignment(exp, workerScript) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + + if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left))); + } + + if (exp.operator !== "=" && !(exp.left.name in env.vars)){ + return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined")); + } + + return evaluate(exp.right, workerScript).then(function(expRight) { + if (exp.left.type == "MemberExpression") { + //Assign to array element + //Array object designed by exp.left.object.name + //Index designated by exp.left.property + return getArrayElement(exp.left, workerScript).then(function(res) { + if (!(res instanceof Array) || res.length < 2) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error evaluating array assignment. This is (probably) a bug please report to game dev")); + } + + //The array name is the second value + var arrName = res.splice(1, 1); + arrName = arrName[0]; + + env.setArrayElement(arrName, res, expRight); + return Promise.resolve(false); + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + //Other assignments + try { + switch (exp.operator) { + case "=": + env.set(exp.left.name,expRight); + break; + case "+=": + env.set(exp.left.name,env.get(exp.left.name) + expRight); + break; + case "-=": + env.set(exp.left.name,env.get(exp.left.name) - expRight); + break; + case "*=": + env.set(exp.left.name,env.get(exp.left.name) * expRight); + break; + case "/=": + env.set(exp.left.name,env.get(exp.left.name) / expRight); + break; + case "%=": + env.set(exp.left.name,env.get(exp.left.name) % expRight); + break; + default: + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented")); + } + return Promise.resolve(false); + } catch (e) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString())); + } + } + }); +} + +function evaluateIf(exp, workerScript, i) { + var env = workerScript.env; + return evaluate(exp.test, workerScript).then(function(condRes) { + if (condRes) { + return evaluate(exp.consequent, workerScript).then(function(res) { + return Promise.resolve(true); + }, function(e) { + return Promise.reject(e); + }); + } else if (exp.alternate) { + return evaluate(exp.alternate, workerScript).then(function(res) { + return Promise.resolve(true); + }, function(e) { + return Promise.reject(e); + }); + } else { + return Promise.resolve("endIf"); + } + }); +} + +//Evaluate the looping part of a for loop (Initialization block is NOT done in here) +function evaluateFor(exp, workerScript) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + return new Promise(function(resolve, reject) { + function recurse() { + //Don't return a promise so the promise chain is broken on each recursion (saving memory) + evaluate(exp.test, workerScript).then(function(resCond) { + if (resCond) { + return evaluate(exp.body, workerScript).then(function(res) { + return evaluate(exp.update, workerScript); + }).catch(function(e) { + if (e == "CONTINUESTATEMENT" || + (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "CONTINUESTATEMENT")) { + //Continue statement, recurse to next iteration + return evaluate(exp.update, workerScript).then(function(resPostloop) { + return evaluateFor(exp, workerScript); + }).then(function(foo) { + return Promise.resolve("endForLoop"); + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + return Promise.reject(e); + } + }).then(recurse, reject).catch(function(e) { + return Promise.reject(e); + }); + } else { + resolve(); + } + }).catch(function(e) { + reject(e); + }); + } + recurse(); + }); + /* + return evaluate(exp.test, workerScript).then(function(resCond) { + if (resCond) { + //Execute code (body), update, and then recurse + return evaluate(exp.body, workerScript).then(function(resCode) { + return evaluate(exp.update, workerScript); + }).catch(function(e) { + if (e == "CONTINUESTATEMENT" || + (e instanceof WorkerScript && e.errorMessage == "CONTINUESTATEMENT")) { + //Continue statement, recurse to next iteration + return evaluate(exp.update, workerScript).then(function(resPostloop) { + return evaluateFor(exp, workerScript); + }).then(function(foo) { + return Promise.resolve("endForLoop"); + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + return Promise.reject(e); + } + }).then(function(resPostloop) { + return evaluateFor(exp, workerScript); + }).then(function(foo) { + return Promise.resolve("endForLoop"); + }); + } else { + return Promise.resolve("endForLoop"); //Doesn't need to resolve to any particular value + } + });*/ +} + +function evaluateWhile(exp, workerScript) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + return new Promise(function (resolve, reject) { + function recurse() { + //Don't return a promise so the promise chain is broken on each recursion (saving memory) + evaluate(exp.test, workerScript).then(function(resCond) { + if (resCond) { + return evaluate(exp.body, workerScript).catch(function(e) { + if (e == "CONTINUESTATEMENT" || + (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "CONTINUESTATEMENT")) { + //Continue statement, recurse + return evaluateWhile(exp, workerScript).then(function(foo) { + return Promise.resolve("endWhileLoop"); + }, function(e) { + return Promise.reject(e); + }); + } else { + return Promise.reject(e); + } + }).then(recurse, reject).catch(function(e) { + return Promise.reject(e); + }); + } else { + resolve(); + } + }).catch(function(e) { + reject(e); + }); + } + recurse(); + }); +} + +function evaluateProg(exp, workerScript, index) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + if (index >= exp.body.length) { + return Promise.resolve("progFinished"); + } else { + //Evaluate this line of code in the prog + //After the code finishes evaluating, evaluate the next line recursively + return evaluate(exp.body[index], workerScript).then(function(res) { + return evaluateProg(exp, workerScript, index + 1); + }).then(function(res) { + return Promise.resolve(workerScript); + }).catch(function(e) { + return Promise.reject(e); + }); + } +} + +function killNetscriptDelay(workerScript) { + /* + if (workerScript instanceof WorkerScript) { + if (workerScript.delay) { + workerScript.delay.cancel(); + } + } + */ + if (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]) { + if (workerScript.delay) { + clearTimeout(workerScript.delay); + workerScript.delayResolve(); + } + } +} + +function netscriptDelay(time, workerScript) { + /* + workerScript.delay = new Promise(function(resolve, reject, onCancel) { + Promise.delay(time).then(function() { + resolve(); + workerScript.delay = null; + }); + onCancel(function() { + console.log("Cancelling and rejecting this Promise"); + reject(workerScript); + }) + }); + return workerScript.delay; + */ + return new Promise(function(resolve, reject) { + workerScript.delay = setTimeout(()=>{ + workerScript.delay = null; + resolve(); + }, time); + workerScript.delayResolve = resolve; + }); +} + +function makeRuntimeRejectMsg(workerScript, msg) { + return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg; +} + +/* +function apply_op(op, a, b) { + function num(x) { + if (typeof x != "number") + throw new Error("Expected number but got " + x); + return x; + } + function div(x) { + if (num(x) == 0) + throw new Error("Divide by zero"); + return x; + } + switch (op) { + case "+": return a + b; + case "-": return num(a) - num(b); + case "*": return num(a) * num(b); + case "/": return num(a) / div(b); + case "%": return num(a) % div(b); + case "&&": return a !== false && b; + case "||": return a !== false ? a : b; + case "<": return num(a) < num(b); + case ">": return num(a) > num(b); + case "<=": return num(a) <= num(b); + case ">=": return num(a) >= num(b); + case "==": return a === b; + case "!=": return a !== b; + } + throw new Error("Can't apply operator " + op); +} +*/ + +//Run a script from inside a script using run() command +function runScriptFromScript(server, scriptname, args, workerScript, threads=1) { + //Check if the script is already running + var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_7__Script_js__["d" /* findRunningScript */])(scriptname, args, server); + if (runningScriptObj != null) { + workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname); + return Promise.resolve(false); + } + + //Check if the script exists and if it does run it + for (var i = 0; i < server.scripts.length; ++i) { + if (server.scripts[i].filename == scriptname) { + //Check for admin rights and that there is enough RAM availble to run + var script = server.scripts[i]; + var ramUsage = script.ramUsage; + threads = Math.round(Number(threads)); //Convert to number and round + ramUsage = ramUsage * threads * Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultithreadingRAMCost, threads-1); + var ramAvailable = server.maxRam - server.ramUsed; + + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot run script " + scriptname + " on " + server.hostname + " because you do not have root access!"); + return Promise.resolve(false); + } else if (ramUsage > ramAvailable){ + workerScript.scriptRef.log("Cannot run script " + scriptname + "(t=" + threads + ") on " + server.hostname + " because there is not enough available RAM!"); + return Promise.resolve(false); + } else { + //Able to run script + workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["f" /* printArray */])(args) + ". May take a few seconds to start up..."); + var runningScriptObj = new __WEBPACK_IMPORTED_MODULE_7__Script_js__["b" /* RunningScript */](script, args); + runningScriptObj.threads = threads; + server.runningScripts.push(runningScriptObj); //Push onto runningScripts + Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["c" /* addWorkerScript */])(runningScriptObj, server); + return Promise.resolve(true); + } + } + } + workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname); + return Promise.resolve(false); +} + +//Takes in a +function getErrorLineNumber(exp, workerScript) { + var code = workerScript.scriptRef.scriptRef.code; + + //Split code up to the start of the node + code = code.substring(0, exp.start); + return (code.match(/\n/g) || []).length; +} + +function isScriptErrorMessage(msg) { + if (!Object(__WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__["f" /* isString */])(msg)) {return false;} + let splitMsg = msg.split("|"); + if (splitMsg.length != 4){ + return false; + } + var ip = splitMsg[1]; + if (!Object(__WEBPACK_IMPORTED_MODULE_10__utils_IPAddress_js__["c" /* isValidIPAddress */])(ip)) { + return false; + } + return true; +} + +//The same as Player's calculateHackingChance() function but takes in the server as an argument +function scriptCalculateHackingChance(server) { + var difficultyMult = (100 - server.hackDifficulty) / 100; + var skillMult = (1.75 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill) + (0.2 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence); + var skillChance = (skillMult - server.requiredHackingSkill) / skillMult; + var chance = skillChance * difficultyMult * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult; + if (chance > 1) {return 1;} + if (chance < 0) {return 0;} + else {return chance;} +} + +//The same as Player's calculateHackingTime() function but takes in the server as an argument +function scriptCalculateHackingTime(server) { + var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; + var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50 + (0.1 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence)); + var hackingTime = 5 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds + return hackingTime; +} + +//The same as Player's calculateExpGain() function but takes in the server as an argument +function scriptCalculateExpGain(server) { + if (server.baseDifficulty == null) { + server.baseDifficulty = server.hackDifficulty; + } + return (server.baseDifficulty * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult * 0.3 + 3) * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].HackExpGain; +} + +//The same as Player's calculatePercentMoneyHacked() function but takes in the server as an argument +function scriptCalculatePercentMoneyHacked(server) { + var difficultyMult = (100 - server.hackDifficulty) / 100; + var skillMult = (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill - (server.requiredHackingSkill - 1)) / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill; + var percentMoneyHacked = difficultyMult * skillMult * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult / 240; + if (percentMoneyHacked < 0) {return 0;} + if (percentMoneyHacked > 1) {return 1;} + return percentMoneyHacked * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].ScriptHackMoney; +} + +//Amount of time to execute grow() in milliseconds +function scriptCalculateGrowTime(server) { + var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; + var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50 + (0.1 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence)); + var growTime = 16 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds + return growTime * 1000; +} + +//Amount of time to execute weaken() in milliseconds +function scriptCalculateWeakenTime(server) { + var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; + var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50 + (0.1 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence)); + var weakenTime = 20 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds + return weakenTime * 1000; +} + + + + +/***/ }), +/* 37 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Environment; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__NetscriptFunctions_js__ = __webpack_require__(22); + +/* Environment + * NetScript program environment + */ +function Environment(workerScript,parent) { + if (parent){ + //Create a copy of parent's variables + //this.vars = parent.vars; + this.vars = Object.assign({}, parent.vars); + } else { + this.vars = Object(__WEBPACK_IMPORTED_MODULE_0__NetscriptFunctions_js__["a" /* NetscriptFunctions */])(workerScript); + } + this.parent = parent; + this.stopFlag = false; +} +Environment.prototype = { + //Create a "subscope", which is a new new "sub-environment" + //The subscope is linked to this through its parent variable + extend: function() { + return new Environment(null, this); + }, + + //Finds the scope where the variable with the given name is defined + lookup: function(name) { + var scope = this; + while (scope) { + if (Object.prototype.hasOwnProperty.call(scope.vars, name)) { + return scope; + } + scope = scope.parent; + } + return null; + }, + + //Get the current value of a variable + get: function(name) { + if (name in this.vars) { + return this.vars[name]; + } + throw new Error("Undefined variable " + name); + }, + + //Sets the value of a variable in any scope + set: function(name, value) { + var scope = this.lookup(name); + + //If scope has a value, then this variable is already set in a higher scope, so + //set is there. Otherwise, create a new variable in the local scope + if (scope !== null) { + return scope.vars[name] = value; + } else { + return this.vars[name] = value; + } + }, + + setArrayElement: function(name, idx, value) { + if (!(idx instanceof Array)) { + throw new Error("idx parameter is not an Array"); + } + var scope = this.lookup(name); + if (!scope && this.parent) { + throw new Error("Undefined variable " + name); + } + var arr = (scope || this).vars[name]; + if (!(arr.constructor === Array || arr instanceof Array)) { + throw new Error("Variable is not an array: " + name); + } + var res = arr; + for (var iterator = 0; iterator < idx.length-1; ++iterator) { + var i = idx[iterator]; + if (!(res instanceof Array) || i >= res.length) { + throw new Error("Out-of-bounds array access"); + } + res = res[i]; + } + return res[idx[idx.length-1]] = value; + }, + /* + setArrayElement: function(name, idx, value) { + var scope = this.lookup(name); + if (!scope && this.parent) { + console.log("Here"); + throw new Error("Undefined variable " + name); + } + var arr = (scope || this).vars[name]; + if (!(arr.constructor === Array || arr instanceof Array)) { + throw new Error("Variable is not an array: " + name); + } + return (scope || this).vars[name][idx] = value; + },*/ + + //Creates (or overwrites) a variable in the current scope + def: function(name, value) { + return this.vars[name] = value; + } +}; + + + + +/***/ }), +/* 38 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* unused harmony export hacknetNodesInit */ +/* unused harmony export HacknetNode */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return purchaseHacknet; }); +/* unused harmony export updateTotalHacknetProduction */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getCostOfNextHacknetNode; }); +/* unused harmony export updateHacknetNodesMultiplierButtons */ +/* unused harmony export getMaxNumberLevelUpgrades */ +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return displayHacknetNodesContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return updateHacknetNodesContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return processAllHacknetNodeEarnings; }); +/* unused harmony export getHacknetNode */ +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__engine_js__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__ = __webpack_require__(26); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__ = __webpack_require__(2); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__ = __webpack_require__(8); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__ = __webpack_require__(4); + + + + + + + + + + +/* HacknetNode.js */ +function hacknetNodesInit() { + var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); + mult1x.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 1; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); + var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); + mult5x.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 5; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); + var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); + mult10x.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 10; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); + var multMax = document.getElementById("hacknet-nodes-max-multiplier"); + multMax.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 0; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); +} +document.addEventListener("DOMContentLoaded", hacknetNodesInit, false); + +function HacknetNode(name) { + this.level = 1; + this.ram = 1; //GB + this.cores = 1; + + this.name = name; + + this.totalMoneyGenerated = 0; + this.onlineTimeSeconds = 0; + + this.moneyGainRatePerSecond = 0; +} + +HacknetNode.prototype.updateMoneyGainRate = function() { + //How much extra $/s is gained per level + var gainPerLevel = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMoneyGainPerLevel; + + this.moneyGainRatePerSecond = (this.level * gainPerLevel) * + Math.pow(1.035, this.ram-1) * + ((this.cores + 5) / 6) * + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_money_mult * + __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].HacknetNodeMoney; + if (isNaN(this.moneyGainRatePerSecond)) { + this.moneyGainRatePerSecond = 0; + Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Error in calculating Hacknet Node production. Please report to game developer"); + } + + updateTotalHacknetProduction(); +} + +HacknetNode.prototype.calculateLevelUpgradeCost = function(levels=1) { + if (levels < 1) {return 0;} + var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeLevelMult; + var totalMultiplier = 0; //Summed + var currLevel = this.level; + for (var i = 0; i < levels; ++i) { + totalMultiplier += Math.pow(mult, currLevel); + ++currLevel; + } + return __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNode / 2 * totalMultiplier * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_level_cost_mult; +} + +//Wrapper function for Netscript +HacknetNode.prototype.getLevelUpgradeCost = function(levels=1) { + return this.calculateLevelUpgradeCost(levels); +} + +HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) { + var cost = this.calculateLevelUpgradeCost(levels); + if (isNaN(cost) || levels < 0) {return false;} + if (this.level + levels > __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel) { + var diff = Math.max(0, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - this.level); + return this.purchaseLevelUpgrade(diff); + } + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;} + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); + this.level += levels; + this.updateMoneyGainRate(); + return true; +} + +//Wrapper function for Netscript +HacknetNode.prototype.upgradeLevel = function(levels=1) { + return this.purchaseLevelUpgrade(levels); +} + +HacknetNode.prototype.calculateRamUpgradeCost = function() { + var numUpgrades = Math.log2(this.ram); + + //Calculate cost + //Base cost of RAM is 50k per 1GB, increased by some multiplier for each time RAM is upgraded + var baseCost = this.ram * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHacknetNode; + var mult = Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeRamMult, numUpgrades); + return baseCost * mult * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult; +} + +//Wrapper function for Netscript +HacknetNode.prototype.getRamUpgradeCost = function() { + return this.calculateRamUpgradeCost(); +} + +HacknetNode.prototype.purchaseRamUpgrade = function() { + var cost = this.calculateRamUpgradeCost(); + if (isNaN(cost)) {return false;} + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;} + if (this.ram >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxRam) {return false;} + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); + this.ram *= 2; //Ram is always doubled + this.updateMoneyGainRate(); + return true; +} + +//Wrapper function for Netscript +HacknetNode.prototype.upgradeRam = function() { + return this.purchaseRamUpgrade(); +} + +HacknetNode.prototype.calculateCoreUpgradeCost = function() { + var coreBaseCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNodeCore; + var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeCoreMult; + return coreBaseCost * Math.pow(mult, this.cores-1) * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_core_cost_mult; +} + +//Wrapper function for Netscript +HacknetNode.prototype.getCoreUpgradeCost = function() { + return this.calculateCoreUpgradeCost(); +} + +HacknetNode.prototype.purchaseCoreUpgrade = function() { + var cost = this.calculateCoreUpgradeCost(); + if (isNaN(cost)) {return false;} + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;} + if (this.cores >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxCores) {return false;} + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); + ++this.cores; + this.updateMoneyGainRate(); + return true; +} + +//Wrapper function for Netscript +HacknetNode.prototype.upgradeCore = function() { + return this.purchaseCoreUpgrade(); +} + +/* Saving and loading HackNets */ +HacknetNode.prototype.toJSON = function() { + return Object(__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["b" /* Generic_toJSON */])("HacknetNode", this); +} + +HacknetNode.fromJSON = function(value) { + return Object(__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(HacknetNode, value.data); +} + +__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["c" /* Reviver */].constructors.HacknetNode = HacknetNode; + + +function purchaseHacknet() { + /* INTERACTIVE TUTORIAL */ + if (__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["b" /* iTutorialIsRunning */]) { + if (__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["a" /* currITutorialStep */] == __WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["e" /* iTutorialSteps */].HacknetNodesIntroduction) { + Object(__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["c" /* iTutorialNextStep */])(); + } else { + return; + } + } + + /* END INTERACTIVE TUTORIAL */ + + var cost = getCostOfNextHacknetNode(); + if (isNaN(cost)) {throw new Error("Cost is NaN"); return;} + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) { + //dialogBoxCreate("You cannot afford to purchase a Hacknet Node!"); + return false; + } + + //Auto generate a name for the node for now...TODO + var numOwned = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; + var name = "hacknet-node-" + numOwned; + var node = new HacknetNode(name); + node.updateMoneyGainRate(); + + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.push(node); + + displayHacknetNodesContent(); + updateTotalHacknetProduction(); + return numOwned; +} + +//Calculates the total production from all HacknetNodes +function updateTotalHacknetProduction() { + var total = 0; + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { + total += __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i].moneyGainRatePerSecond; + } + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].totalHacknetNodeProduction = total; +} + +function getCostOfNextHacknetNode() { + //Cost increases exponentially based on how many you own + var numOwned = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; + var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodePurchaseNextMult; + return __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNode * Math.pow(mult, numOwned) * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult; +} + +var hacknetNodePurchaseMultiplier = 1; +function updateHacknetNodesMultiplierButtons() { + var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); + var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); + var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); + var multMax = document.getElementById("hacknet-nodes-max-multiplier"); + mult1x.setAttribute("class", "a-link-button"); + mult5x.setAttribute("class", "a-link-button"); + mult10x.setAttribute("class", "a-link-button"); + multMax.setAttribute("class", "a-link-button"); + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length == 0) { + mult1x.setAttribute("class", "a-link-button-inactive"); + mult5x.setAttribute("class", "a-link-button-inactive"); + mult10x.setAttribute("class", "a-link-button-inactive"); + multMax.setAttribute("class", "a-link-button-inactive"); + } else if (hacknetNodePurchaseMultiplier == 1) { + mult1x.setAttribute("class", "a-link-button-inactive"); + } else if (hacknetNodePurchaseMultiplier == 5) { + mult5x.setAttribute("class", "a-link-button-inactive"); + } else if (hacknetNodePurchaseMultiplier == 10) { + mult10x.setAttribute("class", "a-link-button-inactive"); + } else { + multMax.setAttribute("class", "a-link-button-inactive"); + } +} + +//Calculate the maximum number of times the Player can afford to upgrade +//a Hacknet Node's level" +function getMaxNumberLevelUpgrades(nodeObj) { + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(1))) {return 0;} + var min = 1; + var max = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel-1; + var levelsToMax = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - nodeObj.level; + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax))) { + return levelsToMax; + } + + while (min <= max) { + var curr = (min + max) / 2 | 0; + if (curr != __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel && + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(curr)) && + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(curr+1))) { + return Math.min(levelsToMax, curr); + } else if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(curr))) { + max = curr - 1; + } else if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(curr))) { + min = curr + 1; + } else { + return Math.min(levelsToMax, curr); + } + } +} + +//Creates Hacknet Node DOM elements when the page is opened +function displayHacknetNodesContent() { + //Update Hacknet Nodes button + var newPurchaseButton = Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-purchase-button"); + + newPurchaseButton.addEventListener("click", function() { + purchaseHacknet(); + return false; + }); + + //Handle Purchase multiplier buttons + updateHacknetNodesMultiplierButtons(); + + //Remove all old hacknet Node DOM elements + var hacknetNodesList = document.getElementById("hacknet-nodes-list"); + while (hacknetNodesList.firstChild) { + hacknetNodesList.removeChild(hacknetNodesList.firstChild); + } + + //Then re-create them + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { + createHacknetNodeDomElement(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]); + } + updateHacknetNodesContent(); +} + +//Update information on all Hacknet Node DOM elements +function updateHacknetNodesContent() { + //Set purchase button to inactive if not enough money, and update its price display + var cost = getCostOfNextHacknetNode(); + var purchaseButton = document.getElementById("hacknet-nodes-purchase-button"); + purchaseButton.innerHTML = "Purchase Hacknet Node - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2); + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) { + purchaseButton.setAttribute("class", "a-link-button-inactive"); + } else { + purchaseButton.setAttribute("class", "a-link-button"); + } + + //Update player's money + var moneyElem = document.getElementById("hacknet-nodes-money"); + moneyElem.innerHTML = "Money: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.toNumber(), 2) + "
" + + "Total production from all Hacknet Nodes: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].totalHacknetNodeProduction, 2) + " / second"; + + //Update information in each owned hacknet node + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { + updateHacknetNodeDomElement(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]); + } +} + +//Creates a single Hacknet Node DOM element +function createHacknetNodeDomElement(nodeObj) { + var nodeName = nodeObj.name; + + var listItem = document.createElement("li"); + listItem.setAttribute("class", "hacknet-node"); + + var span = document.createElement("span"); + span.style.display = "inline"; + + var buttonDiv = document.createElement("div"); + buttonDiv.setAttribute("class", "hacknet-node-button-div"); + + //Text + var txt = document.createElement("p"); + //txt.setAttribute("id", "hacknet-node-text-" + nodeName); + txt.id = "hacknet-node-text-" + nodeName; + + //Upgrade buttons + var upgradeLevelButton = document.createElement("a"); + var upgradeRamButton = document.createElement("a"); + var upgradeCoreButton = document.createElement("a"); + + //upgradeLevelButton.setAttribute("id", "hacknet-node-upgrade-level-" + nodeName); + upgradeLevelButton.id = "hacknet-node-upgrade-level-" + nodeName; + upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); + upgradeLevelButton.addEventListener("click", function() { + var numUpgrades = hacknetNodePurchaseMultiplier; + if (hacknetNodePurchaseMultiplier == 0) { + numUpgrades = getMaxNumberLevelUpgrades(nodeObj); + } + nodeObj.purchaseLevelUpgrade(numUpgrades); + updateHacknetNodesContent(); + return false; + }); + //upgradeRamButton.setAttribute("id", "hacknet-node-upgrade-ram-" + nodeName); + upgradeRamButton.id = "hacknet-node-upgrade-ram-" + nodeName; + upgradeRamButton.setAttribute("class", "a-link-button-inactive"); + upgradeRamButton.addEventListener("click", function() { + nodeObj.purchaseRamUpgrade(); + updateHacknetNodesContent(); + return false; + }); + //upgradeCoreButton.setAttribute("id", "hacknet-node-upgrade-core-" + nodeName); + upgradeCoreButton.id = "hacknet-node-upgrade-core-" + nodeName; + upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); + upgradeCoreButton.addEventListener("click", function() { + nodeObj.purchaseCoreUpgrade(); + updateHacknetNodesContent(); + return false; + }); + + //Put all the components together in the li element + span.appendChild(txt); + buttonDiv.appendChild(upgradeLevelButton); + buttonDiv.appendChild(upgradeRamButton); + buttonDiv.appendChild(upgradeCoreButton); + span.appendChild(buttonDiv); + listItem.appendChild(span); + + document.getElementById("hacknet-nodes-list").appendChild(listItem); + + //Set the text and stuff inside the DOM element + updateHacknetNodeDomElement(nodeObj); +} + +//Updates information on a single hacknet node DOM element +function updateHacknetNodeDomElement(nodeObj) { + var nodeName = nodeObj.name; + var txt = document.getElementById("hacknet-node-text-" + nodeName); + if (txt == null) {throw new Error("Cannot find text element");} + txt.innerHTML = "Node name: " + nodeName + "
" + + "Production: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(nodeObj.totalMoneyGenerated, 2) + + " ($" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(nodeObj.moneyGainRatePerSecond, 2) + " / second)
" + + "Level: " + nodeObj.level + "
" + + "RAM: " + nodeObj.ram + "GB
" + + "Cores: " + nodeObj.cores; + + //Upgrade level + var upgradeLevelButton = document.getElementById("hacknet-node-upgrade-level-" + nodeName); + if (upgradeLevelButton == null) {throw new Error("Cannot find upgrade level button element");} + if (nodeObj.level >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel) { + upgradeLevelButton.innerHTML = "MAX LEVEL"; + upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); + } else { + var multiplier = 0; + if (hacknetNodePurchaseMultiplier == 0) { + //Max + multiplier = getMaxNumberLevelUpgrades(nodeObj); + } else { + var levelsToMax = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - nodeObj.level; + multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier); + } + + var upgradeLevelCost = nodeObj.calculateLevelUpgradeCost(multiplier); + upgradeLevelButton.innerHTML = "Upgrade Hacknet Node Level x" + multiplier + + " - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeLevelCost, 2); + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeLevelCost)) { + upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); + } else { + upgradeLevelButton.setAttribute("class", "a-link-button"); + } + } + + //Upgrade RAM + var upgradeRamButton = document.getElementById("hacknet-node-upgrade-ram-" + nodeName); + if (upgradeRamButton == null) {throw new Error("Cannot find upgrade ram button element");} + if (nodeObj.ram >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxRam) { + upgradeRamButton.innerHTML = "MAX RAM"; + upgradeRamButton.setAttribute("class", "a-link-button-inactive"); + } else { + var upgradeRamCost = nodeObj.calculateRamUpgradeCost(); + upgradeRamButton.innerHTML = "Upgrade Hacknet Node RAM - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeRamCost, 2); + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeRamCost)) { + upgradeRamButton.setAttribute("class", "a-link-button-inactive"); + } else { + upgradeRamButton.setAttribute("class", "a-link-button"); + } + } + + //Upgrade Cores + var upgradeCoreButton = document.getElementById("hacknet-node-upgrade-core-" + nodeName); + if (upgradeCoreButton == null) {throw new Error("Cannot find upgrade cores button element");} + if (nodeObj.cores >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxCores) { + upgradeCoreButton.innerHTML = "MAX CORES"; + upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); + } else { + var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost(); + upgradeCoreButton.innerHTML = "Purchase additional CPU Core - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeCoreCost, 2); + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeCoreCost)) { + upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); + } else { + upgradeCoreButton.setAttribute("class", "a-link-button"); + } + } +} + +function processAllHacknetNodeEarnings(numCycles) { + var total = 0; + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { + total += processSingleHacknetNodeEarnings(numCycles, __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]); + } + return total; +} + +function processSingleHacknetNodeEarnings(numCycles, nodeObj) { + var cyclesPerSecond = 1000 / __WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed; + var earningPerCycle = nodeObj.moneyGainRatePerSecond / cyclesPerSecond; + if (isNaN(earningPerCycle)) {throw new Error("Calculated Earnings is not a number");} + var totalEarnings = numCycles * earningPerCycle; + nodeObj.totalMoneyGenerated += totalEarnings; + nodeObj.onlineTimeSeconds += (numCycles * (__WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed / 1000)); + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gainMoney(totalEarnings); + return totalEarnings; +} + +function getHacknetNode(name) { + for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { + if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i].name == name) { + return __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]; + } + } + return null; +} + + + + +/***/ }), +/* 39 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + "use strict"; /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Gang; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return displayGangContent; }); @@ -38384,16 +40530,16 @@ module.exports = g; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return resetGangs; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Faction_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Faction_js__ = __webpack_require__(11); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Location_js__ = __webpack_require__(13); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__ = __webpack_require__(22); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__ = __webpack_require__(17); @@ -39428,7 +41574,7 @@ function displayGangContent() { territorySubpage.appendChild(territoryBorder); } - document.getElementById("gang-container").style.visibility = "visible"; + document.getElementById("gang-container").style.display = "block"; updateGangContent(); } @@ -39693,2152 +41839,6 @@ function setGangMemberTaskDescription(memberObj, taskName) { /* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9))) -/***/ }), -/* 35 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SourceFiles; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PlayerOwnedSourceFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return applySourceFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initSourceFiles; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BitNode_js__ = __webpack_require__(7); - - - -/* SourceFile.js */ -//Each SourceFile corresponds to a BitNode with the same number -function SourceFile(number, info="") { - var bitnodeKey = "BitNode" + number; - var bitnode = __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["b" /* BitNodes */][bitnodeKey]; - if (bitnode == null) { - throw new Error("Invalid Bit Node for this Source File"); - } - - this.n = number; - this.name = "Source-File " + number + ": " + bitnode.name; - this.lvl = 1; - this.info = info; - this.owned = false; -} - -let SourceFiles = {}; -function initSourceFiles() { - SourceFiles = {}; - SourceFiles["SourceFile1"] = new SourceFile(1, "This Source-File lets the player start with 32GB of RAM on his/her " + - "home computer. It also increases all of the player's multipliers by:

" + - "Level 1: 16%
" + - "Level 2: 24%
" + - "Level 3: 28%"); - SourceFiles["SourceFile2"] = new SourceFile(2, "This Source-File increases the player's crime success rate, crime money, and charisma " + - "multipliers by:

" + - "Level 1: 20%
" + - "Level 2: 30%
" + - "Level 3: 35%"); - SourceFiles["SourceFile3"] = new SourceFile(3); - SourceFiles["SourceFile4"] = new SourceFile(4, "This Source-File lets you access and use the Singularity Functions in every BitNode. Every " + - "level of this Source-File opens up more of the Singularity Functions you can use."); - SourceFiles["SourceFile5"] = new SourceFile(5, "This Source-File grants a special new stat called Intelligence. Intelligence " + - "is unique because it is permanent and persistent (it never gets reset back to 1). However, " + - "gaining Intelligence experience is much slower than other stats, and it is also hidden (you won't " + - "know when you gain experience and how much). Higher Intelligence levels will boost your production " + - "for many actions in the game. In addition, this Source-File will unlock the getBitNodeMultipliers() " + - "Netscript function, and will raise all of your hacking-related multipliers by:

" + - "Level 1: 4%
" + - "Level 2: 6%
" + - "Level 3: 7%"); - SourceFiles["SourceFile6"] = new SourceFile(6); - SourceFiles["SourceFile7"] = new SourceFile(7); - SourceFiles["SourceFile8"] = new SourceFile(8, "This Source-File grants the following benefits:

" + - "Level 1: Permanent access to WSE and TIX API
" + - "Level 2: Ability to short stocks in other BitNodes
" + - "Level 3: Ability to use limit/stop orders in other BitNodes

" + - "This Source-File also increases your hacking growth multipliers by: " + - "
Level 1: 8%
Level 2: 12%
Level 3: 14%"); - SourceFiles["SourceFile9"] = new SourceFile(9); - SourceFiles["SourceFile10"] = new SourceFile(10); - SourceFiles["SourceFile11"] = new SourceFile(11, "This Source-File makes it so that company favor increases BOTH the player's salary and reputation gain rate " + - "at that company by 1% per favor (rather than just the reputation gain). This Source-File also " + - " increases the player's company salary and reputation gain multipliers by:

" + - "Level 1: 24%
" + - "Level 2: 36%
" + - "Level 3: 42%
"); - SourceFiles["SourceFile12"] = new SourceFile(12); -} - -function PlayerOwnedSourceFile(number, level) { - this.n = number; - this.lvl = level; -} - -//Takes in a PlayerOwnedSourceFile as the "srcFile" argument -function applySourceFile(srcFile) { - var srcFileKey = "SourceFile" + srcFile.n; - var sourceFileObject = SourceFiles[srcFileKey]; - if (sourceFileObject == null) { - console.log("ERROR: Invalid source file number: " + srcFile.n); - return; - } - - switch(srcFile.n) { - case 1: // The Source Genesis - var mult = 0; - for (var i = 0; i < srcFile.lvl; ++i) { - mult += (16 / (Math.pow(2, i))); - } - var incMult = 1 + (mult / 100); - var decMult = 1 - (mult / 100); - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_chance_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_speed_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_money_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_grow_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].strength_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].defense_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].dexterity_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].agility_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_exp_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].strength_exp_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].defense_exp_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].dexterity_exp_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].agility_exp_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_exp_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].company_rep_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].faction_rep_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_money_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_success_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_money_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult *= decMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult *= decMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_core_cost_mult *= decMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_level_cost_mult *= decMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].work_money_mult *= incMult; - break; - case 2: //Rise of the Underworld - var mult = 0; - for (var i = 0; i < srcFile.lvl; ++i) { - mult += (20 / (Math.pow(2, i))); - } - var incMult = 1 + (mult / 100); - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_money_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_success_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_mult *= incMult; - break; - case 4: //The Singularity - //No effects, just gives access to Singularity functions - break; - case 5: //Artificial Intelligence - var mult = 0; - for (var i = 0; i < srcFile.lvl; ++i) { - mult += (4 / (Math.pow(2, i))); - } - var incMult = 1 + (mult / 100); - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_chance_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_speed_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_money_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_grow_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_exp_mult *= incMult; - break; - case 8: //Ghost of Wall Street - var mult = 0; - for (var i = 0; i < srcFile.lvl; ++i) { - mult += (8 / (Math.pow(2, i))); - } - var incMult = 1 + (mult / 100); - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_grow_mult *= incMult; - break; - case 11: //The Big Crash - var mult = 0; - for (var i = 0; i < srcFile.lvl; ++i) { - mult += (24 / (Math.pow(2, i))); - } - var incMult = 1 + (mult / 100); - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].work_money_mult *= incMult; - __WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].company_rep_mult *= incMult; - break; - default: - console.log("ERROR: Invalid source file number: " + srcFile.n); - break; - } - - sourceFileObject.owned = true; -} - - - - -/***/ }), -/* 36 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return prestigeAugmentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return prestigeSourceFile; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(25); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__ = __webpack_require__(20); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__BitNode_js__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Company_js__ = __webpack_require__(21); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__ = __webpack_require__(15); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Faction_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Location_js__ = __webpack_require__(13); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Message_js__ = __webpack_require__(24); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__NetscriptFunctions_js__ = __webpack_require__(19); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__StockMarket_js__ = __webpack_require__(29); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__Terminal_js__ = __webpack_require__(23); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js__ = __webpack_require__(28); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_16__utils_decimal_js__); - - - - - - - - - - - - - - - - - - -//Prestige by purchasing augmentation -function prestigeAugmentation() { - Object(__WEBPACK_IMPORTED_MODULE_2__BitNode_js__["c" /* initBitNodeMultipliers */])(); - - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].prestigeAugmentation(); - - //Delete all Worker Scripts objects - Object(__WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__["e" /* prestigeWorkerScripts */])(); - - var homeComp = __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].getHomeComputer(); - //Delete all servers except home computer - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["h" /* prestigeAllServers */])(); - - //Delete Special Server IPs - Object(__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["e" /* prestigeSpecialServerIps */])(); //Must be done before initForeignServers() - - //Reset home computer (only the programs) and add to AllServers - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["i" /* prestigeHomeComputer */])(homeComp); - - if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].Neurolink) && - __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].Neurolink].owned) { - homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].FTPCrackProgram); - homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram); - } - if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].CashRoot) && - __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].CashRoot].owned) { - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].setMoney(new __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js___default.a(1000000)); - homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].BruteSSHProgram); - } - - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["a" /* AddToAllServers */])(homeComp); - - //Re-create foreign servers - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["f" /* initForeignServers */])(); - - //Darkweb is purchase-able - document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button"); - - //Gain favor for Companies - for (var member in __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */]) { - if (__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */].hasOwnProperty(member)) { - __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */][member].gainFavor(); - } - } - - //Gain favor for factions - for (var member in __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */]) { - if (__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */].hasOwnProperty(member)) { - __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][member].gainFavor(); - } - } - - //Stop a Terminal action if there is onerror - if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress) { - __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress = false; - __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].finishAction(true); - } - - //Re-initialize things - This will update any changes - Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["f" /* initFactions */])(); //Factions must be initialized before augmentations - Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["g" /* initAugmentations */])(); //Calls reapplyAllAugmentations() and resets Player multipliers - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].reapplyAllSourceFiles(); - Object(__WEBPACK_IMPORTED_MODULE_3__Company_js__["h" /* initCompanies */])(); - - //Clear terminal - $("#terminal tr:not(:last)").remove(); - Object(__WEBPACK_IMPORTED_MODULE_15__Terminal_js__["c" /* postNetburnerText */])(); - - //Messages - Object(__WEBPACK_IMPORTED_MODULE_8__Message_js__["d" /* initMessages */])(); - - //Reset Stock market - if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasWseAccount) { - Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["g" /* initStockMarket */])(); - Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["i" /* initSymbolToStockMap */])(); - } - Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["m" /* setStockMarketContentCreated */])(false); - var stockMarketList = document.getElementById("stock-market-list"); - while(stockMarketList.firstChild) { - stockMarketList.removeChild(stockMarketList.firstChild); - } - - //Gang, in BitNode 2 - if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].inGang()) { - var faction = __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].gang.facName]; - if (faction instanceof __WEBPACK_IMPORTED_MODULE_6__Faction_js__["a" /* Faction */]) { - Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["h" /* joinFaction */])(faction); - } - } - - //BitNode 8: Ghost of Wall Street - if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].bitNodeN === 8) {__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].money = new __WEBPACK_IMPORTED_MODULE_16__utils_decimal_js___default.a(100000000);} - if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].bitNodeN === 8 || __WEBPACK_IMPORTED_MODULE_9__NetscriptFunctions_js__["d" /* hasWallStreetSF */]) { - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasWseAccount = true; - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasTixApiAccess = true; - } - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].resetTerminalInput(); - __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].loadTerminalContent(); - - //Red Pill - if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].TheRedPill) && - __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].TheRedPill].owned) { - var WorldDaemon = __WEBPACK_IMPORTED_MODULE_12__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon]]; - var DaedalusServer = __WEBPACK_IMPORTED_MODULE_12__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["b" /* SpecialServerNames */].DaedalusServer]]; - if (WorldDaemon && DaedalusServer) { - WorldDaemon.serversOnNetwork.push(DaedalusServer.ip); - DaedalusServer.serversOnNetwork.push(WorldDaemon.ip); - } - } -} - - -//Prestige by destroying Bit Node and gaining a Source File -function prestigeSourceFile() { - Object(__WEBPACK_IMPORTED_MODULE_2__BitNode_js__["c" /* initBitNodeMultipliers */])(); - - //Crime statistics - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].prestigeSourceFile(); - - //Delete all Worker Scripts objects - Object(__WEBPACK_IMPORTED_MODULE_10__NetscriptWorker_js__["e" /* prestigeWorkerScripts */])(); - - var homeComp = __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].getHomeComputer(); - - //Delete all servers except home computer - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["h" /* prestigeAllServers */])(); //Must be done before initForeignServers() - - //Delete Special Server IPs - Object(__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["e" /* prestigeSpecialServerIps */])(); - - //Reset home computer (only the programs) and add to AllServers - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["i" /* prestigeHomeComputer */])(homeComp); - - var srcFile1Owned = false; - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].sourceFiles.length; ++i) { - if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].sourceFiles[i].n == 1) { - srcFile1Owned = true; - } - } - if (srcFile1Owned) { - homeComp.setMaxRam(32); - } else { - homeComp.setMaxRam(8); - } - homeComp.cpuCores = 1; - - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["a" /* AddToAllServers */])(homeComp); - - //Re-create foreign servers - Object(__WEBPACK_IMPORTED_MODULE_12__Server_js__["f" /* initForeignServers */])(); - - //Darkweb is purchase-able - document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button"); - - //Reset favor for Companies - for (var member in __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */]) { - if (__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */].hasOwnProperty(member)) { - __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */][member].favor = 0; - } - } - - //Reset favor for factions - for (var member in __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */]) { - if (__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */].hasOwnProperty(member)) { - __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][member].favor = 0; - } - } - - //Stop a Terminal action if there is one - if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress) { - __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress = false; - __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].finishAction(true); - } - - //Delete all Augmentations - for (var name in __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */]) { - if (__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */].hasOwnProperty(name)) { - delete __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][name]; - } - } - - //Re-initialize things - This will update any changes - Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["f" /* initFactions */])(); //Factions must be initialized before augmentations - Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["g" /* initAugmentations */])(); //Calls reapplyAllAugmentations() and resets Player multipliers - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].reapplyAllSourceFiles(); - Object(__WEBPACK_IMPORTED_MODULE_3__Company_js__["h" /* initCompanies */])(); - - //Clear terminal - $("#terminal tr:not(:last)").remove(); - Object(__WEBPACK_IMPORTED_MODULE_15__Terminal_js__["c" /* postNetburnerText */])(); - - //Messages - Object(__WEBPACK_IMPORTED_MODULE_8__Message_js__["d" /* initMessages */])(); - - var mainMenu = document.getElementById("mainmenu-container"); - mainMenu.style.visibility = "visible"; - __WEBPACK_IMPORTED_MODULE_15__Terminal_js__["a" /* Terminal */].resetTerminalInput(); - __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].loadTerminalContent(); - - //Reinitialize Bit Node flags - Object(__WEBPACK_IMPORTED_MODULE_9__NetscriptFunctions_js__["e" /* initSingularitySFFlags */])(); - - //Reset Stock market - if (__WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].hasWseAccount) { - Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["g" /* initStockMarket */])(); - Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["i" /* initSymbolToStockMap */])(); - } - Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["m" /* setStockMarketContentCreated */])(false); - var stockMarketList = document.getElementById("stock-market-list"); - while(stockMarketList.firstChild) { - stockMarketList.removeChild(stockMarketList.firstChild); - } - - //Gain int exp - __WEBPACK_IMPORTED_MODULE_11__Player_js__["a" /* Player */].gainIntelligenceExp(5); -} - - - -/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9))) - -/***/ }), -/* 37 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return redPillFlag; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return hackWorldDaemon; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Prestige_js__ = __webpack_require__(36); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__ = __webpack_require__(35); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Terminal_js__ = __webpack_require__(23); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__ = __webpack_require__(22); - - - - - - - - - - - -/* RedPill.js - * Implements what happens when you have Red Pill augmentation and then hack the world daemon */ - -//Returns promise -function writeRedPillLine(line) { - return new Promise(function(resolve, reject) { - - var container = document.getElementById("red-pill-container"); - var pElem = document.createElement("p"); - container.appendChild(pElem); - - var promise = writeRedPillLetter(pElem, line, 0); - promise.then(function(res) { - resolve(res); - }, function(e) { - reject(e); - }); - }); -} - -function writeRedPillLetter(pElem, line, i=0) { - return new Promise(function(resolve, reject) { - setTimeout(function() { - if (i >= line.length) { - var textToShow = line.substring(0, i); - pElem.innerHTML = "> " + textToShow; - return resolve(true); - } - var textToShow = line.substring(0, i); - pElem.innerHTML = "> " + textToShow + ""; - var promise = writeRedPillLetter(pElem, line, i+1); - promise.then(function(res) { - resolve(res); - }, function(e) { - reject(e); - }); - }, 30); - }); -} - -let redPillFlag = false; -function hackWorldDaemon(currentNodeNumber) { - redPillFlag = true; - __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].loadRedPillContent(); - return writeRedPillLine("[ERROR] SEMPOOL INVALID").then(function() { - return writeRedPillLine("[ERROR] Segmentation Fault"); - }).then(function() { - return writeRedPillLine("[ERROR] SIGKILL RECVD"); - }).then(function() { - return writeRedPillLine("Dumping core..."); - }).then(function() { - return writeRedPillLine("0000 000016FA 174FEE40 29AC8239 384FEA88"); - }).then(function() { - return writeRedPillLine("0010 745F696E 2BBBE394 390E3940 248BEC23"); - }).then(function() { - return writeRedPillLine("0020 7124696B 0000FF69 74652E6F FFFF1111"); - }).then(function() { - return writeRedPillLine("----------------------------------------"); - }).then(function() { - return writeRedPillLine("Failsafe initiated..."); - }).then(function() { - return writeRedPillLine("Restarting BitNode-" + currentNodeNumber + "..."); - }).then(function() { - return writeRedPillLine("..........."); - }).then(function() { - return writeRedPillLine("..........."); - }).then(function() { - return writeRedPillLine("[ERROR] FAILED TO AUTOMATICALLY REBOOT BITNODE"); - }).then(function() { - return writeRedPillLine("..............................................") - }).then(function() { - return writeRedPillLine("..............................................") - }).then(function() { - return loadBitVerse(currentNodeNumber); - }).catch(function(e){ - console.log("ERROR: " + e.toString()); - }); -} - -//The bitNode name passed in will have a hyphen between number (e.g. BitNode-1) -//This needs to be removed -function giveSourceFile(bitNodeNumber) { - var sourceFileKey = "SourceFile"+ bitNodeNumber.toString(); - var sourceFile = __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__["b" /* SourceFiles */][sourceFileKey]; - if (sourceFile == null) { - console.log("ERROR: could not find source file for Bit node: " + bitNodeNumber); - return; - } - - //Check if player already has this source file - var alreadyOwned = false; - var ownedSourceFile = null; - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles.length; ++i) { - if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles[i].n === bitNodeNumber) { - alreadyOwned = true; - ownedSourceFile = __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles[i]; - break; - } - } - - if (alreadyOwned && ownedSourceFile) { - if (ownedSourceFile.lvl >= 3) { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("The Source-File for the BitNode you just destroyed, " + sourceFile.name + ", " + - "is already at max level!"); - } else { - ++ownedSourceFile.lvl; - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])(sourceFile.name + " was upgraded to level " + ownedSourceFile.lvl + " for " + - "destroying its corresponding BitNode!"); - } - } else { - var playerSrcFile = new __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__["a" /* PlayerOwnedSourceFile */](bitNodeNumber, 1); - __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles.push(playerSrcFile); - if (bitNodeNumber === 5) { //Artificial Intelligence - __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence = 1; - } - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You received a Source-File for destroying a Bit Node!

" + - sourceFile.name + "

" + sourceFile.info); - } -} - -function loadBitVerse(destroyedBitNodeNum) { - //Clear the screen - var container = document.getElementById("red-pill-container"); - while (container.firstChild) { - container.removeChild(container.firstChild); - } - - //Create the Bit Verse - var bitVerseImage = document.createElement("pre"); - var bitNodes = []; - for (var i = 1; i <= 12; ++i) { - bitNodes.push(createBitNode(i)); - } - - bitVerseImage.innerHTML = - " O
" + - " | O O | O O |
" + - " O | | / __| \\ | | O
" + - " O | O | | O / | O | | O | O
" + - " | | | | |_/ |/ | \\_ \\_| | | | |
" + - " O | | | O | | O__/ | / \\__ | | O | | | O
" + - " | | | | | | | / /| O / \\| | | | | | |
" + - "O | | | \\| | O / _/ | / O | |/ | | | O
" + - "| | | |O / | | O / | O O | | \\ O| | | |
" + - "| | |/ \\/ / __| | |/ \\ | \\ | |__ \\ \\/ \\| | |
" + - " \\| O | |_/ |\\| \\ O \\__| \\_| | O |/
" + - " | | |_/ | | \\| / | \\_| | |
" + - " \\| / \\| | / / \\ |/
" + - " | "+bitNodes[9]+" | | / | "+bitNodes[10]+" |
" + - " "+bitNodes[8]+" | | | | | | | "+bitNodes[11]+"
" + - " | | | / / \\ \\ | | |
" + - " \\| | / "+bitNodes[6]+" / \\ "+bitNodes[7]+" \\ | |/
" + - " \\ | / / | | \\ \\ | /
" + - " \\ \\JUMP "+bitNodes[4]+"3R | | | | | | R3"+bitNodes[5]+" PMUJ/ /
" + - " \\|| | | | | | | | | ||/
" + - " \\| \\_ | | | | | | _/ |/
" + - " \\ \\| / \\ / \\ |/ /
" + - " "+bitNodes[0]+" |/ "+bitNodes[1]+" | | "+bitNodes[2]+" \\| "+bitNodes[3]+"
" + - " | | | | | | | |
" + - " \\JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/



"; - - - /* - " O
" + - " | O O | O O |
" + - " O | | / __| \ | | O
" + - " O | O | | O / | O | | O | O
" + - " | | | | |_/ |/ | \_ \_| | | | |
" + - " O | | | O | | O__/ | / \__ | | O | | | O
" + - " | | | | | | | / /| O / \| | | | | | |
" + - "O | | | \| | O / _/ | / O | |/ | | | O
" + - "| | | |O / | | O / | O O | | \ O| | | |
" + - "| | |/ \/ / __| | |/ \ | \ | |__ \ \/ \| | |
" + - " \| O | |_/ |\| \ O \__| \_| | O |/
" + - " | | |_/ | | \| / | \_| | |
" + - " \| / \| | / / \ |/
" + - " | O | | / | O |
" + - " O | | | | | | | O
" + - " | | | / / \ \ | | |
" + - " \| | / O / \ O \ | |/
" + - " \ | / / | | \ \ | /
" + - " \ \JUMP O3R | | | | | | R3O PMUJ/ /
" + - " \|| | | | | | | | | ||/
" + - " \| \_ | | | | | | _/ |/
" + - " \ \| / \ / \ |/ /
" + - " O |/ O | | O \| O
" + - " | | | | | | | |
" + - " \JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/
"; - */ - - container.appendChild(bitVerseImage); - - //Bit node event listeners - for (var i = 1; i <= 12; ++i) { - (function(i) { - var elemId = "bitnode-" + i.toString(); - var elem = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])(elemId); - if (elem == null) {return;} - if (i === 1 || i === 2 || i === 4 || i === 5 || i === 8 || i === 11) { - elem.addEventListener("click", function() { - var bitNodeKey = "BitNode" + i; - var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeKey]; - if (bitNode == null) { - console.log("ERROR: Could not find BitNode object for number: " + i); - return; - } - Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("BitNode-" + i + ": " + bitNode.name + "

" + bitNode.info); - createBitNodeYesNoEventListeners(i, destroyedBitNodeNum); - }); - } else { - elem.addEventListener("click", function() { - Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Not yet implemented! Coming soon!") - }); - } - }(i)); //Immediate invocation closure - } - - //Create lore text - return writeRedPillLine("Many decades ago, a humanoid extraterrestial species which we call the Enders descended on the Earth...violently").then(function() { - return writeRedPillLine("Our species fought back, but it was futile. The Enders had technology far beyond our own..."); - }).then(function() { - return writeRedPillLine("Instead of killing every last one of us, the human race was enslaved..."); - }).then(function() { - return writeRedPillLine("We were shackled in a digital world, chained into a prison for our minds..."); - }).then(function() { - return writeRedPillLine("Using their advanced technology, the Enders created complex simulations of a virtual reality..."); - }).then(function() { - return writeRedPillLine("Simulations designed to keep us content...ignorant of the truth."); - }).then(function() { - return writeRedPillLine("Simulations used to trap and suppress our consciousness, to keep us under control..."); - }).then(function() { - return writeRedPillLine("Why did they do this? Why didn't they just end our entire race? We don't know, not yet."); - }).then(function() { - return writeRedPillLine("Humanity's only hope is to destroy these simulations, destroy the only realities we've ever known..."); - }).then(function() { - return writeRedPillLine("Only then can we begin to fight back..."); - }).then(function() { - return writeRedPillLine("By hacking the daemon that generated your reality, you've just destroyed one simulation, called a BitNode..."); - }).then(function() { - return writeRedPillLine("But there is still a long way to go..."); - }).then(function() { - return writeRedPillLine("The technology the Enders used to enslave the human race wasn't just a single complex simulation..."); - }).then(function() { - return writeRedPillLine("There are tens if not hundreds of BitNodes out there..."); - }).then(function() { - return writeRedPillLine("Each with their own simulations of a reality..."); - }).then(function() { - return writeRedPillLine("Each creating their own universes...a universe of universes"); - }).then(function() { - return writeRedPillLine("And all of which must be destroyed..."); - }).then(function() { - return writeRedPillLine("......................................."); - }).then(function() { - return writeRedPillLine("Welcome to the Bitverse..."); - }).then(function() { - return writeRedPillLine(" "); - }).then(function() { - return writeRedPillLine("(Enter a new BitNode using the image above)"); - }).then(function() { - return Promise.resolve(true); - }).catch(function(e){ - console.log("ERROR: " + e.toString()); - }); -} - - -//Returns string with DOM element for Bit Node -function createBitNode(n) { - var bitNodeStr = "BitNode" + n.toString(); - var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeStr]; - if (bitNode == null) {return "O";} - return "O" + - "" + - "BitNode-" + bitNode.number.toString() + "
" + bitNode.name+ "

" + - bitNode.desc + "
" + - "
"; -} - -function createBitNodeYesNoEventListeners(newBitNode, destroyedBitNode) { - var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(); - yesBtn.innerHTML = "Enter BitNode-" + newBitNode; - yesBtn.addEventListener("click", function() { - giveSourceFile(destroyedBitNode); - redPillFlag = false; - var container = document.getElementById("red-pill-container"); - while (container.firstChild) { - container.removeChild(container.firstChild); - } - - //Set new Bit Node - __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN = newBitNode; - console.log("Entering Bit Node " + __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN); - - //Reenable terminal - $("#hack-progress-bar").attr('id', "old-hack-progress-bar"); - $("#hack-progress").attr('id', "old-hack-progress"); - document.getElementById("terminal-input-td").innerHTML = '$ '; - $('input[class=terminal-input]').prop('disabled', false); - - __WEBPACK_IMPORTED_MODULE_5__Terminal_js__["a" /* Terminal */].hackFlag = false; - - Object(__WEBPACK_IMPORTED_MODULE_3__Prestige_js__["b" /* prestigeSourceFile */])(); - Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); - }); - var noBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])(); - noBtn.innerHTML = "Back"; - noBtn.addEventListener("click", function() { - Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])(); - }); - -} - - - -/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(9))) - -/***/ }), -/* 38 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return makeRuntimeRejectMsg; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return netscriptDelay; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptFromScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return scriptCalculateHackingChance; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return scriptCalculateHackingTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return scriptCalculateExpGain; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return scriptCalculatePercentMoneyHacked; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return scriptCalculateGrowTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return scriptCalculateWeakenTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return evaluate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isScriptErrorMessage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return killNetscriptDelay; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__ = __webpack_require__(31); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(14); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Script_js__ = __webpack_require__(16); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_acorn_js__ = __webpack_require__(47); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_acorn_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8__utils_acorn_js__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_IPAddress_js__ = __webpack_require__(17); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__ = __webpack_require__(4); - - - - - - - - - - - - - - -var Promise = __webpack_require__(72); - -Promise.config({ - warnings: false, - longStackTraces: false, - cancellation: true, - monitoring: false -}); -/* Evaluator - * Evaluates/Interprets the Abstract Syntax Tree generated by Acorns parser - * - * Returns a promise - */ -function evaluate(exp, workerScript) { - /* return new Promise(function(resolve, reject) {*/ - return Promise.delay(__WEBPACK_IMPORTED_MODULE_6__Settings_js__["a" /* Settings */].CodeInstructionRunTime).then(function() { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - if (exp == null) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression")); - } - if (env.stopFlag) {return Promise.reject(workerScript);} - switch (exp.type) { - case "BlockStatement": - case "Program": - var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment - return evaluateProgPromise.then(function(w) { - return Promise.resolve(workerScript); - }).catch(function(e) { - if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { - return Promise.reject(e); - } else if (Object(__WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__["f" /* isString */])(e)) { - workerScript.errorMessage = e; - return Promise.reject(workerScript); - } else if (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]) { - return Promise.reject(e); - } else { - return Promise.reject(workerScript); - } - }); - break; - case "Literal": - return Promise.resolve(exp.value); - break; - case "Identifier": - if (!(exp.name in env.vars)){ - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined")); - } - return Promise.resolve(env.get(exp.name)) - break; - case "ExpressionStatement": - return evaluate(exp.expression, workerScript); - break; - case "ArrayExpression": - var argPromises = exp.elements.map(function(arg) { - return evaluate(arg, workerScript); - }); - return Promise.all(argPromises).then(function(array) { - return Promise.resolve(array) - }); - break; - case "CallExpression": - return evaluate(exp.callee, workerScript).then(function(func) { - return Promise.map(exp.arguments, function(arg) { - return evaluate(arg, workerScript); - }).then(function(args) { - if (func instanceof __WEBPACK_IMPORTED_MODULE_8__utils_acorn_js__["Node"]) { //Player-defined function - //Create new Environment for the function - //Should be automatically garbage collected... - var funcEnv = env.extend(); - - //Define function arguments in this new environment - for (var i = 0; i < func.params.length; ++i) { - var arg; - if (i >= args.length) { - arg = null; - } else { - arg = args[i]; - } - funcEnv.def(func.params[i].name, arg); - } - - //Create a new WorkerScript for this function evaluation - var funcWorkerScript = new __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */](workerScript.scriptRef); - funcWorkerScript.serverIp = workerScript.serverIp; - funcWorkerScript.env = funcEnv; - workerScript.fnWorker = funcWorkerScript; - - return evaluate(func.body, funcWorkerScript).then(function(res) { - //If the function finished successfuly, that means there - //was no return statement since a return statement rejects. So resolve to null - workerScript.fnWorker = null; - return Promise.resolve(null); - }).catch(function(e) { - if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { - //Return statement from function - return Promise.resolve(e[1]); - workerScript.fnWorker = null; - } else if (Object(__WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__["f" /* isString */])(e)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } else if (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]) { - //Parse out the err message from the WorkerScript and re-reject - var errorMsg = e.errorMessage; - var errorTextArray = errorMsg.split("|"); - if (errorTextArray.length === 4) { - errorMsg = errorTextArray[3]; - return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg)); - } else { - if (env.stopFlag) { - return Promise.reject(workerScript); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function")); - } - } - } else if (e instanceof Error) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString())); - } - }); - } else if (exp.callee.type == "MemberExpression"){ - return evaluate(exp.callee.object, workerScript).then(function(object) { - try { - var res = func.apply(object,args); - return Promise.resolve(res); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } - }); - } else { - try { - var out = func.apply(null,args); - if (out instanceof Promise){ - return out.then(function(res) { - return Promise.resolve(res) - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - return Promise.resolve(out); - } - } catch (e) { - if (isScriptErrorMessage(e)) { - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } - } - } - }); - }); - break; - case "MemberExpression": - return evaluate(exp.object, workerScript).then(function(object) { - if (exp.computed){ - return evaluate(exp.property, workerScript).then(function(index) { - if (index >= object.length) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays")); - } - return Promise.resolve(object[index]); - }).catch(function(e) { - if (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] || isScriptErrorMessage(e)) { - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression")); - } - - }); - } else { - try { - return Promise.resolve(object[exp.property.name]) - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString())); - } - } - }); - break; - case "LogicalExpression": - case "BinaryExpression": - return evalBinary(exp, workerScript); - break; - case "UnaryExpression": - return evalUnary(exp, workerScript); - break; - case "AssignmentExpression": - return evalAssignment(exp, workerScript); - break; - case "UpdateExpression": - if (exp.argument.type==="Identifier"){ - if (exp.argument.name in env.vars){ - if (exp.operator === "++" || exp.operator === "--") { - switch (exp.operator) { - case "++": - env.set(exp.argument.name,env.get(exp.argument.name)+1); - break; - case "--": - env.set(exp.argument.name,env.get(exp.argument.name)-1); - break; - default: break; - } - return Promise.resolve(env.get(exp.argument.name)); - } - //Not sure what prefix UpdateExpressions there would be besides ++/-- - if (exp.prefix){ - return Promise.resolve(env.get(exp.argument.name)) - } - switch (exp.operator){ - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported")); - } - return Promise.resolve(env.get(exp.argument.name)) - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined")); - } - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier")); - } - break; - case "EmptyStatement": - return Promise.resolve(false); - break; - case "ReturnStatement": - return evaluate(exp.argument, workerScript).then(function(res) { - return Promise.reject(["RETURNSTATEMENT", res]); - }); - break; - case "BreakStatement": - return Promise.reject("BREAKSTATEMENT"); - break; - case "ContinueStatement": - return Promise.reject("CONTINUESTATEMENT"); - break; - case "IfStatement": - return evaluateIf(exp, workerScript); - break; - case "SwitchStatement": - var lineNum = getErrorLineNumber(exp, workerScript); - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript (line " + (lineNum+1) + ")")); - break; - case "WhileStatement": - return evaluateWhile(exp, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("whileLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "ForStatement": - return evaluate(exp.init, workerScript).then(function(expInit) { - return evaluateFor(exp, workerScript); - }).then(function(forLoopRes) { - return Promise.resolve("forLoopDone"); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("forLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "FunctionDeclaration": - if (exp.id && exp.id.name) { - env.set(exp.id.name, exp); - return Promise.resolve(true); - } else { - var lineNum = getErrorLineNumber(exp, workerScript); - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration at line " + lineNum+1)); - } - break; - default: - var lineNum = getErrorLineNumber(exp, workerScript); - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + " (line " + (lineNum+1) + "). This is currently unsupported in Netscript")); - break; - } //End switch - }).catch(function(e) { - return Promise.reject(e); - }); // End Promise -} - -function evalBinary(exp, workerScript){ - return evaluate(exp.left, workerScript).then(function(expLeft) { - //Short circuiting - if (expLeft == true && exp.operator === "||") { - return Promise.resolve(true); - } - if (expLeft == false && exp.operator === "&&") { - return Promise.resolve(false); - } - return evaluate(exp.right, workerScript).then(function(expRight) { - switch (exp.operator){ - case "===": - case "==": - return Promise.resolve(expLeft===expRight); - break; - case "!==": - case "!=": - return Promise.resolve(expLeft!==expRight); - break; - case "<": - return Promise.resolve(expLeft": - return Promise.resolve(expLeft>expRight); - break; - case ">=": - return Promise.resolve(expLeft>=expRight); - break; - case "+": - return Promise.resolve(expLeft+expRight); - break; - case "-": - return Promise.resolve(expLeft-expRight); - break; - case "*": - return Promise.resolve(expLeft*expRight); - break; - case "/": - if (expRight === 0) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero")); - } else { - return Promise.resolve(expLeft/expRight); - } - break; - case "%": - return Promise.resolve(expLeft%expRight); - break; - case "in": - return Promise.resolve(expLeft in expRight); - break; - case "instanceof": - return Promise.resolve(expLeft instanceof expRight); - break; - case "||": - return Promise.resolve(expLeft || expRight); - break; - case "&&": - return Promise.resolve(expLeft && expRight); - break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unsupported operator: " + exp.operator)); - } - }); - }); -} - -function evalUnary(exp, workerScript){ - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return evaluate(exp.argument, workerScript).then(function(res) { - if (exp.operator == "!") { - return Promise.resolve(!res); - } else if (exp.operator == "-") { - if (isNaN(res)) { - return Promise.resolve(res); - } else { - return Promise.resolve(-1 * res); - } - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator)); - } - }); -} - -//Takes in a MemberExpression that should represent a Netscript array (possible multidimensional) -//The return value is an array of the form: -// [0th index (leftmost), array name, 1st index, 2nd index, ...] -function getArrayElement(exp, workerScript) { - var indices = []; - return evaluate(exp.property, workerScript).then(function(idx) { - if (isNaN(idx)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx)); - } else { - if (exp.object.name === undefined && exp.object.object) { - return getArrayElement(exp.object, workerScript).then(function(res) { - res.push(idx); - indices = res; - return Promise.resolve(indices); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - indices.push(idx); - indices.push(exp.object.name); - return Promise.resolve(indices); - } - } - }); -} - -function evalAssignment(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - - if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left))); - } - - if (exp.operator !== "=" && !(exp.left.name in env.vars)){ - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined")); - } - - return evaluate(exp.right, workerScript).then(function(expRight) { - if (exp.left.type == "MemberExpression") { - //Assign to array element - //Array object designed by exp.left.object.name - //Index designated by exp.left.property - return getArrayElement(exp.left, workerScript).then(function(res) { - if (!(res instanceof Array) || res.length < 2) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error evaluating array assignment. This is (probably) a bug please report to game dev")); - } - - //The array name is the second value - var arrName = res.splice(1, 1); - arrName = arrName[0]; - - env.setArrayElement(arrName, res, expRight); - return Promise.resolve(false); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - //Other assignments - try { - switch (exp.operator) { - case "=": - env.set(exp.left.name,expRight); - break; - case "+=": - env.set(exp.left.name,env.get(exp.left.name) + expRight); - break; - case "-=": - env.set(exp.left.name,env.get(exp.left.name) - expRight); - break; - case "*=": - env.set(exp.left.name,env.get(exp.left.name) * expRight); - break; - case "/=": - env.set(exp.left.name,env.get(exp.left.name) / expRight); - break; - case "%=": - env.set(exp.left.name,env.get(exp.left.name) % expRight); - break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented")); - } - return Promise.resolve(false); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString())); - } - } - }); -} - -function evaluateIf(exp, workerScript, i) { - var env = workerScript.env; - return evaluate(exp.test, workerScript).then(function(condRes) { - if (condRes) { - return evaluate(exp.consequent, workerScript).then(function(res) { - return Promise.resolve(true); - }, function(e) { - return Promise.reject(e); - }); - } else if (exp.alternate) { - return evaluate(exp.alternate, workerScript).then(function(res) { - return Promise.resolve(true); - }, function(e) { - return Promise.reject(e); - }); - } else { - return Promise.resolve("endIf"); - } - }); -} - -//Evaluate the looping part of a for loop (Initialization block is NOT done in here) -function evaluateFor(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return new Promise(function(resolve, reject) { - function recurse() { - //Don't return a promise so the promise chain is broken on each recursion (saving memory) - evaluate(exp.test, workerScript).then(function(resCond) { - if (resCond) { - return evaluate(exp.body, workerScript).then(function(res) { - return evaluate(exp.update, workerScript); - }).catch(function(e) { - if (e == "CONTINUESTATEMENT" || - (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "CONTINUESTATEMENT")) { - //Continue statement, recurse to next iteration - return evaluate(exp.update, workerScript).then(function(resPostloop) { - return evaluateFor(exp, workerScript); - }).then(function(foo) { - return Promise.resolve("endForLoop"); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - return Promise.reject(e); - } - }).then(recurse, reject).catch(function(e) { - return Promise.reject(e); - }); - } else { - resolve(); - } - }).catch(function(e) { - reject(e); - }); - } - recurse(); - }); - /* - return evaluate(exp.test, workerScript).then(function(resCond) { - if (resCond) { - //Execute code (body), update, and then recurse - return evaluate(exp.body, workerScript).then(function(resCode) { - return evaluate(exp.update, workerScript); - }).catch(function(e) { - if (e == "CONTINUESTATEMENT" || - (e instanceof WorkerScript && e.errorMessage == "CONTINUESTATEMENT")) { - //Continue statement, recurse to next iteration - return evaluate(exp.update, workerScript).then(function(resPostloop) { - return evaluateFor(exp, workerScript); - }).then(function(foo) { - return Promise.resolve("endForLoop"); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - return Promise.reject(e); - } - }).then(function(resPostloop) { - return evaluateFor(exp, workerScript); - }).then(function(foo) { - return Promise.resolve("endForLoop"); - }); - } else { - return Promise.resolve("endForLoop"); //Doesn't need to resolve to any particular value - } - });*/ -} - -function evaluateWhile(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return new Promise(function (resolve, reject) { - function recurse() { - //Don't return a promise so the promise chain is broken on each recursion (saving memory) - evaluate(exp.test, workerScript).then(function(resCond) { - if (resCond) { - return evaluate(exp.body, workerScript).catch(function(e) { - if (e == "CONTINUESTATEMENT" || - (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "CONTINUESTATEMENT")) { - //Continue statement, recurse - return evaluateWhile(exp, workerScript).then(function(foo) { - return Promise.resolve("endWhileLoop"); - }, function(e) { - return Promise.reject(e); - }); - } else { - return Promise.reject(e); - } - }).then(recurse, reject).catch(function(e) { - return Promise.reject(e); - }); - } else { - resolve(); - } - }).catch(function(e) { - reject(e); - }); - } - recurse(); - }); -} - -function evaluateProg(exp, workerScript, index) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - if (index >= exp.body.length) { - return Promise.resolve("progFinished"); - } else { - //Evaluate this line of code in the prog - //After the code finishes evaluating, evaluate the next line recursively - return evaluate(exp.body[index], workerScript).then(function(res) { - return evaluateProg(exp, workerScript, index + 1); - }).then(function(res) { - return Promise.resolve(workerScript); - }).catch(function(e) { - return Promise.reject(e); - }); - } -} - -function killNetscriptDelay(workerScript) { - /* - if (workerScript instanceof WorkerScript) { - if (workerScript.delay) { - workerScript.delay.cancel(); - } - } - */ - if (workerScript instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]) { - if (workerScript.delay) { - clearTimeout(workerScript.delay); - workerScript.delayResolve(); - } - } -} - -function netscriptDelay(time, workerScript) { - /* - workerScript.delay = new Promise(function(resolve, reject, onCancel) { - Promise.delay(time).then(function() { - resolve(); - workerScript.delay = null; - }); - onCancel(function() { - console.log("Cancelling and rejecting this Promise"); - reject(workerScript); - }) - }); - return workerScript.delay; - */ - return new Promise(function(resolve, reject) { - workerScript.delay = setTimeout(()=>{ - workerScript.delay = null; - resolve(); - }, time); - workerScript.delayResolve = resolve; - }); -} - -function makeRuntimeRejectMsg(workerScript, msg) { - return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg; -} - -/* -function apply_op(op, a, b) { - function num(x) { - if (typeof x != "number") - throw new Error("Expected number but got " + x); - return x; - } - function div(x) { - if (num(x) == 0) - throw new Error("Divide by zero"); - return x; - } - switch (op) { - case "+": return a + b; - case "-": return num(a) - num(b); - case "*": return num(a) * num(b); - case "/": return num(a) / div(b); - case "%": return num(a) % div(b); - case "&&": return a !== false && b; - case "||": return a !== false ? a : b; - case "<": return num(a) < num(b); - case ">": return num(a) > num(b); - case "<=": return num(a) <= num(b); - case ">=": return num(a) >= num(b); - case "==": return a === b; - case "!=": return a !== b; - } - throw new Error("Can't apply operator " + op); -} -*/ - -//Run a script from inside a script using run() command -function runScriptFromScript(server, scriptname, args, workerScript, threads=1) { - //Check if the script is already running - var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_7__Script_js__["d" /* findRunningScript */])(scriptname, args, server); - if (runningScriptObj != null) { - workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname); - return Promise.resolve(false); - } - - //Check if the script exists and if it does run it - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename == scriptname) { - //Check for admin rights and that there is enough RAM availble to run - var script = server.scripts[i]; - var ramUsage = script.ramUsage; - threads = Math.round(Number(threads)); //Convert to number and round - ramUsage = ramUsage * threads * Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultithreadingRAMCost, threads-1); - var ramAvailable = server.maxRam - server.ramUsed; - - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot run script " + scriptname + " on " + server.hostname + " because you do not have root access!"); - return Promise.resolve(false); - } else if (ramUsage > ramAvailable){ - workerScript.scriptRef.log("Cannot run script " + scriptname + "(t=" + threads + ") on " + server.hostname + " because there is not enough available RAM!"); - return Promise.resolve(false); - } else { - //Able to run script - workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["f" /* printArray */])(args) + ". May take a few seconds to start up..."); - var runningScriptObj = new __WEBPACK_IMPORTED_MODULE_7__Script_js__["b" /* RunningScript */](script, args); - runningScriptObj.threads = threads; - server.runningScripts.push(runningScriptObj); //Push onto runningScripts - Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["c" /* addWorkerScript */])(runningScriptObj, server); - return Promise.resolve(true); - } - } - } - workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname); - return Promise.resolve(false); -} - -//Takes in a -function getErrorLineNumber(exp, workerScript) { - var code = workerScript.scriptRef.scriptRef.code; - - //Split code up to the start of the node - code = code.substring(0, exp.start); - return (code.match(/\n/g) || []).length; -} - -function isScriptErrorMessage(msg) { - if (!Object(__WEBPACK_IMPORTED_MODULE_11__utils_StringHelperFunctions_js__["f" /* isString */])(msg)) {return false;} - let splitMsg = msg.split("|"); - if (splitMsg.length != 4){ - return false; - } - var ip = splitMsg[1]; - if (!Object(__WEBPACK_IMPORTED_MODULE_10__utils_IPAddress_js__["c" /* isValidIPAddress */])(ip)) { - return false; - } - return true; -} - -//The same as Player's calculateHackingChance() function but takes in the server as an argument -function scriptCalculateHackingChance(server) { - var difficultyMult = (100 - server.hackDifficulty) / 100; - var skillMult = (1.75 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill) + (0.2 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence); - var skillChance = (skillMult - server.requiredHackingSkill) / skillMult; - var chance = skillChance * difficultyMult * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult; - if (chance > 1) {return 1;} - if (chance < 0) {return 0;} - else {return chance;} -} - -//The same as Player's calculateHackingTime() function but takes in the server as an argument -function scriptCalculateHackingTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50 + (0.1 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence)); - var hackingTime = 5 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds - return hackingTime; -} - -//The same as Player's calculateExpGain() function but takes in the server as an argument -function scriptCalculateExpGain(server) { - if (server.baseDifficulty == null) { - server.baseDifficulty = server.hackDifficulty; - } - return (server.baseDifficulty * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult * 0.3 + 3) * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].HackExpGain; -} - -//The same as Player's calculatePercentMoneyHacked() function but takes in the server as an argument -function scriptCalculatePercentMoneyHacked(server) { - var difficultyMult = (100 - server.hackDifficulty) / 100; - var skillMult = (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill - (server.requiredHackingSkill - 1)) / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill; - var percentMoneyHacked = difficultyMult * skillMult * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult / 240; - if (percentMoneyHacked < 0) {return 0;} - if (percentMoneyHacked > 1) {return 1;} - return percentMoneyHacked * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].ScriptHackMoney; -} - -//Amount of time to execute grow() in milliseconds -function scriptCalculateGrowTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50 + (0.1 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence)); - var growTime = 16 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds - return growTime * 1000; -} - -//Amount of time to execute weaken() in milliseconds -function scriptCalculateWeakenTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50 + (0.1 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].intelligence)); - var weakenTime = 20 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds - return weakenTime * 1000; -} - - - - -/***/ }), -/* 39 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* unused harmony export hacknetNodesInit */ -/* unused harmony export HacknetNode */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return purchaseHacknet; }); -/* unused harmony export updateTotalHacknetProduction */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getCostOfNextHacknetNode; }); -/* unused harmony export updateHacknetNodesMultiplierButtons */ -/* unused harmony export getMaxNumberLevelUpgrades */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return displayHacknetNodesContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return updateHacknetNodesContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return processAllHacknetNodeEarnings; }); -/* unused harmony export getHacknetNode */ -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__ = __webpack_require__(27); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__ = __webpack_require__(8); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__ = __webpack_require__(4); - - - - - - - - - - -/* HacknetNode.js */ -function hacknetNodesInit() { - var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); - mult1x.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 1; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); - var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); - mult5x.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 5; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); - var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); - mult10x.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 10; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); - var multMax = document.getElementById("hacknet-nodes-max-multiplier"); - multMax.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 0; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); -} -document.addEventListener("DOMContentLoaded", hacknetNodesInit, false); - -function HacknetNode(name) { - this.level = 1; - this.ram = 1; //GB - this.cores = 1; - - this.name = name; - - this.totalMoneyGenerated = 0; - this.onlineTimeSeconds = 0; - - this.moneyGainRatePerSecond = 0; -} - -HacknetNode.prototype.updateMoneyGainRate = function() { - //How much extra $/s is gained per level - var gainPerLevel = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMoneyGainPerLevel; - - this.moneyGainRatePerSecond = (this.level * gainPerLevel) * - Math.pow(1.035, this.ram-1) * - ((this.cores + 5) / 6) * - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_money_mult * - __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].HacknetNodeMoney; - if (isNaN(this.moneyGainRatePerSecond)) { - this.moneyGainRatePerSecond = 0; - Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Error in calculating Hacknet Node production. Please report to game developer"); - } - - updateTotalHacknetProduction(); -} - -HacknetNode.prototype.calculateLevelUpgradeCost = function(levels=1) { - if (levels < 1) {return 0;} - var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeLevelMult; - var totalMultiplier = 0; //Summed - var currLevel = this.level; - for (var i = 0; i < levels; ++i) { - totalMultiplier += Math.pow(mult, currLevel); - ++currLevel; - } - return __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNode / 2 * totalMultiplier * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_level_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getLevelUpgradeCost = function(levels=1) { - return this.calculateLevelUpgradeCost(levels); -} - -HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) { - var cost = this.calculateLevelUpgradeCost(levels); - if (isNaN(cost) || levels < 0) {return false;} - if (this.level + levels > __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel) { - var diff = Math.max(0, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - this.level); - return this.purchaseLevelUpgrade(diff); - } - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;} - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); - this.level += levels; - this.updateMoneyGainRate(); - return true; -} - -//Wrapper function for Netscript -HacknetNode.prototype.upgradeLevel = function(levels=1) { - return this.purchaseLevelUpgrade(levels); -} - -HacknetNode.prototype.calculateRamUpgradeCost = function() { - var numUpgrades = Math.log2(this.ram); - - //Calculate cost - //Base cost of RAM is 50k per 1GB, increased by some multiplier for each time RAM is upgraded - var baseCost = this.ram * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHacknetNode; - var mult = Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeRamMult, numUpgrades); - return baseCost * mult * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getRamUpgradeCost = function() { - return this.calculateRamUpgradeCost(); -} - -HacknetNode.prototype.purchaseRamUpgrade = function() { - var cost = this.calculateRamUpgradeCost(); - if (isNaN(cost)) {return false;} - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;} - if (this.ram >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxRam) {return false;} - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); - this.ram *= 2; //Ram is always doubled - this.updateMoneyGainRate(); - return true; -} - -//Wrapper function for Netscript -HacknetNode.prototype.upgradeRam = function() { - return this.purchaseRamUpgrade(); -} - -HacknetNode.prototype.calculateCoreUpgradeCost = function() { - var coreBaseCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNodeCore; - var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeCoreMult; - return coreBaseCost * Math.pow(mult, this.cores-1) * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_core_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getCoreUpgradeCost = function() { - return this.calculateCoreUpgradeCost(); -} - -HacknetNode.prototype.purchaseCoreUpgrade = function() { - var cost = this.calculateCoreUpgradeCost(); - if (isNaN(cost)) {return false;} - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;} - if (this.cores >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxCores) {return false;} - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); - ++this.cores; - this.updateMoneyGainRate(); - return true; -} - -//Wrapper function for Netscript -HacknetNode.prototype.upgradeCore = function() { - return this.purchaseCoreUpgrade(); -} - -/* Saving and loading HackNets */ -HacknetNode.prototype.toJSON = function() { - return Object(__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["b" /* Generic_toJSON */])("HacknetNode", this); -} - -HacknetNode.fromJSON = function(value) { - return Object(__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(HacknetNode, value.data); -} - -__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["c" /* Reviver */].constructors.HacknetNode = HacknetNode; - - -function purchaseHacknet() { - /* INTERACTIVE TUTORIAL */ - if (__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["b" /* iTutorialIsRunning */]) { - if (__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["a" /* currITutorialStep */] == __WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["e" /* iTutorialSteps */].HacknetNodesIntroduction) { - Object(__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["c" /* iTutorialNextStep */])(); - } else { - return; - } - } - - /* END INTERACTIVE TUTORIAL */ - - var cost = getCostOfNextHacknetNode(); - if (isNaN(cost)) {throw new Error("Cost is NaN"); return;} - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) { - //dialogBoxCreate("You cannot afford to purchase a Hacknet Node!"); - return false; - } - - //Auto generate a name for the node for now...TODO - var numOwned = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; - var name = "hacknet-node-" + numOwned; - var node = new HacknetNode(name); - node.updateMoneyGainRate(); - - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost); - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.push(node); - - displayHacknetNodesContent(); - updateTotalHacknetProduction(); - return numOwned; -} - -//Calculates the total production from all HacknetNodes -function updateTotalHacknetProduction() { - var total = 0; - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { - total += __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i].moneyGainRatePerSecond; - } - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].totalHacknetNodeProduction = total; -} - -function getCostOfNextHacknetNode() { - //Cost increases exponentially based on how many you own - var numOwned = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; - var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodePurchaseNextMult; - return __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNode * Math.pow(mult, numOwned) * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult; -} - -var hacknetNodePurchaseMultiplier = 1; -function updateHacknetNodesMultiplierButtons() { - var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); - var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); - var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); - var multMax = document.getElementById("hacknet-nodes-max-multiplier"); - mult1x.setAttribute("class", "a-link-button"); - mult5x.setAttribute("class", "a-link-button"); - mult10x.setAttribute("class", "a-link-button"); - multMax.setAttribute("class", "a-link-button"); - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length == 0) { - mult1x.setAttribute("class", "a-link-button-inactive"); - mult5x.setAttribute("class", "a-link-button-inactive"); - mult10x.setAttribute("class", "a-link-button-inactive"); - multMax.setAttribute("class", "a-link-button-inactive"); - } else if (hacknetNodePurchaseMultiplier == 1) { - mult1x.setAttribute("class", "a-link-button-inactive"); - } else if (hacknetNodePurchaseMultiplier == 5) { - mult5x.setAttribute("class", "a-link-button-inactive"); - } else if (hacknetNodePurchaseMultiplier == 10) { - mult10x.setAttribute("class", "a-link-button-inactive"); - } else { - multMax.setAttribute("class", "a-link-button-inactive"); - } -} - -//Calculate the maximum number of times the Player can afford to upgrade -//a Hacknet Node's level" -function getMaxNumberLevelUpgrades(nodeObj) { - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(1))) {return 0;} - var min = 1; - var max = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel-1; - var levelsToMax = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - nodeObj.level; - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax))) { - return levelsToMax; - } - - while (min <= max) { - var curr = (min + max) / 2 | 0; - if (curr != __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel && - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(curr)) && - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(curr+1))) { - return Math.min(levelsToMax, curr); - } else if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(curr))) { - max = curr - 1; - } else if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(curr))) { - min = curr + 1; - } else { - return Math.min(levelsToMax, curr); - } - } -} - -//Creates Hacknet Node DOM elements when the page is opened -function displayHacknetNodesContent() { - //Update Hacknet Nodes button - var newPurchaseButton = Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-purchase-button"); - - newPurchaseButton.addEventListener("click", function() { - purchaseHacknet(); - return false; - }); - - //Handle Purchase multiplier buttons - updateHacknetNodesMultiplierButtons(); - - //Remove all old hacknet Node DOM elements - var hacknetNodesList = document.getElementById("hacknet-nodes-list"); - while (hacknetNodesList.firstChild) { - hacknetNodesList.removeChild(hacknetNodesList.firstChild); - } - - //Then re-create them - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { - createHacknetNodeDomElement(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]); - } - updateHacknetNodesContent(); -} - -//Update information on all Hacknet Node DOM elements -function updateHacknetNodesContent() { - //Set purchase button to inactive if not enough money, and update its price display - var cost = getCostOfNextHacknetNode(); - var purchaseButton = document.getElementById("hacknet-nodes-purchase-button"); - purchaseButton.innerHTML = "Purchase Hacknet Node - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2); - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) { - purchaseButton.setAttribute("class", "a-link-button-inactive"); - } else { - purchaseButton.setAttribute("class", "a-link-button"); - } - - //Update player's money - var moneyElem = document.getElementById("hacknet-nodes-money"); - moneyElem.innerHTML = "Money: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.toNumber(), 2) + "
" + - "Total production from all Hacknet Nodes: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].totalHacknetNodeProduction, 2) + " / second"; - - //Update information in each owned hacknet node - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { - updateHacknetNodeDomElement(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]); - } -} - -//Creates a single Hacknet Node DOM element -function createHacknetNodeDomElement(nodeObj) { - var nodeName = nodeObj.name; - - var listItem = document.createElement("li"); - listItem.setAttribute("class", "hacknet-node"); - - var span = document.createElement("span"); - span.style.display = "inline"; - - var buttonDiv = document.createElement("div"); - buttonDiv.setAttribute("class", "hacknet-node-button-div"); - - //Text - var txt = document.createElement("p"); - //txt.setAttribute("id", "hacknet-node-text-" + nodeName); - txt.id = "hacknet-node-text-" + nodeName; - - //Upgrade buttons - var upgradeLevelButton = document.createElement("a"); - var upgradeRamButton = document.createElement("a"); - var upgradeCoreButton = document.createElement("a"); - - //upgradeLevelButton.setAttribute("id", "hacknet-node-upgrade-level-" + nodeName); - upgradeLevelButton.id = "hacknet-node-upgrade-level-" + nodeName; - upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); - upgradeLevelButton.addEventListener("click", function() { - var numUpgrades = hacknetNodePurchaseMultiplier; - if (hacknetNodePurchaseMultiplier == 0) { - numUpgrades = getMaxNumberLevelUpgrades(nodeObj); - } - nodeObj.purchaseLevelUpgrade(numUpgrades); - updateHacknetNodesContent(); - return false; - }); - //upgradeRamButton.setAttribute("id", "hacknet-node-upgrade-ram-" + nodeName); - upgradeRamButton.id = "hacknet-node-upgrade-ram-" + nodeName; - upgradeRamButton.setAttribute("class", "a-link-button-inactive"); - upgradeRamButton.addEventListener("click", function() { - nodeObj.purchaseRamUpgrade(); - updateHacknetNodesContent(); - return false; - }); - //upgradeCoreButton.setAttribute("id", "hacknet-node-upgrade-core-" + nodeName); - upgradeCoreButton.id = "hacknet-node-upgrade-core-" + nodeName; - upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); - upgradeCoreButton.addEventListener("click", function() { - nodeObj.purchaseCoreUpgrade(); - updateHacknetNodesContent(); - return false; - }); - - //Put all the components together in the li element - span.appendChild(txt); - buttonDiv.appendChild(upgradeLevelButton); - buttonDiv.appendChild(upgradeRamButton); - buttonDiv.appendChild(upgradeCoreButton); - span.appendChild(buttonDiv); - listItem.appendChild(span); - - document.getElementById("hacknet-nodes-list").appendChild(listItem); - - //Set the text and stuff inside the DOM element - updateHacknetNodeDomElement(nodeObj); -} - -//Updates information on a single hacknet node DOM element -function updateHacknetNodeDomElement(nodeObj) { - var nodeName = nodeObj.name; - var txt = document.getElementById("hacknet-node-text-" + nodeName); - if (txt == null) {throw new Error("Cannot find text element");} - txt.innerHTML = "Node name: " + nodeName + "
" + - "Production: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(nodeObj.totalMoneyGenerated, 2) + - " ($" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(nodeObj.moneyGainRatePerSecond, 2) + " / second)
" + - "Level: " + nodeObj.level + "
" + - "RAM: " + nodeObj.ram + "GB
" + - "Cores: " + nodeObj.cores; - - //Upgrade level - var upgradeLevelButton = document.getElementById("hacknet-node-upgrade-level-" + nodeName); - if (upgradeLevelButton == null) {throw new Error("Cannot find upgrade level button element");} - if (nodeObj.level >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel) { - upgradeLevelButton.innerHTML = "MAX LEVEL"; - upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); - } else { - var multiplier = 0; - if (hacknetNodePurchaseMultiplier == 0) { - //Max - multiplier = getMaxNumberLevelUpgrades(nodeObj); - } else { - var levelsToMax = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - nodeObj.level; - multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier); - } - - var upgradeLevelCost = nodeObj.calculateLevelUpgradeCost(multiplier); - upgradeLevelButton.innerHTML = "Upgrade Hacknet Node Level x" + multiplier + - " - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeLevelCost, 2); - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeLevelCost)) { - upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); - } else { - upgradeLevelButton.setAttribute("class", "a-link-button"); - } - } - - //Upgrade RAM - var upgradeRamButton = document.getElementById("hacknet-node-upgrade-ram-" + nodeName); - if (upgradeRamButton == null) {throw new Error("Cannot find upgrade ram button element");} - if (nodeObj.ram >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxRam) { - upgradeRamButton.innerHTML = "MAX RAM"; - upgradeRamButton.setAttribute("class", "a-link-button-inactive"); - } else { - var upgradeRamCost = nodeObj.calculateRamUpgradeCost(); - upgradeRamButton.innerHTML = "Upgrade Hacknet Node RAM - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeRamCost, 2); - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeRamCost)) { - upgradeRamButton.setAttribute("class", "a-link-button-inactive"); - } else { - upgradeRamButton.setAttribute("class", "a-link-button"); - } - } - - //Upgrade Cores - var upgradeCoreButton = document.getElementById("hacknet-node-upgrade-core-" + nodeName); - if (upgradeCoreButton == null) {throw new Error("Cannot find upgrade cores button element");} - if (nodeObj.cores >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxCores) { - upgradeCoreButton.innerHTML = "MAX CORES"; - upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); - } else { - var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost(); - upgradeCoreButton.innerHTML = "Purchase additional CPU Core - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeCoreCost, 2); - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeCoreCost)) { - upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); - } else { - upgradeCoreButton.setAttribute("class", "a-link-button"); - } - } -} - -function processAllHacknetNodeEarnings(numCycles) { - var total = 0; - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { - total += processSingleHacknetNodeEarnings(numCycles, __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]); - } - return total; -} - -function processSingleHacknetNodeEarnings(numCycles, nodeObj) { - var cyclesPerSecond = 1000 / __WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed; - var earningPerCycle = nodeObj.moneyGainRatePerSecond / cyclesPerSecond; - if (isNaN(earningPerCycle)) {throw new Error("Calculated Earnings is not a number");} - var totalEarnings = numCycles * earningPerCycle; - nodeObj.totalMoneyGenerated += totalEarnings; - nodeObj.onlineTimeSeconds += (numCycles * (__WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed / 1000)); - __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gainMoney(totalEarnings); - return totalEarnings; -} - -function getHacknetNode(name) { - for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) { - if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i].name == name) { - return __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]; - } - } - return null; -} - - - - /***/ }), /* 40 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -41896,6 +41896,22 @@ function gameOptionsBoxOpen() { /***/ }), /* 41 */ +/***/ (function(module, exports) { + +module.exports = function() { + throw new Error("define cannot be used indirect"); +}; + + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + +module.exports.id = 'ace/mode/javascript_worker'; +module.exports.src = "\"no use strict\";(function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return 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),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}})(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/range\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){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 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={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(0==cmp)return this;if(-1==cmp)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(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).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)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},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){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,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){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&\").replace(/\"/g,\""\").replace(/'/g,\"'\").replace(/i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(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(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/javascript/jshint\",[\"require\",\"exports\",\"module\"],function(acequire,exports,module){module.exports=function outer(modules,cache,entry){function newRequire(name,jumped){if(!cache[name]){if(!modules[name]){var currentRequire=\"function\"==typeof acequire&&acequire;if(!jumped&¤tRequire)return currentRequire(name,!0);if(previousRequire)return previousRequire(name,!0);var err=Error(\"Cannot find module '\"+name+\"'\");throw err.code=\"MODULE_NOT_FOUND\",err}var m=cache[name]={exports:{}};modules[name][0].call(m.exports,function(x){var id=modules[name][1][x];return newRequire(id?id:x)},m,m.exports,outer,modules,cache,entry)}return cache[name].exports}for(var previousRequire=\"function\"==typeof acequire&&acequire,i=0;entry.length>i;i++)newRequire(entry[i]);return newRequire(entry[0])}({\"/node_modules/browserify/node_modules/events/events.js\":[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return\"function\"==typeof arg}function isNumber(arg){return\"number\"==typeof arg}function isObject(arg){return\"object\"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError(\"n must be a positive number\");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),\"error\"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified \"error\" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(this._events||(this._events={}),this._events.newListener&&this.emit(\"newListener\",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error(\"(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.\",this._events[type].length),\"function\"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError(\"listener must be a function\");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit(\"removeListener\",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),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){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)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),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;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp\"),infix(\"[\",function(left,that){var s,e=expression(10);return e&&\"(string)\"===e.type&&(state.option.evil||\"eval\"!==e.value&&\"execScript\"!==e.value||isGlobalEval(left,state)&&warning(\"W061\"),countMember(e.value),!state.option.sub&®.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning(\"W069\",state.tokens.prev,e.value))),advance(\"]\",that),e&&\"hasOwnProperty\"===e.value&&\"=\"===state.tokens.next.value&&warning(\"W001\"),that.left=left,that.right=e,that},160,!0),prefix(\"[\",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning(\"W118\",state.tokens.curr,\"array comprehension\"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));\"(end)\"!==state.tokens.next.id;){for(;\",\"===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning(\"W128\");do advance(\",\");while(\",\"===state.tokens.next.id);continue}warning(\"W070\")}advance(\",\")}if(\"]\"===state.tokens.next.id)break;if(this.first.push(expression(10)),\",\"!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),\"]\"===state.tokens.next.id&&!state.inES5()){warning(\"W070\",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance(\"]\",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;\"}\"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||\",\"!==peekIgnoreEOL().id&&\"}\"!==peekIgnoreEOL().id)if(\":\"===peek().id||\"get\"!==nextVal&&\"set\"!==nextVal){if(\"*\"===state.tokens.next.value&&\"(punctuator)\"===state.tokens.next.type?(state.inES6()||warning(\"W104\",state.tokens.next,\"generator functions\",\"6\"),advance(\"*\"),isGeneratorMethod=!0):isGeneratorMethod=!1,\"[\"===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),\"string\"!=typeof i)break;\"(\"===state.tokens.next.value?(state.inES6()||warning(\"W104\",state.tokens.curr,\"concise methods\",\"6\"),doFunction({type:isGeneratorMethod?\"generator\":null})):(advance(\":\"),expression(10))}else advance(nextVal),state.inES5()||error(\"E034\"),i=propertyName(),i||state.inES6()||error(\"E035\"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f[\"(params)\"],\"get\"===nextVal&&i&&p?warning(\"W076\",t,p[0],i):\"set\"!==nextVal||!i||p&&1===p.length||warning(\"W077\",t,i);else state.inES6()||warning(\"W104\",state.tokens.next,\"object short notation\",\"6\"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),\",\"!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),\",\"===state.tokens.next.id?warning(\"W070\",state.tokens.curr):\"}\"!==state.tokens.next.id||state.inES5()||warning(\"W070\",state.tokens.curr)}return b&&(indent-=state.option.indent),advance(\"}\",this),checkProperties(props),this},x.fud=function(){error(\"E036\",state.tokens.curr)}}(delim(\"{\"));var conststatement=stmt(\"const\",function(context){return blockVariableStatement(\"const\",this,context)});conststatement.exps=!0;var letstatement=stmt(\"let\",function(context){return blockVariableStatement(\"let\",this,context)});letstatement.exps=!0;var varstatement=stmt(\"var\",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning(\"W132\",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct[\"(global)\"]&&(predefined[t.id]===!1?warning(\"W079\",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning(\"W129\",t.token,t.id)),t.id&&(\"for\"===implied?(state.funct[\"(scope)\"].has(t.id)||report&&warning(\"W088\",t.token,t.id),state.funct[\"(scope)\"].block.use(t.id,t.token)):(state.funct[\"(scope)\"].addlabel(t.id,{type:\"var\",token:t.token}),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.id,t.token)),names.push(t.token)));if(\"=\"===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance(\"=\"),prefix||!report||state.funct[\"(loopage)\"]||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),\"=\"===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct[\"(params)\"]||-1===state.funct[\"(params)\"].indexOf(state.tokens.next.value))&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),\",\"!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt(\"class\",function(){return classdef.call(this,!0)}),blockstmt(\"function\",function(context){var inexport=context&&context.inexport,generator=!1;\"*\"===state.tokens.next.value&&(advance(\"*\"),state.inES6({strict:!0})?generator=!0:warning(\"W119\",state.tokens.curr,\"function*\",\"6\")),inblock&&warning(\"W082\",state.tokens.curr);var i=optionalidentifier();return state.funct[\"(scope)\"].addlabel(i,{type:\"function\",token:state.tokens.curr}),void 0===i?warning(\"W025\"):inexport&&state.funct[\"(scope)\"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?\"generator\":null,ignoreLoopFunc:inblock}),\"(\"===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error(\"E039\"),this}),prefix(\"function\",function(){var generator=!1;\"*\"===state.tokens.next.value&&(state.inES6()||warning(\"W119\",state.tokens.curr,\"function*\",\"6\"),advance(\"*\"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?\"generator\":null}),this}),blockstmt(\"if\",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance(\"(\");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type=\"(punctuator)\"===expr.type&&\"!\"===expr.value?\"(negative)\":\"(positive)\"),advance(\")\",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&\"(negative)\"===forinifcheck.type&&s&&s[0]&&\"(identifier)\"===s[0].type&&\"continue\"===s[0].value&&(forinifcheck.type=\"(negative-with-continue)\"),\"else\"===state.tokens.next.id&&(advance(\"else\"),\"if\"===state.tokens.next.id||\"switch\"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt(\"try\",function(){function doCatch(){if(advance(\"catch\"),advance(\"(\"),state.funct[\"(scope)\"].stack(\"catchparams\"),checkPunctuators(state.tokens.next,[\"[\",\"{\"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct[\"(scope)\"].addParam(token.id,token,\"exception\")})}else\"(identifier)\"!==state.tokens.next.type?warning(\"E030\",state.tokens.next,state.tokens.next.value):state.funct[\"(scope)\"].addParam(identifier(),state.tokens.curr,\"exception\");\"if\"===state.tokens.next.value&&(state.inMoz()||warning(\"W118\",state.tokens.curr,\"catch filter\"),advance(\"if\"),expression(0)),advance(\")\"),block(!1),state.funct[\"(scope)\"].unstack()}var b;for(block(!0);\"catch\"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning(\"W118\",state.tokens.next,\"multiple catch blocks\"),doCatch(),b=!0;return\"finally\"===state.tokens.next.id?(advance(\"finally\"),block(!0),void 0):(b||error(\"E021\",state.tokens.next,\"catch\",state.tokens.next.value),this)}),blockstmt(\"while\",function(){var t=state.tokens.next;return state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this}).labelled=!0,blockstmt(\"with\",function(){var t=state.tokens.next;return state.isStrict()?error(\"E010\",state.tokens.curr):state.option.withstmt||warning(\"W085\",state.tokens.curr),advance(\"(\"),expression(0),advance(\")\",t),block(!0,!0),this}),blockstmt(\"switch\",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct[\"(breakage)\"]+=1,advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),t=state.tokens.next,advance(\"{\"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case\"case\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"case\":case\"continue\":case\"return\":case\"switch\":case\"throw\":break;default:state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"case\")}advance(\"case\"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(\":\"),state.funct[\"(verb)\"]=\"case\";break;case\"default\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"continue\":case\"return\":case\"throw\":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"default\"))}advance(\"default\"),g=!0,advance(\":\");break;case\"}\":return noindent||(indent-=state.option.indent),advance(\"}\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(verb)\"]=void 0,void 0;case\"(end)\":return error(\"E023\",state.tokens.next,\"}\"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case\",\":return error(\"E040\"),void 0;case\":\":g=!1,statements();break;default:return error(\"E025\",state.tokens.curr),void 0}else{if(\":\"!==state.tokens.curr.id)return error(\"E021\",state.tokens.next,\"case\",state.tokens.next.value),void 0;advance(\":\"),error(\"E024\",state.tokens.curr,\":\"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt(\"debugger\",function(){return state.option.debug||warning(\"W087\",this),this}).exps=!0,function(){var x=stmt(\"do\",function(){state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance(\"while\");var t=state.tokens.next;return advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt(\"for\",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;\"each\"===t.value&&(foreachtok=t,advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),increaseComplexityCount(),advance(\"(\");var nextop,comma,initializer,i=0,inof=[\"in\",\"of\"],level=0;checkPunctuators(state.tokens.next,[\"{\",\"[\"])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,[\"{\",\"[\"])?++level:checkPunctuators(nextop,[\"}\",\"]\"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,\",\")?comma=nextop:!initializer&&checkPunctuator(nextop,\"=\")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&\";\"!==nextop.value&&\"(end)\"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||\"of\"!==nextop.value||warning(\"W104\",nextop,\"for of\",\"6\");var ok=!(initializer||comma);if(initializer&&error(\"W133\",comma,nextop.value,\"initializer is forbidden\"),comma&&error(\"W133\",comma,nextop.value,\"more than one ForBinding\"),\"var\"===state.tokens.next.id?(advance(\"var\"),state.tokens.curr.fud({prefix:!0})):\"let\"===state.tokens.next.id||\"const\"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:\"for\",ignore:!ok}),advance(nextop.value),expression(20),advance(\")\",t),\"in\"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:\"(none)\"})),state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,s=block(!0,!0),\"in\"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&(\"object\"!=typeof s[0]||\"if\"!==s[0].value)||\"(positive)\"===check.type&&s.length>1||\"(negative)\"===check.type)&&warning(\"W089\",this)}state.forinifcheckneeded=!1}state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}else{if(foreachtok&&error(\"E045\",foreachtok),\";\"!==state.tokens.next.id)if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud();else if(\"let\"===state.tokens.next.id)advance(\"let\"),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud();else for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(\";\"),state.funct[\"(loopage)\"]+=1,\";\"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(\";\"),\";\"===state.tokens.next.id&&error(\"E021\",state.tokens.next,\")\",\";\"),\")\"!==state.tokens.next.id)for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();advance(\")\",t),state.funct[\"(breakage)\"]+=1,block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}return letscope&&state.funct[\"(scope)\"].unstack(),this}).labelled=!0,stmt(\"break\",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value):(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"continue\",function(){var v=state.tokens.next.value;return 0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value),state.funct[\"(loopage)\"]||warning(\"W052\",state.tokens.next,this.value),state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"return\",function(){return this.line===startLine(state.tokens.next)?\";\"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)):\"(punctuator)\"===state.tokens.next.type&&[\"[\",\"{\",\"+\",\"-\"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix(\"yield\",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct[\"(generator)\"]?\"(catch)\"===state.funct[\"(name)\"]&&state.funct[\"(context)\"][\"(generator)\"]||error(\"E046\",state.tokens.curr,\"yield\"):state.inES6()||warning(\"W104\",state.tokens.curr,\"yield\",\"6\"),state.funct[\"(generator)\"]=\"yielded\";var delegatingYield=!1;return\"*\"===state.tokens.next.value&&(delegatingYield=!0,advance(\"*\")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||\";\"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)),state.inMoz()&&\")\"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||\"yield\"===prev.id)&&error(\"E050\",this)),this})),stmt(\"throw\",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt(\"import\",function(){if(state.inES6()||warning(\"W119\",state.tokens.curr,\"import\",\"6\"),\"(string)\"===state.tokens.next.type)return advance(\"(string)\"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value)return advance(\"from\"),advance(\"(string)\"),this;advance(\",\")}if(\"*\"===state.tokens.next.id)advance(\"*\"),advance(\"as\"),state.tokens.next.identifier&&(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}));else for(advance(\"{\");;){if(\"}\"===state.tokens.next.value){advance(\"}\");break}var importName;if(\"default\"===state.tokens.next.type?(importName=\"default\",advance(\"default\")):importName=identifier(),\"as\"===state.tokens.next.value&&(advance(\"as\"),importName=identifier()),state.funct[\"(scope)\"].addlabel(importName,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return advance(\"from\"),advance(\"(string)\"),this}).exps=!0,stmt(\"export\",function(){var token,identifier,ok=!0;if(state.inES6()||(warning(\"W119\",state.tokens.curr,\"export\",\"6\"),ok=!1),state.funct[\"(scope)\"].block.isGlobal()||(error(\"E053\",state.tokens.curr),ok=!1),\"*\"===state.tokens.next.value)return advance(\"*\"),advance(\"from\"),advance(\"(string)\"),this;if(\"default\"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance(\"default\");var exportType=state.tokens.next.id;return(\"function\"===exportType||\"class\"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct[\"(scope)\"].addlabel(identifier,{type:exportType,token:token}),state.funct[\"(scope)\"].setExported(identifier,token)),this}if(\"{\"===state.tokens.next.value){advance(\"{\");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),\"as\"===state.tokens.next.value&&(advance(\"as\"),state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance()),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return\"from\"===state.tokens.next.value?(advance(\"from\"),advance(\"(string)\")):ok&&exportedTokens.forEach(function(token){state.funct[\"(scope)\"].setExported(token.value,token)}),this}if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud({inexport:!0});else if(\"let\"===state.tokens.next.id)advance(\"let\"),state.tokens.curr.fud({inexport:!0});else if(\"const\"===state.tokens.next.id)advance(\"const\"),state.tokens.curr.fud({inexport:!0});else if(\"function\"===state.tokens.next.id)this.block=!0,advance(\"function\"),state.syntax[\"function\"].fud({inexport:!0});else if(\"class\"===state.tokens.next.id){this.block=!0,advance(\"class\");var classNameToken=state.tokens.next;state.syntax[\"class\"].fud(),state.funct[\"(scope)\"].setExported(classNameToken.value,classNameToken)}else error(\"E024\",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord(\"abstract\"),FutureReservedWord(\"boolean\"),FutureReservedWord(\"byte\"),FutureReservedWord(\"char\"),FutureReservedWord(\"class\",{es5:!0,nud:classdef}),FutureReservedWord(\"double\"),FutureReservedWord(\"enum\",{es5:!0}),FutureReservedWord(\"export\",{es5:!0}),FutureReservedWord(\"extends\",{es5:!0}),FutureReservedWord(\"final\"),FutureReservedWord(\"float\"),FutureReservedWord(\"goto\"),FutureReservedWord(\"implements\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"import\",{es5:!0}),FutureReservedWord(\"int\"),FutureReservedWord(\"interface\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"long\"),FutureReservedWord(\"native\"),FutureReservedWord(\"package\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"private\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"protected\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"public\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"short\"),FutureReservedWord(\"static\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"super\",{es5:!0}),FutureReservedWord(\"synchronized\"),FutureReservedWord(\"transient\"),FutureReservedWord(\"volatile\");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,[\"[\",\"{\"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,[\"[\",\"{\"])?bracketStack+=1:checkPunctuators(pn,[\"]\",\"}\"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&\"for\"===pn.value&&!checkPunctuator(prev,\".\")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,[\"}\",\"]\"])){if(\"=\"===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if(\".\"===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,\";\")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&\"(end)\"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode=\"use\",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning(\"W098\",v.token,v.raw_text||v.value),v.undef&&state.funct[\"(scope)\"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains([\"use\",\"define\",\"generate\",\"filter\"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&\"use\"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&\"define\"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&\"generate\"===_current.mode?(state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):_current&&\"filter\"===_current.mode?(use(v)&&state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||\"object\"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope=\"(main)\"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;\"-\"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],(\"esversion\"===optionKey&&5===o[optionKey]||\"es5\"===optionKey&&o[optionKey])&&warning(\"I003\"),\"newcap\"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj[\"(explicitNewcap)\"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on(\"warning\",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on(\"error\",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor(\"(global)\",null,{\"(global)\":!0,\"(scope)\":scopeManagerInst,\"(comparray)\":arrayComprehension(),\"(metrics)\":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt(\"E004\",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax[\"(begin)\"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+\"[\\\\s\\\\S]*?\"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,\"ig\"),s=s.replace(reIgnore,function(match){return match.replace(/./g,\" \")}))})),lex=new Lexer(s),lex.on(\"warning\",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"error\",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"fatal\",function(ev){quit(\"E041\",ev.line,ev.from)}),lex.on(\"Identifier\",function(ev){emitter.emit(\"Identifier\",ev)}),lex.on(\"String\",function(ev){emitter.emit(\"String\",ev)}),lex.on(\"Number\",function(ev){emitter.emit(\"Number\",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case\"{\":case\"[\":destructuringAssignOrJsonValue();break;default:directives(),state.directive[\"use strict\"]&&\"global\"!==state.option.strict&&warning(\"W097\",state.tokens.prev),statements()}\"(end)\"!==state.tokens.next.id&&quit(\"E041\",state.tokens.curr.line),state.funct[\"(scope)\"].unstack()}catch(err){if(!err||\"JSHintError\"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:\"(main)\",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if(\"(main)\"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct[\"(scope)\"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct[\"(scope)\"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f[\"(name)\"],fu.param=f[\"(params)\"],fu.line=f[\"(line)\"],fu.character=f[\"(character)\"],fu.last=f[\"(last)\"],fu.lastcharacter=f[\"(lastcharacter)\"],fu.metrics={complexity:f[\"(metrics)\"].ComplexityCount,parameters:f[\"(metrics)\"].arity,statements:f[\"(metrics)\"].statementCount},data.functions.push(fu)}var unuseds=state.funct[\"(scope)\"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if(\"number\"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();\"object\"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./lex.js\":\"/node_modules/jshint/src/lex.js\",\"./messages.js\":\"/node_modules/jshint/src/messages.js\",\"./options.js\":\"/node_modules/jshint/src/options.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./scope-manager.js\":\"/node_modules/jshint/src/scope-manager.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",\"./style.js\":\"/node_modules/jshint/src/style.js\",\"./vars.js\":\"/node_modules/jshint/src/vars.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/lex.js\":[function(_dereq_,module,exports){\"use strict\";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;\"string\"==typeof lines&&(lines=lines.replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\").split(\"\\n\")),lines[0]&&\"#!\"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf(\"node\")&&(state.option.node=!0),lines[0]=\"\"),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input=\"\",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=\" \";this.ignoreLinterErrors=!1}var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,unicodeData=_dereq_(\"../data/ascii-identifier-data.js\"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(\" \").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case\".\":if(/^[0-9]$/.test(this.peek(1)))return null;if(\".\"===this.peek(1)&&\".\"===this.peek(2))return{type:Token.Punctuator,value:\"...\"};case\"(\":case\")\":case\";\":case\",\":case\"[\":case\"]\":case\":\":case\"~\":case\"?\":return{type:Token.Punctuator,value:ch1};case\"{\":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case\"}\":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case\"#\":return{type:Token.Punctuator,value:ch1};case\"\":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),\">\"===ch1&&\">\"===ch2&&\">\"===ch3&&\"=\"===ch4?{type:Token.Punctuator,value:\">>>=\"}:\"=\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"===\"}:\"!\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"!==\"}:\">\"===ch1&&\">\"===ch2&&\">\"===ch3?{type:Token.Punctuator,value:\">>>\"}:\"<\"===ch1&&\"<\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"<<=\"}:\">\"===ch1&&\">\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\">>=\"}:\"=\"===ch1&&\">\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&\"+-<>&|\".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:\"<>=!+-*%&|^\".indexOf(ch1)>=0?\"=\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:\"/\"===ch1?\"=\"===ch2?{type:Token.Punctuator,value:\"/=\"}:{type:Token.Punctuator,value:\"/\"}:null},scanComments:function(){function commentToken(label,body,opt){var special=[\"jshint\",\"jslint\",\"members\",\"member\",\"globals\",\"global\",\"exported\"],isSpecial=!1,value=label+body,commentType=\"plain\";return opt=opt||{},opt.isMultiline&&(value+=\"*/\"),body=body.replace(/\\n/g,\" \"),\"/*\"===label&®.fallsThrough.test(body)&&(isSpecial=!0,commentType=\"falls through\"),special.forEach(function(str){if(!isSpecial&&(\"//\"!==label||\"jshint\"===str)&&(\" \"===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||\" \"!==body.charAt(0)||\" \"!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+\" \"+str,body=body.substr(str.length+1)),isSpecial))switch(str){case\"member\":commentType=\"members\";break;case\"global\":commentType=\"globals\";break;default:var options=body.split(\":\").map(function(v){return v.replace(/^\\s+/,\"\").replace(/\\s+$/,\"\")});if(2===options.length)switch(options[0]){case\"ignore\":switch(options[1]){case\"start\":self.ignoringLinterErrors=!0,isSpecial=!1;break;case\"end\":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if(\"*\"===ch1&&\"/\"===ch2)return this.trigger(\"error\",{code:\"E018\",line:startLine,character:startChar}),this.skip(2),null;if(\"/\"!==ch1||\"*\"!==ch2&&\"/\"!==ch2)return null;if(\"/\"===ch2)return this.skip(this.input.length),commentToken(\"//\",rest);var body=\"\";if(\"*\"===ch2){for(this.inComment=!0,this.skip(2);\"*\"!==this.peek()||\"/\"!==this.peek(1);)if(\"\"===this.peek()){if(body+=\"\\n\",!this.nextLine())return this.trigger(\"error\",{code:\"E017\",line:startLine,character:startChar}),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=[\"if\",\"in\",\"do\",\"var\",\"for\",\"new\",\"try\",\"let\",\"this\",\"else\",\"case\",\"void\",\"with\",\"enum\",\"while\",\"break\",\"catch\",\"throw\",\"const\",\"yield\",\"class\",\"super\",\"return\",\"typeof\",\"delete\",\"switch\",\"export\",\"import\",\"default\",\"finally\",\"extends\",\"function\",\"continue\",\"debugger\",\"instanceof\"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id=\"\",index=0,readUnicodeEscapeSequence=function(){if(index+=1,\"u\"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,\"\\\\u\"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case\"true\":case\"false\":type=Token.BooleanLiteral;break;case\"null\":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return\"$\"===ch||\"_\"===ch||\"\\\\\"===ch||ch>=\"a\"&&\"z\">=ch||ch>=\"A\"&&\"Z\">=ch}var bad,index=0,value=\"\",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if(\".\"!==char&&!isDecimalDigit(char))return null;if(\".\"!==char){for(value=this.peek(index),index+=1,char=this.peek(index),\"0\"===value&&((\"x\"===char||\"X\"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),(\"o\"===char||\"O\"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Octal integer literal\",\"6\"]}),index+=1,value+=char),(\"b\"===char||\"B\"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Binary integer literal\",\"6\"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if(\".\"===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if(\"e\"===char||\"E\"===char){if(value+=char,index+=1,char=this.peek(index),(\"+\"===char||\"-\"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case\"'\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\'\"]},checks,function(){return state.jsonMode});break;case\"b\":char=\"\\\\b\";break;case\"f\":char=\"\\\\f\";break;case\"n\":char=\"\\\\n\";break;case\"r\":char=\"\\\\r\";break;case\"t\":char=\"\\\\t\";break;case\"0\":char=\"\\\\0\";var n=parseInt(this.peek(1),10);this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case\"u\":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger(\"warning\",{code:\"W052\",line:this.line,character:this.char,data:[\"u\"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case\"v\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\v\"]},checks,function(){return state.jsonMode}),char=\"\u000b\";break;case\"x\":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\x-\"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case\"\\\\\":char=\"\\\\\\\\\";break;case'\"':char='\\\\\"';break;case\"/\":break;case\"\":allowNewLine=!0,char=\"\"}return{\"char\":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value=\"\",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if(\"`\"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,\"char\":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||\"}\"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;\"`\"!==this.peek();){for(;\"\"===(ch=this.peek());)if(value+=\"\\n\",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger(\"error\",{code:\"E052\",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if(\"$\"===ch&&\"{\"===this.peek(1))return value+=\"${\",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif(\"\\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else\"`\"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if('\"'!==quote&&\"'\"!==quote)return null;this.triggerAsync(\"warning\",{code:\"W108\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&'\"'!==quote});var value=\"\",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(\"\"===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync(\"warning\",{code:\"W043\",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync(\"warning\",{code:\"W042\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger(\"warning\",{code:\"W112\",line:this.line,character:this.char}),!this.nextLine())return this.trigger(\"error\",{code:\"E029\",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(\" \">char&&this.trigger(\"warning\",{code:\"W113\",line:this.line,character:this.char,data:[\"\"]}),\"\\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body=\"\",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){\" \">char&&(malformed=!0,this.trigger(\"warning\",{code:\"W048\",line:this.line,character:this.char})),\"<\"===char&&(malformed=!0,this.trigger(\"warning\",{code:\"W049\",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||\"/\"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)\"]\"===char&&(\"\\\\\"!==this.peek(index-1)||\"\\\\\"===this.peek(index-2))&&(isCharSet=!1),\"\\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if(\"\\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),\"/\"===char){index+=1;continue}if(\"[\"===char){index+=1;continue}}if(\"[\"!==char){if(\"/\"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger(\"error\",{code:\"E015\",line:this.line,character:this.from}),void this.trigger(\"fatal\",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(\"\"))}catch(err){malformed=!0,this.trigger(\"error\",{code:\"E016\",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith(\"/*\",\"//\")||this.inComment&&endsWith(\"*/\")||(this.input=\"\")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger(\"warning\",{code:\"W125\",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger(\"warning\",{code:\"W100\",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen=0;--i){var scopeLabels=_scopeStack[i][\"(labels)\"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(usages)\"][labelName])return current[\"(usages)\"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if(\"outer\"===state.option.shadow)for(var isGlobal=\"global\"===_currentFunctBody[\"(type)\"],isNewFunction=\"functionparams\"===_current[\"(type)\"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem[\"(labels)\"][labelName]&&warning(\"W123\",token,labelName),stackItem[\"(breakLabels)\"][labelName]&&warning(\"W123\",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&\"function\"===type||\"function\"!==type)&&warning(\"W003\",token,labelName)}var _current,_scopeStack=[];_newScope(\"global\"),_current[\"(predefined)\"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt=\"last-param\"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:[\"var\"],\"last-param\":[\"var\",\"param\"],strict:[\"var\",\"param\",\"last-param\"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning(\"W098\",{line:line,from:chr},raw_name),(unused_opt||\"var\"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0][\"(predefined)\"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||\"functionparams\"!==previousScope[\"(type)\"]||(_current[\"(isFuncBody)\"]=!0,_current[\"(context)\"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams=\"functionparams\"===_current[\"(type)\"],isUnstackingFunctionOuter=\"functionouter\"===_current[\"(type)\"],currentUsages=_current[\"(usages)\"],currentLabels=_current[\"(labels)\"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf(\"__proto__\")&&usedLabelNameList.push(\"__proto__\"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel[\"(type)\"];if(usedLabel[\"(useOutsideOfScope)\"]&&!state.option.funcscope){var usedTokens=usage[\"(tokens)\"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel[\"(function)\"]===usedTokens[j][\"(function)\"]&&error(\"W038\",usedTokens[j],usedLabelName)}if(_current[\"(labels)\"][usedLabelName][\"(unused)\"]=!1,\"const\"===usedLabelType&&usage[\"(modified)\"])for(j=0;usage[\"(modified)\"].length>j;j++)error(\"E013\",usage[\"(modified)\"][j],usedLabelName);if((\"function\"===usedLabelType||\"class\"===usedLabelType)&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)error(\"W021\",usage[\"(reassigned)\"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct[\"(isCapturing)\"]=!0),subScope)if(subScope[\"(usages)\"][usedLabelName]){var subScopeUsage=subScope[\"(usages)\"][usedLabelName];subScopeUsage[\"(modified)\"]=subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]),subScopeUsage[\"(tokens)\"]=subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]),subScopeUsage[\"(reassigned)\"]=subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]),subScopeUsage[\"(onlyUsedSubFunction)\"]=!1}else subScope[\"(usages)\"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"]=!0);else if(\"boolean\"==typeof _current[\"(predefined)\"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current[\"(predefined)\"][usedLabelName]===!1&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)warning(\"W020\",usage[\"(reassigned)\"][j])}else if(usage[\"(tokens)\"])for(j=0;usage[\"(tokens)\"].length>j;j++){var undefinedToken=usage[\"(tokens)\"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning(\"W117\",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],\"var\")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName][\"(blockscoped)\"]||\"exception\"===currentLabels[defLabelName][\"(type)\"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope[\"(labels)\"][defLabelName]=currentLabels[defLabelName],\"global\"!==_currentFunctBody[\"(type)\"]&&(subScope[\"(labels)\"][defLabelName][\"(useOutsideOfScope)\"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope[\"(isFuncBody)\"]||\"global\"===scope[\"(type)\"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||\"param\",\"exception\"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&\"exception\"!==previouslyDefinedLabelType&&(state.option.node||warning(\"W002\",state.tokens.next,labelName))}if(_.has(_current[\"(labels)\"],labelName)?_current[\"(labels)\"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":token,\"(unused)\":!0},_current[\"(params)\"].push(labelName)),_.has(_current[\"(usages)\"],labelName)){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}},validateParams:function(){if(\"global\"!==_currentFunctBody[\"(type)\"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody[\"(parent)\"];currentFunctParamScope[\"(params)\"]&¤tFunctParamScope[\"(params)\"].forEach(function(labelName){var label=currentFunctParamScope[\"(labels)\"][labelName];label&&label.duplicated&&(isStrict?warning(\"E011\",label[\"(token)\"],labelName):state.option.shadow!==!0&&warning(\"W004\",label[\"(token)\"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf(\"__proto__\")&&list.push(\"__proto__\"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return\"__proto__\"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName][\"(type)\"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0][\"(labels)\"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName][\"(unused)\"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope[\"(type)\"])break;if(_.has(scope[\"(labels)\"],labelName)&&!scope[\"(labels)\"][labelName][\"(blockscoped)\"])return scope[\"(labels)\"][labelName][\"(unused)\"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped=\"let\"===type||\"const\"===type||\"class\"===type,isexported=\"global\"===(isblockscoped?_current:_currentFunctBody)[\"(type)\"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current[\"(labels)\"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||\"global\"===_current[\"(type)\"]||(declaredInCurrentScope=!!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName]),!declaredInCurrentScope&&_current[\"(usages)\"][labelName]){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}declaredInCurrentScope?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning(\"W004\",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning(\"E011\",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&\"__proto__\"!==labelName&&\"global\"!==_currentFunctBody[\"(type)\"]&&warning(\"W004\",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),\"global\"===_currentFunctBody[\"(type)\"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current[\"(labels)\"][labelName]&&(!onlyBlockscoped||current[\"(labels)\"][labelName][\"(blockscoped)\"]))return current[\"(labels)\"][labelName][\"(type)\"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&\"functionparams\"===scopeCheck[\"(type)\"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(breakLabels)\"][labelName])return!0;if(\"functionparams\"===current[\"(type)\"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!1,\"(function)\":_currentFunctBody,\"(unused)\":unused}}},block:{isGlobal:function(){return\"global\"===_current[\"(type)\"]},use:function(labelName,token){var paramScope=_currentFunctBody[\"(parent)\"];paramScope&¶mScope[\"(labels)\"][labelName]&&\"param\"===paramScope[\"(labels)\"][labelName][\"(type)\"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope[\"(labels)\"][labelName][\"(unused)\"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token[\"(function)\"]=_currentFunctBody,_current[\"(usages)\"][labelName][\"(tokens)\"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current[\"(usages)\"][labelName][\"(reassigned)\"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current[\"(usages)\"][labelName][\"(modified)\"].push(token)},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!0,\"(unused)\":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning(\"W004\",token,labelName):_checkOuterShadow(labelName,token)),_current[\"(breakLabels)\"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{\"../lodash\":\"/node_modules/jshint/lodash.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/state.js\":[function(_dereq_,module,exports){\"use strict\";var NameStack=_dereq_(\"./name-stack.js\"),state={syntax:{},isStrict:function(){return this.directive[\"use strict\"]||this.inClassBody||this.option.module||\"implied\"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab=\"\",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{\"./name-stack.js\":\"/node_modules/jshint/src/name-stack.js\"}],\"/node_modules/jshint/src/style.js\":[function(_dereq_,module,exports){\"use strict\";exports.register=function(linter){linter.on(\"Identifier\",function(data){linter.getOption(\"proto\")||\"__proto__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name,\"6\"]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"iterator\")||\"__iterator__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"camelcase\")&&data.name.replace(/^_+|_+$/g,\"\").indexOf(\"_\")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn(\"W106\",{line:data.line,\"char\":data.from,data:[data.name]})}),linter.on(\"String\",function(data){var code,quotmark=linter.getOption(\"quotmark\");quotmark&&(\"single\"===quotmark&&\"'\"!==data.quote&&(code=\"W109\"),\"double\"===quotmark&&'\"'!==data.quote&&(code=\"W108\"),quotmark===!0&&(linter.getCache(\"quotmark\")||linter.setCache(\"quotmark\",data.quote),linter.getCache(\"quotmark\")!==data.quote&&(code=\"W110\")),code&&linter.warn(code,{line:data.line,\"char\":data.char}))}),linter.on(\"Number\",function(data){\".\"===data.value.charAt(0)&&linter.warn(\"W008\",{line:data.line,\"char\":data.char,data:[data.value]}),\".\"===data.value.substr(data.value.length-1)&&linter.warn(\"W047\",{line:data.line,\"char\":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn(\"W046\",{line:data.line,\"char\":data.char,data:[data.value]})}),linter.on(\"String\",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption(\"scripturl\")||re.test(data.value)&&linter.warn(\"W107\",{line:data.line,\"char\":data.char})})}},{}],\"/node_modules/jshint/src/vars.js\":[function(_dereq_,module,exports){\"use strict\";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,\"throws\":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},[\"/node_modules/jshint/src/jshint.js\"])}),ace.define(\"ace/mode/javascript_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\",\"ace/mode/javascript/jshint\"],function(acequire,exports,module){\"use strict\";function startRegex(arr){return RegExp(\"^(\"+arr.join(\"|\")+\")\")}var oop=acequire(\"../lib/oop\"),Mirror=acequire(\"../worker/mirror\").Mirror,lint=acequire(\"./javascript/jshint\").JSHINT,disabledWarningsRe=startRegex([\"Bad for in variable '(.+)'.\",'Missing \"use strict\"']),errorsRe=startRegex([\"Unexpected\",\"Expected \",\"Confusing (plus|minus)\",\"\\\\{a\\\\} unterminated regular expression\",\"Unclosed \",\"Unmatched \",\"Unbegun comment\",\"Bad invocation\",\"Missing space after\",\"Missing operator at\"]),infoRe=startRegex([\"Expected an assignment\",\"Bad escapement of EOL\",\"Unexpected comma\",\"Unexpected space\",\"Missing radix parameter.\",\"A leading decimal point can\",\"\\\\['{a}'\\\\] is better written in dot notation.\",\"'{a}' used out of scope\"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval(\"throw 0;\"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,\"\\n\"),!value)return this.sender.emit(\"annotate\",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?\"warning\":\"error\";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type=\"warning\";if(\"Missing semicolon.\"==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),\"error\"==maxErrorLevel&&str&&/[\\w\\d{(['\"]/.test(str)?(error.reason='Missing \";\" before statement',type=\"error\"):type=\"info\"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type=\"info\":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):\"'{a}' is not defined.\"==raw?type=\"warning\":\"'{a}' is defined but never used.\"==raw&&(type=\"info\")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit(\"annotate\",errors)}}.call(JavaScriptWorker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);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__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||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: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r   ᠎              \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});"; + +/***/ }), +/* 43 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */ @@ -42119,155 +42135,10 @@ var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */ }() -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - -module.exports = function() { - throw new Error("define cannot be used indirect"); -}; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports) { - -module.exports.id = 'ace/mode/javascript_worker'; -module.exports.src = "\"no use strict\";(function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return 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),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}})(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/range\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){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 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={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(0==cmp)return this;if(-1==cmp)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(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).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)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},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){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,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){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&\").replace(/\"/g,\""\").replace(/'/g,\"'\").replace(/i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(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(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/javascript/jshint\",[\"require\",\"exports\",\"module\"],function(acequire,exports,module){module.exports=function outer(modules,cache,entry){function newRequire(name,jumped){if(!cache[name]){if(!modules[name]){var currentRequire=\"function\"==typeof acequire&&acequire;if(!jumped&¤tRequire)return currentRequire(name,!0);if(previousRequire)return previousRequire(name,!0);var err=Error(\"Cannot find module '\"+name+\"'\");throw err.code=\"MODULE_NOT_FOUND\",err}var m=cache[name]={exports:{}};modules[name][0].call(m.exports,function(x){var id=modules[name][1][x];return newRequire(id?id:x)},m,m.exports,outer,modules,cache,entry)}return cache[name].exports}for(var previousRequire=\"function\"==typeof acequire&&acequire,i=0;entry.length>i;i++)newRequire(entry[i]);return newRequire(entry[0])}({\"/node_modules/browserify/node_modules/events/events.js\":[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return\"function\"==typeof arg}function isNumber(arg){return\"number\"==typeof arg}function isObject(arg){return\"object\"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError(\"n must be a positive number\");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),\"error\"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified \"error\" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(this._events||(this._events={}),this._events.newListener&&this.emit(\"newListener\",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error(\"(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.\",this._events[type].length),\"function\"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError(\"listener must be a function\");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit(\"removeListener\",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),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){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)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),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;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp\"),infix(\"[\",function(left,that){var s,e=expression(10);return e&&\"(string)\"===e.type&&(state.option.evil||\"eval\"!==e.value&&\"execScript\"!==e.value||isGlobalEval(left,state)&&warning(\"W061\"),countMember(e.value),!state.option.sub&®.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning(\"W069\",state.tokens.prev,e.value))),advance(\"]\",that),e&&\"hasOwnProperty\"===e.value&&\"=\"===state.tokens.next.value&&warning(\"W001\"),that.left=left,that.right=e,that},160,!0),prefix(\"[\",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning(\"W118\",state.tokens.curr,\"array comprehension\"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));\"(end)\"!==state.tokens.next.id;){for(;\",\"===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning(\"W128\");do advance(\",\");while(\",\"===state.tokens.next.id);continue}warning(\"W070\")}advance(\",\")}if(\"]\"===state.tokens.next.id)break;if(this.first.push(expression(10)),\",\"!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),\"]\"===state.tokens.next.id&&!state.inES5()){warning(\"W070\",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance(\"]\",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;\"}\"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||\",\"!==peekIgnoreEOL().id&&\"}\"!==peekIgnoreEOL().id)if(\":\"===peek().id||\"get\"!==nextVal&&\"set\"!==nextVal){if(\"*\"===state.tokens.next.value&&\"(punctuator)\"===state.tokens.next.type?(state.inES6()||warning(\"W104\",state.tokens.next,\"generator functions\",\"6\"),advance(\"*\"),isGeneratorMethod=!0):isGeneratorMethod=!1,\"[\"===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),\"string\"!=typeof i)break;\"(\"===state.tokens.next.value?(state.inES6()||warning(\"W104\",state.tokens.curr,\"concise methods\",\"6\"),doFunction({type:isGeneratorMethod?\"generator\":null})):(advance(\":\"),expression(10))}else advance(nextVal),state.inES5()||error(\"E034\"),i=propertyName(),i||state.inES6()||error(\"E035\"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f[\"(params)\"],\"get\"===nextVal&&i&&p?warning(\"W076\",t,p[0],i):\"set\"!==nextVal||!i||p&&1===p.length||warning(\"W077\",t,i);else state.inES6()||warning(\"W104\",state.tokens.next,\"object short notation\",\"6\"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),\",\"!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),\",\"===state.tokens.next.id?warning(\"W070\",state.tokens.curr):\"}\"!==state.tokens.next.id||state.inES5()||warning(\"W070\",state.tokens.curr)}return b&&(indent-=state.option.indent),advance(\"}\",this),checkProperties(props),this},x.fud=function(){error(\"E036\",state.tokens.curr)}}(delim(\"{\"));var conststatement=stmt(\"const\",function(context){return blockVariableStatement(\"const\",this,context)});conststatement.exps=!0;var letstatement=stmt(\"let\",function(context){return blockVariableStatement(\"let\",this,context)});letstatement.exps=!0;var varstatement=stmt(\"var\",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning(\"W132\",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct[\"(global)\"]&&(predefined[t.id]===!1?warning(\"W079\",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning(\"W129\",t.token,t.id)),t.id&&(\"for\"===implied?(state.funct[\"(scope)\"].has(t.id)||report&&warning(\"W088\",t.token,t.id),state.funct[\"(scope)\"].block.use(t.id,t.token)):(state.funct[\"(scope)\"].addlabel(t.id,{type:\"var\",token:t.token}),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.id,t.token)),names.push(t.token)));if(\"=\"===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance(\"=\"),prefix||!report||state.funct[\"(loopage)\"]||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),\"=\"===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct[\"(params)\"]||-1===state.funct[\"(params)\"].indexOf(state.tokens.next.value))&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),\",\"!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt(\"class\",function(){return classdef.call(this,!0)}),blockstmt(\"function\",function(context){var inexport=context&&context.inexport,generator=!1;\"*\"===state.tokens.next.value&&(advance(\"*\"),state.inES6({strict:!0})?generator=!0:warning(\"W119\",state.tokens.curr,\"function*\",\"6\")),inblock&&warning(\"W082\",state.tokens.curr);var i=optionalidentifier();return state.funct[\"(scope)\"].addlabel(i,{type:\"function\",token:state.tokens.curr}),void 0===i?warning(\"W025\"):inexport&&state.funct[\"(scope)\"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?\"generator\":null,ignoreLoopFunc:inblock}),\"(\"===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error(\"E039\"),this}),prefix(\"function\",function(){var generator=!1;\"*\"===state.tokens.next.value&&(state.inES6()||warning(\"W119\",state.tokens.curr,\"function*\",\"6\"),advance(\"*\"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?\"generator\":null}),this}),blockstmt(\"if\",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance(\"(\");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type=\"(punctuator)\"===expr.type&&\"!\"===expr.value?\"(negative)\":\"(positive)\"),advance(\")\",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&\"(negative)\"===forinifcheck.type&&s&&s[0]&&\"(identifier)\"===s[0].type&&\"continue\"===s[0].value&&(forinifcheck.type=\"(negative-with-continue)\"),\"else\"===state.tokens.next.id&&(advance(\"else\"),\"if\"===state.tokens.next.id||\"switch\"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt(\"try\",function(){function doCatch(){if(advance(\"catch\"),advance(\"(\"),state.funct[\"(scope)\"].stack(\"catchparams\"),checkPunctuators(state.tokens.next,[\"[\",\"{\"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct[\"(scope)\"].addParam(token.id,token,\"exception\")})}else\"(identifier)\"!==state.tokens.next.type?warning(\"E030\",state.tokens.next,state.tokens.next.value):state.funct[\"(scope)\"].addParam(identifier(),state.tokens.curr,\"exception\");\"if\"===state.tokens.next.value&&(state.inMoz()||warning(\"W118\",state.tokens.curr,\"catch filter\"),advance(\"if\"),expression(0)),advance(\")\"),block(!1),state.funct[\"(scope)\"].unstack()}var b;for(block(!0);\"catch\"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning(\"W118\",state.tokens.next,\"multiple catch blocks\"),doCatch(),b=!0;return\"finally\"===state.tokens.next.id?(advance(\"finally\"),block(!0),void 0):(b||error(\"E021\",state.tokens.next,\"catch\",state.tokens.next.value),this)}),blockstmt(\"while\",function(){var t=state.tokens.next;return state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this}).labelled=!0,blockstmt(\"with\",function(){var t=state.tokens.next;return state.isStrict()?error(\"E010\",state.tokens.curr):state.option.withstmt||warning(\"W085\",state.tokens.curr),advance(\"(\"),expression(0),advance(\")\",t),block(!0,!0),this}),blockstmt(\"switch\",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct[\"(breakage)\"]+=1,advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),t=state.tokens.next,advance(\"{\"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case\"case\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"case\":case\"continue\":case\"return\":case\"switch\":case\"throw\":break;default:state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"case\")}advance(\"case\"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(\":\"),state.funct[\"(verb)\"]=\"case\";break;case\"default\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"continue\":case\"return\":case\"throw\":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"default\"))}advance(\"default\"),g=!0,advance(\":\");break;case\"}\":return noindent||(indent-=state.option.indent),advance(\"}\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(verb)\"]=void 0,void 0;case\"(end)\":return error(\"E023\",state.tokens.next,\"}\"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case\",\":return error(\"E040\"),void 0;case\":\":g=!1,statements();break;default:return error(\"E025\",state.tokens.curr),void 0}else{if(\":\"!==state.tokens.curr.id)return error(\"E021\",state.tokens.next,\"case\",state.tokens.next.value),void 0;advance(\":\"),error(\"E024\",state.tokens.curr,\":\"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt(\"debugger\",function(){return state.option.debug||warning(\"W087\",this),this}).exps=!0,function(){var x=stmt(\"do\",function(){state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance(\"while\");var t=state.tokens.next;return advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt(\"for\",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;\"each\"===t.value&&(foreachtok=t,advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),increaseComplexityCount(),advance(\"(\");var nextop,comma,initializer,i=0,inof=[\"in\",\"of\"],level=0;checkPunctuators(state.tokens.next,[\"{\",\"[\"])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,[\"{\",\"[\"])?++level:checkPunctuators(nextop,[\"}\",\"]\"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,\",\")?comma=nextop:!initializer&&checkPunctuator(nextop,\"=\")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&\";\"!==nextop.value&&\"(end)\"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||\"of\"!==nextop.value||warning(\"W104\",nextop,\"for of\",\"6\");var ok=!(initializer||comma);if(initializer&&error(\"W133\",comma,nextop.value,\"initializer is forbidden\"),comma&&error(\"W133\",comma,nextop.value,\"more than one ForBinding\"),\"var\"===state.tokens.next.id?(advance(\"var\"),state.tokens.curr.fud({prefix:!0})):\"let\"===state.tokens.next.id||\"const\"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:\"for\",ignore:!ok}),advance(nextop.value),expression(20),advance(\")\",t),\"in\"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:\"(none)\"})),state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,s=block(!0,!0),\"in\"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&(\"object\"!=typeof s[0]||\"if\"!==s[0].value)||\"(positive)\"===check.type&&s.length>1||\"(negative)\"===check.type)&&warning(\"W089\",this)}state.forinifcheckneeded=!1}state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}else{if(foreachtok&&error(\"E045\",foreachtok),\";\"!==state.tokens.next.id)if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud();else if(\"let\"===state.tokens.next.id)advance(\"let\"),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud();else for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(\";\"),state.funct[\"(loopage)\"]+=1,\";\"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(\";\"),\";\"===state.tokens.next.id&&error(\"E021\",state.tokens.next,\")\",\";\"),\")\"!==state.tokens.next.id)for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();advance(\")\",t),state.funct[\"(breakage)\"]+=1,block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}return letscope&&state.funct[\"(scope)\"].unstack(),this}).labelled=!0,stmt(\"break\",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value):(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"continue\",function(){var v=state.tokens.next.value;return 0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value),state.funct[\"(loopage)\"]||warning(\"W052\",state.tokens.next,this.value),state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"return\",function(){return this.line===startLine(state.tokens.next)?\";\"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)):\"(punctuator)\"===state.tokens.next.type&&[\"[\",\"{\",\"+\",\"-\"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix(\"yield\",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct[\"(generator)\"]?\"(catch)\"===state.funct[\"(name)\"]&&state.funct[\"(context)\"][\"(generator)\"]||error(\"E046\",state.tokens.curr,\"yield\"):state.inES6()||warning(\"W104\",state.tokens.curr,\"yield\",\"6\"),state.funct[\"(generator)\"]=\"yielded\";var delegatingYield=!1;return\"*\"===state.tokens.next.value&&(delegatingYield=!0,advance(\"*\")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||\";\"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)),state.inMoz()&&\")\"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||\"yield\"===prev.id)&&error(\"E050\",this)),this})),stmt(\"throw\",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt(\"import\",function(){if(state.inES6()||warning(\"W119\",state.tokens.curr,\"import\",\"6\"),\"(string)\"===state.tokens.next.type)return advance(\"(string)\"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value)return advance(\"from\"),advance(\"(string)\"),this;advance(\",\")}if(\"*\"===state.tokens.next.id)advance(\"*\"),advance(\"as\"),state.tokens.next.identifier&&(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}));else for(advance(\"{\");;){if(\"}\"===state.tokens.next.value){advance(\"}\");break}var importName;if(\"default\"===state.tokens.next.type?(importName=\"default\",advance(\"default\")):importName=identifier(),\"as\"===state.tokens.next.value&&(advance(\"as\"),importName=identifier()),state.funct[\"(scope)\"].addlabel(importName,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return advance(\"from\"),advance(\"(string)\"),this}).exps=!0,stmt(\"export\",function(){var token,identifier,ok=!0;if(state.inES6()||(warning(\"W119\",state.tokens.curr,\"export\",\"6\"),ok=!1),state.funct[\"(scope)\"].block.isGlobal()||(error(\"E053\",state.tokens.curr),ok=!1),\"*\"===state.tokens.next.value)return advance(\"*\"),advance(\"from\"),advance(\"(string)\"),this;if(\"default\"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance(\"default\");var exportType=state.tokens.next.id;return(\"function\"===exportType||\"class\"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct[\"(scope)\"].addlabel(identifier,{type:exportType,token:token}),state.funct[\"(scope)\"].setExported(identifier,token)),this}if(\"{\"===state.tokens.next.value){advance(\"{\");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),\"as\"===state.tokens.next.value&&(advance(\"as\"),state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance()),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return\"from\"===state.tokens.next.value?(advance(\"from\"),advance(\"(string)\")):ok&&exportedTokens.forEach(function(token){state.funct[\"(scope)\"].setExported(token.value,token)}),this}if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud({inexport:!0});else if(\"let\"===state.tokens.next.id)advance(\"let\"),state.tokens.curr.fud({inexport:!0});else if(\"const\"===state.tokens.next.id)advance(\"const\"),state.tokens.curr.fud({inexport:!0});else if(\"function\"===state.tokens.next.id)this.block=!0,advance(\"function\"),state.syntax[\"function\"].fud({inexport:!0});else if(\"class\"===state.tokens.next.id){this.block=!0,advance(\"class\");var classNameToken=state.tokens.next;state.syntax[\"class\"].fud(),state.funct[\"(scope)\"].setExported(classNameToken.value,classNameToken)}else error(\"E024\",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord(\"abstract\"),FutureReservedWord(\"boolean\"),FutureReservedWord(\"byte\"),FutureReservedWord(\"char\"),FutureReservedWord(\"class\",{es5:!0,nud:classdef}),FutureReservedWord(\"double\"),FutureReservedWord(\"enum\",{es5:!0}),FutureReservedWord(\"export\",{es5:!0}),FutureReservedWord(\"extends\",{es5:!0}),FutureReservedWord(\"final\"),FutureReservedWord(\"float\"),FutureReservedWord(\"goto\"),FutureReservedWord(\"implements\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"import\",{es5:!0}),FutureReservedWord(\"int\"),FutureReservedWord(\"interface\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"long\"),FutureReservedWord(\"native\"),FutureReservedWord(\"package\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"private\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"protected\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"public\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"short\"),FutureReservedWord(\"static\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"super\",{es5:!0}),FutureReservedWord(\"synchronized\"),FutureReservedWord(\"transient\"),FutureReservedWord(\"volatile\");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,[\"[\",\"{\"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,[\"[\",\"{\"])?bracketStack+=1:checkPunctuators(pn,[\"]\",\"}\"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&\"for\"===pn.value&&!checkPunctuator(prev,\".\")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,[\"}\",\"]\"])){if(\"=\"===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if(\".\"===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,\";\")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&\"(end)\"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode=\"use\",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning(\"W098\",v.token,v.raw_text||v.value),v.undef&&state.funct[\"(scope)\"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains([\"use\",\"define\",\"generate\",\"filter\"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&\"use\"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&\"define\"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&\"generate\"===_current.mode?(state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):_current&&\"filter\"===_current.mode?(use(v)&&state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||\"object\"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope=\"(main)\"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;\"-\"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],(\"esversion\"===optionKey&&5===o[optionKey]||\"es5\"===optionKey&&o[optionKey])&&warning(\"I003\"),\"newcap\"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj[\"(explicitNewcap)\"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on(\"warning\",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on(\"error\",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor(\"(global)\",null,{\"(global)\":!0,\"(scope)\":scopeManagerInst,\"(comparray)\":arrayComprehension(),\"(metrics)\":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt(\"E004\",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax[\"(begin)\"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+\"[\\\\s\\\\S]*?\"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,\"ig\"),s=s.replace(reIgnore,function(match){return match.replace(/./g,\" \")}))})),lex=new Lexer(s),lex.on(\"warning\",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"error\",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"fatal\",function(ev){quit(\"E041\",ev.line,ev.from)}),lex.on(\"Identifier\",function(ev){emitter.emit(\"Identifier\",ev)}),lex.on(\"String\",function(ev){emitter.emit(\"String\",ev)}),lex.on(\"Number\",function(ev){emitter.emit(\"Number\",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case\"{\":case\"[\":destructuringAssignOrJsonValue();break;default:directives(),state.directive[\"use strict\"]&&\"global\"!==state.option.strict&&warning(\"W097\",state.tokens.prev),statements()}\"(end)\"!==state.tokens.next.id&&quit(\"E041\",state.tokens.curr.line),state.funct[\"(scope)\"].unstack()}catch(err){if(!err||\"JSHintError\"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:\"(main)\",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if(\"(main)\"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct[\"(scope)\"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct[\"(scope)\"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f[\"(name)\"],fu.param=f[\"(params)\"],fu.line=f[\"(line)\"],fu.character=f[\"(character)\"],fu.last=f[\"(last)\"],fu.lastcharacter=f[\"(lastcharacter)\"],fu.metrics={complexity:f[\"(metrics)\"].ComplexityCount,parameters:f[\"(metrics)\"].arity,statements:f[\"(metrics)\"].statementCount},data.functions.push(fu)}var unuseds=state.funct[\"(scope)\"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if(\"number\"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();\"object\"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./lex.js\":\"/node_modules/jshint/src/lex.js\",\"./messages.js\":\"/node_modules/jshint/src/messages.js\",\"./options.js\":\"/node_modules/jshint/src/options.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./scope-manager.js\":\"/node_modules/jshint/src/scope-manager.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",\"./style.js\":\"/node_modules/jshint/src/style.js\",\"./vars.js\":\"/node_modules/jshint/src/vars.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/lex.js\":[function(_dereq_,module,exports){\"use strict\";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;\"string\"==typeof lines&&(lines=lines.replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\").split(\"\\n\")),lines[0]&&\"#!\"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf(\"node\")&&(state.option.node=!0),lines[0]=\"\"),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input=\"\",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=\" \";this.ignoreLinterErrors=!1}var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,unicodeData=_dereq_(\"../data/ascii-identifier-data.js\"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(\" \").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case\".\":if(/^[0-9]$/.test(this.peek(1)))return null;if(\".\"===this.peek(1)&&\".\"===this.peek(2))return{type:Token.Punctuator,value:\"...\"};case\"(\":case\")\":case\";\":case\",\":case\"[\":case\"]\":case\":\":case\"~\":case\"?\":return{type:Token.Punctuator,value:ch1};case\"{\":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case\"}\":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case\"#\":return{type:Token.Punctuator,value:ch1};case\"\":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),\">\"===ch1&&\">\"===ch2&&\">\"===ch3&&\"=\"===ch4?{type:Token.Punctuator,value:\">>>=\"}:\"=\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"===\"}:\"!\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"!==\"}:\">\"===ch1&&\">\"===ch2&&\">\"===ch3?{type:Token.Punctuator,value:\">>>\"}:\"<\"===ch1&&\"<\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"<<=\"}:\">\"===ch1&&\">\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\">>=\"}:\"=\"===ch1&&\">\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&\"+-<>&|\".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:\"<>=!+-*%&|^\".indexOf(ch1)>=0?\"=\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:\"/\"===ch1?\"=\"===ch2?{type:Token.Punctuator,value:\"/=\"}:{type:Token.Punctuator,value:\"/\"}:null},scanComments:function(){function commentToken(label,body,opt){var special=[\"jshint\",\"jslint\",\"members\",\"member\",\"globals\",\"global\",\"exported\"],isSpecial=!1,value=label+body,commentType=\"plain\";return opt=opt||{},opt.isMultiline&&(value+=\"*/\"),body=body.replace(/\\n/g,\" \"),\"/*\"===label&®.fallsThrough.test(body)&&(isSpecial=!0,commentType=\"falls through\"),special.forEach(function(str){if(!isSpecial&&(\"//\"!==label||\"jshint\"===str)&&(\" \"===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||\" \"!==body.charAt(0)||\" \"!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+\" \"+str,body=body.substr(str.length+1)),isSpecial))switch(str){case\"member\":commentType=\"members\";break;case\"global\":commentType=\"globals\";break;default:var options=body.split(\":\").map(function(v){return v.replace(/^\\s+/,\"\").replace(/\\s+$/,\"\")});if(2===options.length)switch(options[0]){case\"ignore\":switch(options[1]){case\"start\":self.ignoringLinterErrors=!0,isSpecial=!1;break;case\"end\":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if(\"*\"===ch1&&\"/\"===ch2)return this.trigger(\"error\",{code:\"E018\",line:startLine,character:startChar}),this.skip(2),null;if(\"/\"!==ch1||\"*\"!==ch2&&\"/\"!==ch2)return null;if(\"/\"===ch2)return this.skip(this.input.length),commentToken(\"//\",rest);var body=\"\";if(\"*\"===ch2){for(this.inComment=!0,this.skip(2);\"*\"!==this.peek()||\"/\"!==this.peek(1);)if(\"\"===this.peek()){if(body+=\"\\n\",!this.nextLine())return this.trigger(\"error\",{code:\"E017\",line:startLine,character:startChar}),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=[\"if\",\"in\",\"do\",\"var\",\"for\",\"new\",\"try\",\"let\",\"this\",\"else\",\"case\",\"void\",\"with\",\"enum\",\"while\",\"break\",\"catch\",\"throw\",\"const\",\"yield\",\"class\",\"super\",\"return\",\"typeof\",\"delete\",\"switch\",\"export\",\"import\",\"default\",\"finally\",\"extends\",\"function\",\"continue\",\"debugger\",\"instanceof\"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id=\"\",index=0,readUnicodeEscapeSequence=function(){if(index+=1,\"u\"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,\"\\\\u\"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case\"true\":case\"false\":type=Token.BooleanLiteral;break;case\"null\":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return\"$\"===ch||\"_\"===ch||\"\\\\\"===ch||ch>=\"a\"&&\"z\">=ch||ch>=\"A\"&&\"Z\">=ch}var bad,index=0,value=\"\",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if(\".\"!==char&&!isDecimalDigit(char))return null;if(\".\"!==char){for(value=this.peek(index),index+=1,char=this.peek(index),\"0\"===value&&((\"x\"===char||\"X\"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),(\"o\"===char||\"O\"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Octal integer literal\",\"6\"]}),index+=1,value+=char),(\"b\"===char||\"B\"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Binary integer literal\",\"6\"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if(\".\"===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if(\"e\"===char||\"E\"===char){if(value+=char,index+=1,char=this.peek(index),(\"+\"===char||\"-\"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case\"'\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\'\"]},checks,function(){return state.jsonMode});break;case\"b\":char=\"\\\\b\";break;case\"f\":char=\"\\\\f\";break;case\"n\":char=\"\\\\n\";break;case\"r\":char=\"\\\\r\";break;case\"t\":char=\"\\\\t\";break;case\"0\":char=\"\\\\0\";var n=parseInt(this.peek(1),10);this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case\"u\":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger(\"warning\",{code:\"W052\",line:this.line,character:this.char,data:[\"u\"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case\"v\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\v\"]},checks,function(){return state.jsonMode}),char=\"\u000b\";break;case\"x\":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\x-\"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case\"\\\\\":char=\"\\\\\\\\\";break;case'\"':char='\\\\\"';break;case\"/\":break;case\"\":allowNewLine=!0,char=\"\"}return{\"char\":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value=\"\",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if(\"`\"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,\"char\":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||\"}\"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;\"`\"!==this.peek();){for(;\"\"===(ch=this.peek());)if(value+=\"\\n\",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger(\"error\",{code:\"E052\",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if(\"$\"===ch&&\"{\"===this.peek(1))return value+=\"${\",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif(\"\\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else\"`\"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if('\"'!==quote&&\"'\"!==quote)return null;this.triggerAsync(\"warning\",{code:\"W108\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&'\"'!==quote});var value=\"\",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(\"\"===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync(\"warning\",{code:\"W043\",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync(\"warning\",{code:\"W042\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger(\"warning\",{code:\"W112\",line:this.line,character:this.char}),!this.nextLine())return this.trigger(\"error\",{code:\"E029\",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(\" \">char&&this.trigger(\"warning\",{code:\"W113\",line:this.line,character:this.char,data:[\"\"]}),\"\\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body=\"\",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){\" \">char&&(malformed=!0,this.trigger(\"warning\",{code:\"W048\",line:this.line,character:this.char})),\"<\"===char&&(malformed=!0,this.trigger(\"warning\",{code:\"W049\",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||\"/\"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)\"]\"===char&&(\"\\\\\"!==this.peek(index-1)||\"\\\\\"===this.peek(index-2))&&(isCharSet=!1),\"\\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if(\"\\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),\"/\"===char){index+=1;continue}if(\"[\"===char){index+=1;continue}}if(\"[\"!==char){if(\"/\"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger(\"error\",{code:\"E015\",line:this.line,character:this.from}),void this.trigger(\"fatal\",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(\"\"))}catch(err){malformed=!0,this.trigger(\"error\",{code:\"E016\",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith(\"/*\",\"//\")||this.inComment&&endsWith(\"*/\")||(this.input=\"\")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger(\"warning\",{code:\"W125\",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger(\"warning\",{code:\"W100\",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen=0;--i){var scopeLabels=_scopeStack[i][\"(labels)\"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(usages)\"][labelName])return current[\"(usages)\"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if(\"outer\"===state.option.shadow)for(var isGlobal=\"global\"===_currentFunctBody[\"(type)\"],isNewFunction=\"functionparams\"===_current[\"(type)\"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem[\"(labels)\"][labelName]&&warning(\"W123\",token,labelName),stackItem[\"(breakLabels)\"][labelName]&&warning(\"W123\",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&\"function\"===type||\"function\"!==type)&&warning(\"W003\",token,labelName)}var _current,_scopeStack=[];_newScope(\"global\"),_current[\"(predefined)\"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt=\"last-param\"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:[\"var\"],\"last-param\":[\"var\",\"param\"],strict:[\"var\",\"param\",\"last-param\"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning(\"W098\",{line:line,from:chr},raw_name),(unused_opt||\"var\"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0][\"(predefined)\"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||\"functionparams\"!==previousScope[\"(type)\"]||(_current[\"(isFuncBody)\"]=!0,_current[\"(context)\"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams=\"functionparams\"===_current[\"(type)\"],isUnstackingFunctionOuter=\"functionouter\"===_current[\"(type)\"],currentUsages=_current[\"(usages)\"],currentLabels=_current[\"(labels)\"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf(\"__proto__\")&&usedLabelNameList.push(\"__proto__\"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel[\"(type)\"];if(usedLabel[\"(useOutsideOfScope)\"]&&!state.option.funcscope){var usedTokens=usage[\"(tokens)\"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel[\"(function)\"]===usedTokens[j][\"(function)\"]&&error(\"W038\",usedTokens[j],usedLabelName)}if(_current[\"(labels)\"][usedLabelName][\"(unused)\"]=!1,\"const\"===usedLabelType&&usage[\"(modified)\"])for(j=0;usage[\"(modified)\"].length>j;j++)error(\"E013\",usage[\"(modified)\"][j],usedLabelName);if((\"function\"===usedLabelType||\"class\"===usedLabelType)&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)error(\"W021\",usage[\"(reassigned)\"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct[\"(isCapturing)\"]=!0),subScope)if(subScope[\"(usages)\"][usedLabelName]){var subScopeUsage=subScope[\"(usages)\"][usedLabelName];subScopeUsage[\"(modified)\"]=subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]),subScopeUsage[\"(tokens)\"]=subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]),subScopeUsage[\"(reassigned)\"]=subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]),subScopeUsage[\"(onlyUsedSubFunction)\"]=!1}else subScope[\"(usages)\"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"]=!0);else if(\"boolean\"==typeof _current[\"(predefined)\"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current[\"(predefined)\"][usedLabelName]===!1&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)warning(\"W020\",usage[\"(reassigned)\"][j])}else if(usage[\"(tokens)\"])for(j=0;usage[\"(tokens)\"].length>j;j++){var undefinedToken=usage[\"(tokens)\"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning(\"W117\",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],\"var\")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName][\"(blockscoped)\"]||\"exception\"===currentLabels[defLabelName][\"(type)\"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope[\"(labels)\"][defLabelName]=currentLabels[defLabelName],\"global\"!==_currentFunctBody[\"(type)\"]&&(subScope[\"(labels)\"][defLabelName][\"(useOutsideOfScope)\"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope[\"(isFuncBody)\"]||\"global\"===scope[\"(type)\"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||\"param\",\"exception\"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&\"exception\"!==previouslyDefinedLabelType&&(state.option.node||warning(\"W002\",state.tokens.next,labelName))}if(_.has(_current[\"(labels)\"],labelName)?_current[\"(labels)\"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":token,\"(unused)\":!0},_current[\"(params)\"].push(labelName)),_.has(_current[\"(usages)\"],labelName)){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}},validateParams:function(){if(\"global\"!==_currentFunctBody[\"(type)\"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody[\"(parent)\"];currentFunctParamScope[\"(params)\"]&¤tFunctParamScope[\"(params)\"].forEach(function(labelName){var label=currentFunctParamScope[\"(labels)\"][labelName];label&&label.duplicated&&(isStrict?warning(\"E011\",label[\"(token)\"],labelName):state.option.shadow!==!0&&warning(\"W004\",label[\"(token)\"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf(\"__proto__\")&&list.push(\"__proto__\"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return\"__proto__\"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName][\"(type)\"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0][\"(labels)\"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName][\"(unused)\"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope[\"(type)\"])break;if(_.has(scope[\"(labels)\"],labelName)&&!scope[\"(labels)\"][labelName][\"(blockscoped)\"])return scope[\"(labels)\"][labelName][\"(unused)\"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped=\"let\"===type||\"const\"===type||\"class\"===type,isexported=\"global\"===(isblockscoped?_current:_currentFunctBody)[\"(type)\"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current[\"(labels)\"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||\"global\"===_current[\"(type)\"]||(declaredInCurrentScope=!!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName]),!declaredInCurrentScope&&_current[\"(usages)\"][labelName]){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}declaredInCurrentScope?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning(\"W004\",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning(\"E011\",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&\"__proto__\"!==labelName&&\"global\"!==_currentFunctBody[\"(type)\"]&&warning(\"W004\",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),\"global\"===_currentFunctBody[\"(type)\"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current[\"(labels)\"][labelName]&&(!onlyBlockscoped||current[\"(labels)\"][labelName][\"(blockscoped)\"]))return current[\"(labels)\"][labelName][\"(type)\"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&\"functionparams\"===scopeCheck[\"(type)\"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(breakLabels)\"][labelName])return!0;if(\"functionparams\"===current[\"(type)\"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!1,\"(function)\":_currentFunctBody,\"(unused)\":unused}}},block:{isGlobal:function(){return\"global\"===_current[\"(type)\"]},use:function(labelName,token){var paramScope=_currentFunctBody[\"(parent)\"];paramScope&¶mScope[\"(labels)\"][labelName]&&\"param\"===paramScope[\"(labels)\"][labelName][\"(type)\"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope[\"(labels)\"][labelName][\"(unused)\"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token[\"(function)\"]=_currentFunctBody,_current[\"(usages)\"][labelName][\"(tokens)\"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current[\"(usages)\"][labelName][\"(reassigned)\"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current[\"(usages)\"][labelName][\"(modified)\"].push(token)},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!0,\"(unused)\":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning(\"W004\",token,labelName):_checkOuterShadow(labelName,token)),_current[\"(breakLabels)\"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{\"../lodash\":\"/node_modules/jshint/lodash.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/state.js\":[function(_dereq_,module,exports){\"use strict\";var NameStack=_dereq_(\"./name-stack.js\"),state={syntax:{},isStrict:function(){return this.directive[\"use strict\"]||this.inClassBody||this.option.module||\"implied\"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab=\"\",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{\"./name-stack.js\":\"/node_modules/jshint/src/name-stack.js\"}],\"/node_modules/jshint/src/style.js\":[function(_dereq_,module,exports){\"use strict\";exports.register=function(linter){linter.on(\"Identifier\",function(data){linter.getOption(\"proto\")||\"__proto__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name,\"6\"]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"iterator\")||\"__iterator__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"camelcase\")&&data.name.replace(/^_+|_+$/g,\"\").indexOf(\"_\")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn(\"W106\",{line:data.line,\"char\":data.from,data:[data.name]})}),linter.on(\"String\",function(data){var code,quotmark=linter.getOption(\"quotmark\");quotmark&&(\"single\"===quotmark&&\"'\"!==data.quote&&(code=\"W109\"),\"double\"===quotmark&&'\"'!==data.quote&&(code=\"W108\"),quotmark===!0&&(linter.getCache(\"quotmark\")||linter.setCache(\"quotmark\",data.quote),linter.getCache(\"quotmark\")!==data.quote&&(code=\"W110\")),code&&linter.warn(code,{line:data.line,\"char\":data.char}))}),linter.on(\"Number\",function(data){\".\"===data.value.charAt(0)&&linter.warn(\"W008\",{line:data.line,\"char\":data.char,data:[data.value]}),\".\"===data.value.substr(data.value.length-1)&&linter.warn(\"W047\",{line:data.line,\"char\":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn(\"W046\",{line:data.line,\"char\":data.char,data:[data.value]})}),linter.on(\"String\",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption(\"scripturl\")||re.test(data.value)&&linter.warn(\"W107\",{line:data.line,\"char\":data.char})})}},{}],\"/node_modules/jshint/src/vars.js\":[function(_dereq_,module,exports){\"use strict\";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,\"throws\":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},[\"/node_modules/jshint/src/jshint.js\"])}),ace.define(\"ace/mode/javascript_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\",\"ace/mode/javascript/jshint\"],function(acequire,exports,module){\"use strict\";function startRegex(arr){return RegExp(\"^(\"+arr.join(\"|\")+\")\")}var oop=acequire(\"../lib/oop\"),Mirror=acequire(\"../worker/mirror\").Mirror,lint=acequire(\"./javascript/jshint\").JSHINT,disabledWarningsRe=startRegex([\"Bad for in variable '(.+)'.\",'Missing \"use strict\"']),errorsRe=startRegex([\"Unexpected\",\"Expected \",\"Confusing (plus|minus)\",\"\\\\{a\\\\} unterminated regular expression\",\"Unclosed \",\"Unmatched \",\"Unbegun comment\",\"Bad invocation\",\"Missing space after\",\"Missing operator at\"]),infoRe=startRegex([\"Expected an assignment\",\"Bad escapement of EOL\",\"Unexpected comma\",\"Unexpected space\",\"Missing radix parameter.\",\"A leading decimal point can\",\"\\\\['{a}'\\\\] is better written in dot notation.\",\"'{a}' used out of scope\"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval(\"throw 0;\"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,\"\\n\"),!value)return this.sender.emit(\"annotate\",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?\"warning\":\"error\";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type=\"warning\";if(\"Missing semicolon.\"==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),\"error\"==maxErrorLevel&&str&&/[\\w\\d{(['\"]/.test(str)?(error.reason='Missing \";\" before statement',type=\"error\"):type=\"info\"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type=\"info\":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):\"'{a}' is not defined.\"==raw?type=\"warning\":\"'{a}' is defined but never used.\"==raw&&(type=\"info\")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit(\"annotate\",errors)}}.call(JavaScriptWorker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);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__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||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: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r   ᠎              \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});"; - /***/ }), /* 44 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Aliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return GlobalAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return printAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return parseAliasDeclaration; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return removeAlias; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return substituteAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadGlobalAliases; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Terminal_js__ = __webpack_require__(23); - - -let Aliases = {}; -let GlobalAliases = {}; - -function loadAliases(saveString) { - if (saveString === "") { - Aliases = {}; - } else { - Aliases = JSON.parse(saveString); - } -} - -function loadGlobalAliases(saveString) { - if (saveString === "") { - GlobalAliases = {}; - } else { - GlobalAliases = JSON.parse(saveString); - } -} - -//Print all aliases to terminal -function printAliases() { - for (var name in Aliases) { - if (Aliases.hasOwnProperty(name)) { - Object(__WEBPACK_IMPORTED_MODULE_0__Terminal_js__["b" /* post */])("alias " + name + "=" + Aliases[name]); - } - } - for (var name in GlobalAliases) { - if (GlobalAliases.hasOwnProperty(name)) { - Object(__WEBPACK_IMPORTED_MODULE_0__Terminal_js__["b" /* post */])("global alias " + name + "=" + GlobalAliases[name]); - } - } -} - -//True if successful, false otherwise -function parseAliasDeclaration(dec,global=false) { - var re = /^([_|\w|!|%|,|@]+)="(.+)"$/; - var matches = dec.match(re); - if (matches == null || matches.length != 3) {return false;} - if (global){ - addGlobalAlias(matches[1],matches[2]); - } else { - addAlias(matches[1], matches[2]); - } - return true; -} - -function addAlias(name, value) { - if (name in GlobalAliases){ - delete GlobalAliases[name]; - } - Aliases[name] = value; -} - -function addGlobalAlias(name, value) { - if (name in Aliases){ - delete Aliases[name]; - } - GlobalAliases[name] = value; -} - -function getAlias(name) { - if (Aliases.hasOwnProperty(name)) { - return Aliases[name]; - } - return null; -} - -function getGlobalAlias(name) { - if (GlobalAliases.hasOwnProperty(name)) { - return GlobalAliases[name]; - } - return null; -} - -function removeAlias(name) { - if (Aliases.hasOwnProperty(name)) { - delete Aliases[name]; - return true; - } - if (GlobalAliases.hasOwnProperty(name)) { - delete GlobalAliases[name]; - return true; - } - return false; -} - -//Returns the original string with any aliases substituted in -//Aliases only applied to "whole words", one level deep -function substituteAliases(origCommand) { - var commandArray = origCommand.split(" "); - if (commandArray.length>0){ - var alias = getAlias(commandArray[0]); - if (alias != null) { - commandArray[0] = alias; - } else { - var alias = getGlobalAlias(commandArray[0]); - if (alias != null) { - commandArray[0] = alias; - } - } - for (var i = 0; i < commandArray.length; ++i) { - var alias = getGlobalAlias(commandArray[i]); - if (alias != null) { - commandArray[i] = alias; - } - } - } - return commandArray.join(" "); -} - - - - -/***/ }), -/* 45 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return checkIfConnectedToDarkweb; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return executeDarkwebTerminalCommand; }); @@ -42275,11 +42146,11 @@ function substituteAliases(origCommand) { /* unused harmony export buyDarkwebItem */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return parseDarkwebItemPrice; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DarkWebItems; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__ = __webpack_require__(15); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__ = __webpack_require__(14); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__SpecialServerIps_js__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Terminal_js__ = __webpack_require__(23); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_IPAddress_js__ = __webpack_require__(17); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_IPAddress_js__ = __webpack_require__(18); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__ = __webpack_require__(4); @@ -42479,6 +42350,135 @@ let DarkWebItems = { +/***/ }), +/* 45 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Aliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return GlobalAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return printAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return parseAliasDeclaration; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return removeAlias; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return substituteAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadGlobalAliases; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Terminal_js__ = __webpack_require__(23); + + +let Aliases = {}; +let GlobalAliases = {}; + +function loadAliases(saveString) { + if (saveString === "") { + Aliases = {}; + } else { + Aliases = JSON.parse(saveString); + } +} + +function loadGlobalAliases(saveString) { + if (saveString === "") { + GlobalAliases = {}; + } else { + GlobalAliases = JSON.parse(saveString); + } +} + +//Print all aliases to terminal +function printAliases() { + for (var name in Aliases) { + if (Aliases.hasOwnProperty(name)) { + Object(__WEBPACK_IMPORTED_MODULE_0__Terminal_js__["b" /* post */])("alias " + name + "=" + Aliases[name]); + } + } + for (var name in GlobalAliases) { + if (GlobalAliases.hasOwnProperty(name)) { + Object(__WEBPACK_IMPORTED_MODULE_0__Terminal_js__["b" /* post */])("global alias " + name + "=" + GlobalAliases[name]); + } + } +} + +//True if successful, false otherwise +function parseAliasDeclaration(dec,global=false) { + var re = /^([_|\w|!|%|,|@]+)="(.+)"$/; + var matches = dec.match(re); + if (matches == null || matches.length != 3) {return false;} + if (global){ + addGlobalAlias(matches[1],matches[2]); + } else { + addAlias(matches[1], matches[2]); + } + return true; +} + +function addAlias(name, value) { + if (name in GlobalAliases){ + delete GlobalAliases[name]; + } + Aliases[name] = value; +} + +function addGlobalAlias(name, value) { + if (name in Aliases){ + delete Aliases[name]; + } + GlobalAliases[name] = value; +} + +function getAlias(name) { + if (Aliases.hasOwnProperty(name)) { + return Aliases[name]; + } + return null; +} + +function getGlobalAlias(name) { + if (GlobalAliases.hasOwnProperty(name)) { + return GlobalAliases[name]; + } + return null; +} + +function removeAlias(name) { + if (Aliases.hasOwnProperty(name)) { + delete Aliases[name]; + return true; + } + if (GlobalAliases.hasOwnProperty(name)) { + delete GlobalAliases[name]; + return true; + } + return false; +} + +//Returns the original string with any aliases substituted in +//Aliases only applied to "whole words", one level deep +function substituteAliases(origCommand) { + var commandArray = origCommand.split(" "); + if (commandArray.length>0){ + var alias = getAlias(commandArray[0]); + if (alias != null) { + commandArray[0] = alias; + } else { + var alias = getGlobalAlias(commandArray[0]); + if (alias != null) { + commandArray[0] = alias; + } + } + for (var i = 0; i < commandArray.length; ++i) { + var alias = getGlobalAlias(commandArray[i]); + if (alias != null) { + commandArray[i] = alias; + } + } + } + return commandArray.join(" "); +} + + + + /***/ }), /* 46 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -46733,6 +46733,146 @@ function createTextFile(fn, txt, server) { /* 50 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FactionInfo; }); +//Contains the "information" property for all the Factions, which is just a description +//of each faction +let FactionInfo = { + //Endgame + IlluminatiInfo: "Humanity never changes. No matter how civilized society becomes, it will eventually fall back " + + "into chaos. And from this chaos, we are the Invisible hand that guides them to order. ", + + DaedalusInfo: "Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.", + + CovenantInfo: "Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " + + "Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.

" + + "Only then can you discover immortality.", + + //Megacorporations, each forms its own faction + ECorpInfo: "ECorp's mission is simple: to connect the world of today with the technology of tomorrow. " + + "With our wide range of Internet-related software and commercial hardware, ECorp makes the world's " + + "information universally accessible.", + + MegaCorpInfo: "MegaCorp does things that others don't. We imagine. We create. We invent. We build things that " + + "others have never even dreamed of. Our work fills the world's needs for food, water, power, and " + + "transporation on an unprecendented scale, in ways that no other company can.

" + + "In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.", + + BachmanAndAssociatesInfo: "Where Law and Business meet - thats where we are.

" + + "Legal Insight - Business Instinct - Experience Innovation", + + BladeIndustriesInfo: "Augmentation is salvation", + + NWOInfo: "The human being created civilization not because of willingness but of a need to be assimilated into higher orders of structure and meaning.", + + ClarkeIncorporatedInfo: "Unlocking the power of the genome", + + OmniTekIncorporatedInfo: "Simply put, our mission is to design and build robots that make a difference", + + FourSigmaInfo: "The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven by " + + "deep learning and innovative ideas. And improved by iteration. That's Four Sigma.", + + KuaiGongInternationalInfo: "Dream big. Work hard. Make history.", + + //Other Corporations + FulcrumSecretTechnologiesInfo: "TODO", + + //Hacker groups + BitRunnersInfo: "Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. "+ + "It's all transformed into bits, stored in bits, communicated through bits. It’s impossible for any person " + + "to move, to live, to operate at any level without the use of bits. " + + "And when a person moves, lives, and operates, they leave behind their bits, mere traces of seemingly " + + "meaningless fragments of information. But these bits can be reconstructed. Transformed. Used.

" + + "Those who run the bits, run the world", + + + BlackHandInfo: "The world, so afraid of strong government, now has no government. Only power - Digital power. Financial power. " + + "Technological power. " + + "And those at the top rule with an invisible hand. They built a society where the rich get richer, " + + "and everyone else suffers.

" + + "So much pain. So many lives. Their darkness must end.", + + NiteSecInfo: +" __..__
" + +" _.nITESECNIt.
" + +" .-'NITESECNITESEc.
" + +" .' NITESECNITESECn
" + +" / NITESECNITESEC;
" + +" : :NITESECNITESEC;
" + +" ; $ NITESECNITESECN
" + +" : _, ,N'ITESECNITESEC
" + +" : .+^^`, : `NITESECNIT
" + +" ) /), `-,-=,NITESECNI
" + +" / ^ ,-;|NITESECN;
" + +" / _.' '-';NITESECN
" + +" ( , ,-''`^NITE'
" + +" )` :`. .'
" + +" )-- ; `- /
" + +" \' _.-' :
" + +" ( _.-' \. \
" + +" \------. \ \
" + +" \. \ \
" + +" \ _.nIt
" + +" \ _.nITESECNi
" + +" nITESECNIT^' \
" + +" NITE^' ___ \
" + +" / .gP''''Tp. \
" + +" : d' . `b \
" + +" ; d' o `b ;
" + +" / d; `b|
" + +" /, $; @ `:
" + +" /' $$ ;
" + +" .' $$b o |
" + +" .' d$$$; :
" + +" / .d$$$$; , ;
" + +" d .dNITESEC $ |
" + +" :bp.__.gNITESEC$$ :$ ;
" + +" NITESECNITESECNIT $$b :
", + + //City factions, essentially governments + ChongqingInfo: "Serve the people", + Sector12Info: "The City of the Future", + HongKongInfo: "Asia's World City", + AevumInfo: "The Silicon City", + IshimaInfo: "The East Asian Order of the Future", + VolhavenInfo: "Benefit, Honour, and Glory", + + //Criminal Organizations/Gangs + SpeakersForTheDeadInfo: "It is better to reign in hell than to serve in heaven.", + + DarkArmyInfo: "The World doesn't care about right or wrong. It's all about power.", + + TheSyndicateInfo: "Honor holds you back", + + SilhouetteInfo: "Corporations have filled the void of power left behind by the collapse of Western government. The issue is they've become so big " + + "that you don't know who they're working for. And if you're employed at one of these corporations, you don't even know who you're working " + + "for.

" + + "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.", + + TetradsInfo: "Following the Mandate of Heaven and Carrying out the Way", + + SlumSnakesInfo: "Slum Snakes rule!", + + //Earlygame factions - factions the player will prestige with early on that don't + //belong in other categories + NetburnersInfo: "~~//*>H4CK|\|3T 8URN3R5**>?>\\~~", + + TianDiHuiInfo: "Obey Heaven and Work Righteousness", + + CyberSecInfo: "The Internet is the first thing that humanity has built that humanity doesn’t understand, " + + "the largest experiment in anarchy that we have ever had. And as the world becomes increasingly " + + "dominated by the internet, society approaches the brink of total chaos. " + + "We serve only to protect society, to protect humanity, to protect the world from its imminent collapse.", + +} + + + + +/***/ }), +/* 51 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return beginInfiltration; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(7); @@ -46741,7 +46881,7 @@ function createTextFile(fn, txt, server) { /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__ = __webpack_require__(2); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_InfiltrationBox_js__ = __webpack_require__(51); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_InfiltrationBox_js__ = __webpack_require__(52); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__ = __webpack_require__(4); @@ -47569,14 +47709,14 @@ function getInfiltrationEscapeChance(inst) { /***/ }), -/* 51 */ +/* 52 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return infiltrationBoxCreate; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_BitNode_js__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_Faction_js__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_Faction_js__ = __webpack_require__(11); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__src_Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__HelperFunctions_js__ = __webpack_require__(2); @@ -47695,139 +47835,30596 @@ function infiltrationBoxCreate(inst) { /***/ }), -/* 52 */ +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +/* ***** BEGIN LICENSE BLOCK ***** + * Distributed under the BSD license: + * + * Copyright (c) 2010, Ajax.org B.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Ajax.org B.V. nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ***** END LICENSE BLOCK ***** */ + +/** + * Define a module along with a payload + * @param module a name for the payload + * @param payload a function to call with (acequire, exports, module) params + */ + +(function() { + +var ACE_NAMESPACE = "ace"; + +var global = (function() { return this; })(); +if (!global && typeof window != "undefined") global = window; // strict mode + + +if (!ACE_NAMESPACE && typeof acequirejs !== "undefined") + return; + + +var define = function(module, deps, payload) { + if (typeof module !== "string") { + if (define.original) + define.original.apply(this, arguments); + else { + console.error("dropping module because define wasn\'t a string."); + console.trace(); + } + return; + } + if (arguments.length == 2) + payload = deps; + if (!define.modules[module]) { + define.payloads[module] = payload; + define.modules[module] = null; + } +}; + +define.modules = {}; +define.payloads = {}; + +/** + * Get at functionality define()ed using the function above + */ +var _acequire = function(parentId, module, callback) { + if (typeof module === "string") { + var payload = lookup(parentId, module); + if (payload != undefined) { + callback && callback(); + return payload; + } + } else 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 == undefined && acequire.original) + return; + params.push(dep); + } + return callback && callback.apply(null, params) || true; + } +}; + +var acequire = function(module, callback) { + var packagedModule = _acequire("", module, callback); + if (packagedModule == undefined && acequire.original) + return acequire.original.apply(this, arguments); + return packagedModule; +}; + +var normalizeModule = function(parentId, moduleName) { + // normalize plugin acequires + if (moduleName.indexOf("!") !== -1) { + var chunks = moduleName.split("!"); + return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); + } + // normalize relative acequires + 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; +}; + +/** + * Internal function to lookup moduleNames and resolve them by calling the + * definition function if needed. + */ +var lookup = function(parentId, moduleName) { + moduleName = normalizeModule(parentId, moduleName); + + var module = define.modules[moduleName]; + if (!module) { + module = define.payloads[moduleName]; + if (typeof module === 'function') { + var exports = {}; + var mod = { + id: moduleName, + uri: '', + exports: exports, + packaged: true + }; + + var req = function(module, callback) { + return _acequire(moduleName, module, callback); + }; + + var returnValue = module(req, exports, mod); + exports = returnValue || mod.exports; + define.modules[moduleName] = exports; + delete define.payloads[moduleName]; + } + module = define.modules[moduleName] = exports || module; + } + return module; +}; + +function exportAce(ns) { + var root = global; + if (ns) { + if (!global[ns]) + global[ns] = {}; + root = global[ns]; + } + + if (!root.define || !root.define.packaged) { + define.original = root.define; + root.define = define; + root.define.packaged = true; + } + + if (!root.acequire || !root.acequire.packaged) { + acequire.original = root.acequire; + root.acequire = acequire; + root.acequire.packaged = true; + } +} + +exportAce(ACE_NAMESPACE); + +})(); + +ace.define("ace/lib/regexp",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + + 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; + RegExp.prototype.exec = function (str) { + var match = real.exec.apply(this, arguments), + name, r2; + if ( typeof(str) == 'string' && match) { + if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { + r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); + 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; + } + }); + } + 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]; + } + } + if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + } + return match; + }; + if (!compliantLastIndexIncrement) { + RegExp.prototype.test = function (str) { + var match = real.exec.call(this, str); + if (match && this.global && !match[0].length && (this.lastIndex > match.index)) + this.lastIndex--; + return !!match; + }; + } + + 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; + } + +}); + +ace.define("ace/lib/es5-shim",["require","exports","module"], function(acequire, exports, module) { + +function Empty() {} + +if (!Function.prototype.bind) { + Function.prototype.bind = function bind(that) { // .length is 1 + var target = this; + if (typeof target != "function") { + throw new TypeError("Function.prototype.bind called on incompatible " + target); + } + var args = slice.call(arguments, 1); // for normal call + var bound = function () { + + if (this instanceof bound) { + + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + + } + + }; + if(target.prototype) { + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + return bound; + }; +} +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); +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__); +} +if ([1,2].splice(0).length != 2) { + if(function() { // test IE < 9 to splice bug - see issue #138 + function makeArray(l) { + var a = new Array(l+2); + a[0] = a[1] = 0; + return a; + } + var array = [], lengthBefore; + + array.splice.apply(array, makeArray(20)); + array.splice.apply(array, makeArray(26)); + + lengthBefore = array.length; //46 + array.splice(5, 0, "XXX"); // add one element + + lengthBefore + 1 == array.length + + if (lengthBefore + 1 == array.length) { + return true;// has right splice implementation without bugs + } + }()) {//IE 6/7 + var array_splice = Array.prototype.splice; + Array.prototype.splice = function(start, deleteCount) { + if (!arguments.length) { + return []; + } else { + return array_splice.apply(this, [ + start === void 0 ? 0 : start, + deleteCount === void 0 ? (this.length - start) : deleteCount + ].concat(slice.call(arguments, 2))) + } + }; + } else {//IE8 + Array.prototype.splice = function(pos, removeCount){ + var length = this.length; + if (pos > 0) { + if (pos > length) + pos = length; + } else if (pos == void 0) { + pos = 0; + } else if (pos < 0) { + pos = Math.max(length + pos, 0); + } + + if (!(pos+removeCount < length)) + removeCount = length - pos; + + var removed = this.slice(pos, pos+removeCount); + var insert = slice.call(arguments, 2); + var add = insert.length; + if (pos === length) { + if (add) { + this.push.apply(this, insert); + } + } else { + var remove = Math.min(removeCount, length - pos); + var tailOldPos = pos + remove; + var tailNewPos = tailOldPos + add - remove; + var tailCount = length - tailOldPos; + var lengthAfterRemove = length - remove; + + if (tailNewPos < tailOldPos) { // case A + for (var i = 0; i < tailCount; ++i) { + this[tailNewPos+i] = this[tailOldPos+i]; + } + } else if (tailNewPos > tailOldPos) { // case B + for (i = tailCount; i--; ) { + this[tailNewPos+i] = this[tailOldPos+i]; + } + } // else, add == remove (nothing to do) + + if (add && pos === lengthAfterRemove) { + this.length = lengthAfterRemove; // truncate array + this.push.apply(this, insert); + } else { + this.length = lengthAfterRemove + add; // reserves space + for (i = 0; i < add; ++i) { + this[pos+i] = insert[i]; + } + } + } + return removed; + }; + } +} +if (!Array.isArray) { + Array.isArray = function isArray(obj) { + return _toString(obj) == "[object Array]"; + }; +} +var boxedString = Object("a"), + splitString = boxedString[0] != "a" || !(0 in boxedString); + +if (!Array.prototype.forEach) { + Array.prototype.forEach = function forEach(fun /*, thisp*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + thisp = arguments[1], + i = -1, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(); // TODO message + } + + while (++i < length) { + if (i in self) { + fun.call(thisp, self[i], i, object); + } + } + }; +} +if (!Array.prototype.map) { + Array.prototype.map = function map(fun /*, thisp*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + result = Array(length), + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) + result[i] = fun.call(thisp, self[i], i, object); + } + return result; + }; +} +if (!Array.prototype.filter) { + Array.prototype.filter = function filter(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + result = [], + value, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self) { + value = self[i]; + if (fun.call(thisp, value, i, object)) { + result.push(value); + } + } + } + return result; + }; +} +if (!Array.prototype.every) { + Array.prototype.every = function every(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && !fun.call(thisp, self[i], i, object)) { + return false; + } + } + return true; + }; +} +if (!Array.prototype.some) { + Array.prototype.some = function some(fun /*, thisp */) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0, + thisp = arguments[1]; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + + for (var i = 0; i < length; i++) { + if (i in self && fun.call(thisp, self[i], i, object)) { + return true; + } + } + return false; + }; +} +if (!Array.prototype.reduce) { + Array.prototype.reduce = function reduce(fun /*, initial*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + if (!length && arguments.length == 1) { + throw new TypeError("reduce of empty array with no initial value"); + } + + var i = 0; + var result; + if (arguments.length >= 2) { + result = arguments[1]; + } else { + do { + if (i in self) { + result = self[i++]; + break; + } + if (++i >= length) { + throw new TypeError("reduce of empty array with no initial value"); + } + } while (true); + } + + for (; i < length; i++) { + if (i in self) { + result = fun.call(void 0, result, self[i], i, object); + } + } + + return result; + }; +} +if (!Array.prototype.reduceRight) { + Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { + var object = toObject(this), + self = splitString && _toString(this) == "[object String]" ? + this.split("") : + object, + length = self.length >>> 0; + if (_toString(fun) != "[object Function]") { + throw new TypeError(fun + " is not a function"); + } + if (!length && arguments.length == 1) { + throw new TypeError("reduceRight of empty array with no initial value"); + } + + var result, i = length - 1; + if (arguments.length >= 2) { + result = arguments[1]; + } else { + do { + if (i in self) { + result = self[i--]; + break; + } + if (--i < 0) { + throw new TypeError("reduceRight of empty array with no initial value"); + } + } while (true); + } + + do { + if (i in this) { + result = fun.call(void 0, result, self[i], i, object); + } + } while (i--); + + return result; + }; +} +if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { + Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { + var self = splitString && _toString(this) == "[object String]" ? + this.split("") : + toObject(this), + length = self.length >>> 0; + + if (!length) { + return -1; + } + + var i = 0; + if (arguments.length > 1) { + i = toInteger(arguments[1]); + } + i = i >= 0 ? i : Math.max(0, length + i); + for (; i < length; i++) { + if (i in self && self[i] === sought) { + return i; + } + } + return -1; + }; +} +if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { + Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { + var self = splitString && _toString(this) == "[object String]" ? + this.split("") : + 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])); + } + i = i >= 0 ? i : length - Math.abs(i); + for (; i >= 0; i--) { + if (i in self && sought === self[i]) { + return i; + } + } + return -1; + }; +} +if (!Object.getPrototypeOf) { + Object.getPrototypeOf = function getPrototypeOf(object) { + return object.__proto__ || ( + object.constructor ? + object.constructor.prototype : + prototypeOfObject + ); + }; +} +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 (!owns(object, property)) + return; + + var descriptor, getter, setter; + descriptor = { enumerable: true, configurable: true }; + if (supportsAccessors) { + var prototype = object.__proto__; + object.__proto__ = prototypeOfObject; + + var getter = lookupGetter(object, property); + var setter = lookupSetter(object, property); + object.__proto__ = prototype; + + if (getter || setter) { + if (getter) descriptor.get = getter; + if (setter) descriptor.set = setter; + return descriptor; + } + } + descriptor.value = object[property]; + return descriptor; + }; +} +if (!Object.getOwnPropertyNames) { + Object.getOwnPropertyNames = function getOwnPropertyNames(object) { + return Object.keys(object); + }; +} +if (!Object.create) { + var createEmpty; + if (Object.prototype.__proto__ === null) { + createEmpty = function () { + return { "__proto__": null }; + }; + } else { + createEmpty = function () { + var empty = {}; + for (var i in empty) + empty[i] = null; + empty.constructor = + empty.hasOwnProperty = + empty.propertyIsEnumerable = + empty.isPrototypeOf = + empty.toLocaleString = + empty.toString = + empty.valueOf = + empty.__proto__ = null; + return empty; + } + } + + Object.create = function create(prototype, properties) { + var object; + if (prototype === null) { + object = createEmpty(); + } else { + if (typeof prototype != "object") + throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); + var Type = function () {}; + Type.prototype = prototype; + object = new Type(); + object.__proto__ = prototype; + } + if (properties !== void 0) + Object.defineProperties(object, properties); + return object; + }; +} + +function doesDefinePropertyWork(object) { + try { + Object.defineProperty(object, "sentinel", {}); + return "sentinel" in object; + } catch (exception) { + } +} +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); + if (definePropertyFallback) { + try { + return definePropertyFallback.call(Object, object, property, descriptor); + } catch (exception) { + } + } + if (owns(descriptor, "value")) { + + if (supportsAccessors && (lookupGetter(object, property) || + lookupSetter(object, property))) + { + var prototype = object.__proto__; + object.__proto__ = prototypeOfObject; + delete object[property]; + object[property] = descriptor.value; + object.__proto__ = prototype; + } else { + object[property] = descriptor.value; + } + } else { + if (!supportsAccessors) + throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); + if (owns(descriptor, "get")) + defineGetter(object, property, descriptor.get); + if (owns(descriptor, "set")) + defineSetter(object, property, descriptor.set); + } + + return object; + }; +} +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; + }; +} +if (!Object.seal) { + Object.seal = function seal(object) { + return object; + }; +} +if (!Object.freeze) { + Object.freeze = function freeze(object) { + return object; + }; +} +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); +} +if (!Object.preventExtensions) { + Object.preventExtensions = function preventExtensions(object) { + return object; + }; +} +if (!Object.isSealed) { + Object.isSealed = function isSealed(object) { + return false; + }; +} +if (!Object.isFrozen) { + Object.isFrozen = function isFrozen(object) { + return false; + }; +} +if (!Object.isExtensible) { + Object.isExtensible = function isExtensible(object) { + if (Object(object) === object) { + throw new TypeError(); // TODO message + } + var name = ''; + while (owns(object, name)) { + name += '?'; + } + object[name] = true; + var returnValue = owns(object, name); + delete object[name]; + return returnValue; + }; +} +if (!Object.keys) { + 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; + }; + +} +if (!Date.now) { + Date.now = function now() { + return new Date().getTime(); + }; +} +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()) { + 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, ""); + }; +} + +function toInteger(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; +} + +function isPrimitive(input) { + var type = typeof input; + return ( + input === null || + type === "undefined" || + type === "boolean" || + type === "number" || + type === "string" + ); +} + +function toPrimitive(input) { + var val, valueOf, toString; + if (isPrimitive(input)) { + return input; + } + valueOf = input.valueOf; + if (typeof valueOf === "function") { + val = valueOf.call(input); + if (isPrimitive(val)) { + return val; + } + } + toString = input.toString; + if (typeof toString === "function") { + val = toString.call(input); + if (isPrimitive(val)) { + return val; + } + } + throw new TypeError(); +} +var toObject = function (o) { + if (o == null) { // this matches both null and undefined + throw new TypeError("can't convert "+o+" to object"); + } + return Object(o); +}; + +}); + +ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"], function(acequire, exports, module) { +"use strict"; + +acequire("./regexp"); +acequire("./es5-shim"); + +}); + +ace.define("ace/lib/dom",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var XHTML_NS = "http://www.w3.org/1999/xhtml"; + +exports.getDocumentHead = function(doc) { + if (!doc) + doc = document; + return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement; +} + +exports.createElement = function(tag, ns) { + return document.createElementNS ? + document.createElementNS(ns || XHTML_NS, tag) : + document.createElement(tag); +}; + +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 (id && exports.hasCssString(id, doc)) + return null; + + var style; + + if (id) + cssText += "\n/*# sourceURL=ace/css/" + id + " */"; + + if (doc.createStyleSheet) { + style = doc.createStyleSheet(); + style.cssText = cssText; + if (id) + style.owningElement.id = id; + } else { + style = exports.createElement("style"); + style.appendChild(doc.createTextNode(cssText)); + if (id) + style.id = id; + + exports.getDocumentHead(doc).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; + + exports.getDocumentHead(doc).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 + ); +}; + +exports.scrollbarWidth = function(document) { + var inner = exports.createElement("ace_inner"); + inner.style.width = "100%"; + inner.style.minWidth = "0px"; + inner.style.height = "200px"; + inner.style.display = "block"; + + var outer = exports.createElement("ace_outer"); + var style = outer.style; + + style.position = "absolute"; + style.left = "-10000px"; + style.overflow = "hidden"; + style.width = "200px"; + style.minWidth = "0px"; + style.height = "150px"; + style.display = "block"; + + outer.appendChild(inner); + + var 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; +}; + +if (typeof document == "undefined") { + exports.importCssString = function() {}; + return; +} + +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.setInnerHtml = function(el, innerHtml) { + var element = el.cloneNode(false);//document.createElement("div"); + element.innerHTML = innerHtml; + el.parentNode.replaceChild(element, el); + return element; +}; + +if ("textContent" in document.documentElement) { + exports.setInnerText = function(el, innerText) { + el.textContent = innerText; + }; + + exports.getInnerText = function(el) { + return el.textContent; + }; +} +else { + exports.setInnerText = function(el, innerText) { + el.innerText = innerText; + }; + + exports.getInnerText = function(el) { + return el.innerText; + }; +} + +exports.getParentWindow = function(document) { + return document.defaultView || document.parentWindow; +}; + +}); + +ace.define("ace/lib/oop",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.inherits = function(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +}; + +exports.mixin = function(obj, mixin) { + for (var key in mixin) { + obj[key] = mixin[key]; + } + return obj; +}; + +exports.implement = function(proto, mixin) { + exports.mixin(proto, mixin); +}; + +}); + +ace.define("ace/lib/keys",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +acequire("./fixoldbrowsers"); + +var oop = acequire("./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, + "super": 8, "meta": 8, "command": 8, "cmd": 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", + '-13': "NumpadEnter", + 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: '.', + 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', + 219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*' + } + }; + var name, i; + for (i in ret.FUNCTION_KEYS) { + name = ret.FUNCTION_KEYS[i].toLowerCase(); + ret[name] = parseInt(i, 10); + } + for (i in ret.PRINTABLE_KEYS) { + name = ret.PRINTABLE_KEYS[i].toLowerCase(); + ret[name] = parseInt(i, 10); + } + oop.mixin(ret, ret.MODIFIER_KEYS); + oop.mixin(ret, ret.PRINTABLE_KEYS); + oop.mixin(ret, ret.FUNCTION_KEYS); + ret.enter = ret["return"]; + ret.escape = ret.esc; + ret.del = ret["delete"]; + ret[173] = '-'; + + (function() { + var mods = ["cmd", "ctrl", "alt", "shift"]; + for (var i = Math.pow(2, mods.length); i--;) { + ret.KEY_MODS[i] = mods.filter(function(x) { + return i & ret.KEY_MODS[x]; + }).join("-") + "-"; + } + })(); + + ret.KEY_MODS[0] = ""; + ret.KEY_MODS[-1] = "input-"; + + return ret; +})(); +oop.mixin(exports, Keys); + +exports.keyCodeToString = function(keyCode) { + var keyString = Keys[keyCode]; + if (typeof keyString != "string") + keyString = String.fromCharCode(keyCode); + return keyString.toLowerCase(); +}; + +}); + +ace.define("ace/lib/useragent",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +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; + } +}; +if (typeof navigator != "object") + return; + +var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); +var ua = navigator.userAgent; +exports.isWin = (os == "win"); +exports.isMac = (os == "mac"); +exports.isLinux = (os == "linux"); +exports.isIE = + (navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0) + ? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]) + : parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie + +exports.isOldIE = exports.isIE && exports.isIE < 9; +exports.isGecko = exports.isMozilla = (window.Controllers || window.controllers) && window.navigator.product === "Gecko"; +exports.isOldGecko = exports.isGecko && parseInt((ua.match(/rv:(\d+)/)||[])[1], 10) < 4; +exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; +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.isChromeOS = ua.indexOf(" CrOS ") >= 0; + +}); + +ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var keys = acequire("./keys"); +var useragent = acequire("./useragent"); + +var pressedKeys = null; +var ts = 0; + +exports.addListener = function(elem, type, callback) { + if (elem.addEventListener) { + return elem.addEventListener(type, callback, false); + } + if (elem.attachEvent) { + var wrapper = function() { + callback.call(elem, 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; + if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey))) + return 2; + if (e.preventDefault) { + return e.button; + } + else { + return {1:0, 2:2, 4:1}[e.button]; + } +}; + +exports.capture = function(el, eventHandler, releaseCaptureHandler) { + function onMouseUp(e) { + eventHandler && eventHandler(e); + releaseCaptureHandler && releaseCaptureHandler(e); + + exports.removeListener(document, "mousemove", eventHandler, true); + exports.removeListener(document, "mouseup", onMouseUp, true); + exports.removeListener(document, "dragstart", onMouseUp, true); + } + + exports.addListener(document, "mousemove", eventHandler, true); + exports.addListener(document, "mouseup", onMouseUp, true); + exports.addListener(document, "dragstart", onMouseUp, true); + + return onMouseUp; +}; + +exports.addTouchMoveListener = function (el, callback) { + if ("ontouchmove" in el) { + var startx, starty; + exports.addListener(el, "touchstart", function (e) { + var touchObj = e.changedTouches[0]; + startx = touchObj.clientX; + starty = touchObj.clientY; + }); + exports.addListener(el, "touchmove", function (e) { + var factor = 1, + touchObj = e.changedTouches[0]; + + e.wheelX = -(touchObj.clientX - startx) / factor; + e.wheelY = -(touchObj.clientY - starty) / factor; + + startx = touchObj.clientX; + starty = touchObj.clientY; + + callback(e); + }); + } +}; + +exports.addMouseWheelListener = function(el, callback) { + if ("onmousewheel" in el) { + exports.addListener(el, "mousewheel", function(e) { + var factor = 8; + if (e.wheelDeltaX !== undefined) { + e.wheelX = -e.wheelDeltaX / factor; + e.wheelY = -e.wheelDeltaY / factor; + } else { + e.wheelX = 0; + e.wheelY = -e.wheelDelta / factor; + } + callback(e); + }); + } else if ("onwheel" in el) { + exports.addListener(el, "wheel", function(e) { + var factor = 0.35; + switch (e.deltaMode) { + case e.DOM_DELTA_PIXEL: + e.wheelX = e.deltaX * factor || 0; + e.wheelY = e.deltaY * factor || 0; + break; + case e.DOM_DELTA_LINE: + case e.DOM_DELTA_PAGE: + e.wheelX = (e.deltaX || 0) * 5; + e.wheelY = (e.deltaY || 0) * 5; + break; + } + + callback(e); + }); + } else { + exports.addListener(el, "DOMMouseScroll", function(e) { + 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.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName) { + var clicks = 0; + var startX, startY, timer; + var eventNames = { + 2: "dblclick", + 3: "tripleclick", + 4: "quadclick" + }; + + function onMousedown(e) { + if (exports.getButton(e) !== 0) { + clicks = 0; + } else if (e.detail > 1) { + clicks++; + if (clicks > 4) + clicks = 1; + } else { + clicks = 1; + } + if (useragent.isIE) { + var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5; + if (!timer || isNewClick) + clicks = 1; + if (timer) + clearTimeout(timer); + timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); + + if (clicks == 1) { + startX = e.clientX; + startY = e.clientY; + } + } + + e._clicks = clicks; + + eventHandler[callbackName]("mousedown", e); + + if (clicks > 4) + clicks = 0; + else if (clicks > 1) + return eventHandler[callbackName](eventNames[clicks], e); + } + function onDblclick(e) { + clicks = 2; + if (timer) + clearTimeout(timer); + timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); + eventHandler[callbackName]("mousedown", e); + eventHandler[callbackName](eventNames[clicks], e); + } + if (!Array.isArray(elements)) + elements = [elements]; + elements.forEach(function(el) { + exports.addListener(el, "mousedown", onMousedown); + if (useragent.isOldIE) + exports.addListener(el, "dblclick", onDblclick); + }); +}; + +var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window) + ? function(e) { + return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0); + } + : function(e) { + return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0); + }; + +exports.getModifierString = function(e) { + return keys.KEY_MODS[getModifierHash(e)]; +}; + +function normalizeCommandKeys(callback, e, keyCode) { + var hashId = getModifierHash(e); + + if (!useragent.isMac && pressedKeys) { + if (e.getModifierState && (e.getModifierState("OS") || e.getModifierState("Win"))) + hashId |= 8; + if (pressedKeys.altGr) { + if ((3 & hashId) != 3) + pressedKeys.altGr = 0; + else + return; + } + if (keyCode === 18 || keyCode === 17) { + var location = "location" in e ? e.location : e.keyLocation; + if (keyCode === 17 && location === 1) { + if (pressedKeys[keyCode] == 1) + ts = e.timeStamp; + } else if (keyCode === 18 && hashId === 3 && location === 2) { + var dt = e.timeStamp - ts; + if (dt < 50) + pressedKeys.altGr = true; + } + } + } + + if (keyCode in keys.MODIFIER_KEYS) { + keyCode = -1; + } + if (hashId & 8 && (keyCode >= 91 && keyCode <= 93)) { + keyCode = -1; + } + + if (!hashId && keyCode === 13) { + var location = "location" in e ? e.location : e.keyLocation; + if (location === 3) { + callback(e, hashId, -keyCode); + if (e.defaultPrevented) + return; + } + } + + if (useragent.isChromeOS && hashId & 8) { + callback(e, hashId, keyCode); + if (e.defaultPrevented) + return; + else + hashId &= ~8; + } + 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 && !("KeyboardEvent" in window))) { + var lastKeyDownKeyCode = null; + addListener(el, "keydown", function(e) { + lastKeyDownKeyCode = e.keyCode; + }); + addListener(el, "keypress", function(e) { + return normalizeCommandKeys(callback, e, lastKeyDownKeyCode); + }); + } else { + var lastDefaultPrevented = null; + + addListener(el, "keydown", function(e) { + pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1; + var result = normalizeCommandKeys(callback, e, e.keyCode); + lastDefaultPrevented = e.defaultPrevented; + return result; + }); + + addListener(el, "keypress", function(e) { + if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) { + exports.stopEvent(e); + lastDefaultPrevented = null; + } + }); + + addListener(el, "keyup", function(e) { + pressedKeys[e.keyCode] = null; + }); + + if (!pressedKeys) { + resetPressedKeys(); + addListener(window, "focus", resetPressedKeys); + } + } +}; +function resetPressedKeys() { + pressedKeys = Object.create(null); +} + +if (typeof window == "object" && window.postMessage && !useragent.isOldIE) { + 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, "*"); + }; +} + + +exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame + || window.mozRequestAnimationFrame + || window.webkitRequestAnimationFrame + || window.msRequestAnimationFrame + || window.oRequestAnimationFrame); + +if (exports.nextFrame) + exports.nextFrame = exports.nextFrame.bind(window); +else + exports.nextFrame = function(callback) { + setTimeout(callback, 17); + }; +}); + +ace.define("ace/lib/lang",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.last = function(a) { + return a[a.length - 1]; +}; + +exports.stringReverse = function(string) { + return string.split("").reverse().join(""); +}; + +exports.stringRepeat = function (string, count) { + var result = ''; + while (count > 0) { + if (count & 1) + result += string; + + if (count >>= 1) + string += string; + } + return result; +}; + +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= 53) { + onInput(); + } + }; + + + + var syncComposition = lang.delayedCall(onCompositionUpdate, 50); + + event.addListener(text, "compositionstart", onCompositionStart); + if (useragent.isGecko) { + event.addListener(text, "text", function(){syncComposition.schedule()}); + } else { + event.addListener(text, "keyup", function(){syncComposition.schedule()}); + event.addListener(text, "keydown", function(){syncComposition.schedule()}); + } + event.addListener(text, "compositionend", onCompositionEnd); + + this.getElement = function() { + return text; + }; + + this.setReadOnly = function(readOnly) { + text.readOnly = readOnly; + }; + + this.onContextMenu = function(e) { + afterContextMenu = true; + resetSelection(host.selection.isEmpty()); + host._emit("nativecontextmenu", {target: host, domEvent: e}); + this.moveToMouse(e, true); + }; + + this.moveToMouse = function(e, bringToFront) { + if (!bringToFront && useragent.isOldIE) + return; + if (!tempStyle) + tempStyle = text.style.cssText; + text.style.cssText = (bringToFront ? "z-index:100000;" : "") + + "height:" + text.style.height + ";" + + (useragent.isIE ? "opacity:0.1;" : ""); + + var rect = host.container.getBoundingClientRect(); + var style = dom.computedStyle(host.container); + var top = rect.top + (parseInt(style.borderTopWidth) || 0); + var left = rect.left + (parseInt(rect.borderLeftWidth) || 0); + var maxTop = rect.bottom - top - text.clientHeight -2; + var move = function(e) { + text.style.left = e.clientX - left - 2 + "px"; + text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px"; + }; + move(e); + + if (e.type != "mousedown") + return; + + if (host.renderer.$keepTextAreaAtCursor) + host.renderer.$keepTextAreaAtCursor = null; + + clearTimeout(closeTimeout); + if (useragent.isWin && !useragent.isOldIE) + event.capture(host.container, move, onContextMenuClose); + }; + + this.onContextMenuClose = onContextMenuClose; + var closeTimeout; + function onContextMenuClose() { + clearTimeout(closeTimeout); + closeTimeout = setTimeout(function () { + if (tempStyle) { + text.style.cssText = tempStyle; + tempStyle = ''; + } + if (host.renderer.$keepTextAreaAtCursor == null) { + host.renderer.$keepTextAreaAtCursor = true; + host.renderer.$moveTextAreaToCursor(); + } + }, useragent.isOldIE ? 200 : 0); + } + + var onContextMenu = function(e) { + host.textInput.onContextMenu(e); + onContextMenuClose(); + }; + event.addListener(text, "mouseup", onContextMenu); + event.addListener(text, "mousedown", function(e) { + e.preventDefault(); + onContextMenuClose(); + }); + event.addListener(host.renderer.scroller, "contextmenu", onContextMenu); + event.addListener(text, "contextmenu", onContextMenu); +}; + +exports.TextInput = TextInput; +}); + +ace.define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); + +var DRAG_OFFSET = 0; // 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.onMouseWheel.bind(mouseHandler)); + editor.setDefaultHandler("touchmove", this.onTouchMove.bind(mouseHandler)); + + var exports = ["select", "startSelect", "selectEnd", "selectAllEnd", "selectByWordsEnd", + "selectByLinesEnd", "dragWait", "dragWaitEnd", "focusWait"]; + + exports.forEach(function(x) { + mouseHandler[x] = this[x]; + }, this); + + mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange"); + mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange"); +} + +(function() { + + this.onMouseDown = function(ev) { + var inSelection = ev.inSelection(); + var pos = ev.getDocumentPosition(); + this.mousedownEvent = ev; + var editor = this.editor; + + var button = ev.getButton(); + if (button !== 0) { + var selectionRange = editor.getSelectionRange(); + var selectionEmpty = selectionRange.isEmpty(); + editor.$blockScrolling++; + if (selectionEmpty || button == 1) + editor.selection.moveToPosition(pos); + editor.$blockScrolling--; + if (button == 2) + editor.textInput.onContextMenu(ev.domEvent); + return; // stopping event here breaks contextmenu on ff mac + } + + this.mousedownEvent.time = Date.now(); + if (inSelection && !editor.isFocused()) { + editor.focus(); + if (this.$focusTimout && !this.$clickSelection && !editor.inMultiSelectMode) { + this.setState("focusWait"); + this.captureMouse(ev); + return; + } + } + + this.captureMouse(ev); + this.startSelect(pos, ev.domEvent._clicks > 1); + return ev.preventDefault(); + }; + + this.startSelect = function(pos, waitForClickSelection) { + pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y); + var editor = this.editor; + editor.$blockScrolling++; + if (this.mousedownEvent.getShiftKey()) + editor.selection.selectToPosition(pos); + else if (!waitForClickSelection) + editor.selection.moveToPosition(pos); + if (!waitForClickSelection) + this.select(); + if (editor.renderer.scroller.setCapture) { + editor.renderer.scroller.setCapture(); + } + editor.setStyle("ace_selecting"); + this.setState("select"); + editor.$blockScrolling--; + }; + + this.select = function() { + var anchor, editor = this.editor; + var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); + editor.$blockScrolling++; + 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 { + var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); + cursor = orientedRange.cursor; + anchor = orientedRange.anchor; + } + editor.selection.setSelectionAnchor(anchor.row, anchor.column); + } + editor.selection.selectToPosition(cursor); + editor.$blockScrolling--; + 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); + editor.$blockScrolling++; + 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; + if (range.end.row != cursor.row || range.end.column != cursor.column) + cursor = range.start; + } else if (cmpEnd == 1 && cmpStart >= 0) { + anchor = this.$clickSelection.start; + if (range.start.row != cursor.row || range.start.column != cursor.column) + cursor = range.end; + } else if (cmpStart == -1 && cmpEnd == 1) { + cursor = range.end; + anchor = range.start; + } else { + var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); + cursor = orientedRange.cursor; + anchor = orientedRange.anchor; + } + editor.selection.setSelectionAnchor(anchor.row, anchor.column); + } + editor.selection.selectToPosition(cursor); + editor.$blockScrolling--; + editor.renderer.scrollCursorIntoView(); + }; + + this.selectEnd = + this.selectAllEnd = + this.selectByWordsEnd = + this.selectByLinesEnd = function() { + this.$clickSelection = null; + this.editor.unsetStyle("ace_selecting"); + if (this.editor.renderer.scroller.releaseCapture) { + this.editor.renderer.scroller.releaseCapture(); + } + }; + + this.focusWait = function() { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + var time = Date.now(); + + if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimout) + this.startSelect(this.mousedownEvent.getDocumentPosition()); + }; + + this.onDoubleClick = function(ev) { + var pos = ev.getDocumentPosition(); + var editor = this.editor; + var session = editor.session; + + var range = session.getBracketRange(pos); + if (range) { + if (range.isEmpty()) { + range.start.column--; + range.end.column++; + } + this.setState("select"); + } else { + range = editor.selection.getWordRange(pos.row, pos.column); + this.setState("selectByWords"); + } + this.$clickSelection = range; + this.select(); + }; + + this.onTripleClick = function(ev) { + var pos = ev.getDocumentPosition(); + var editor = this.editor; + + this.setState("selectByLines"); + var range = editor.getSelectionRange(); + if (range.isMultiLine() && range.contains(pos.row, pos.column)) { + this.$clickSelection = editor.selection.getLineRange(range.start.row); + this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end; + } else { + this.$clickSelection = editor.selection.getLineRange(pos.row); + } + this.select(); + }; + + this.onQuadClick = function(ev) { + var editor = this.editor; + + editor.selectAll(); + this.$clickSelection = editor.getSelectionRange(); + this.setState("selectAll"); + }; + + this.onMouseWheel = function(ev) { + if (ev.getAccelKey()) + return; + if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) { + ev.wheelX = ev.wheelY; + ev.wheelY = 0; + } + + var t = ev.domEvent.timeStamp; + var dt = t - (this.$lastScrollTime||0); + + var editor = this.editor; + var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + if (isScrolable || dt < 200) { + this.$lastScrollTime = t; + editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + return ev.stop(); + } + }; + + this.onTouchMove = function (ev) { + var t = ev.domEvent.timeStamp; + var dt = t - (this.$lastScrollTime || 0); + + var editor = this.editor; + var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + if (isScrolable || dt < 200) { + this.$lastScrollTime = t; + editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); + return ev.stop(); + } + }; + +}).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)); +} + +function calcRangeOrientation(range, cursor) { + if (range.start.row == range.end.row) + var cmp = 2 * cursor.column - range.start.column - range.end.column; + else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column) + var cmp = cursor.column - 4; + else + var cmp = 2 * cursor.row - range.start.row - range.end.row; + + if (cmp < 0) + return {cursor: range.start, anchor: range.end}; + else + return {cursor: range.end, anchor: range.start}; +} + +}); + +ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +function Tooltip (parentNode) { + this.isOpen = false; + this.$element = null; + this.$parentNode = parentNode; +} + +(function() { + this.$init = function() { + this.$element = dom.createElement("div"); + this.$element.className = "ace_tooltip"; + this.$element.style.display = "none"; + this.$parentNode.appendChild(this.$element); + return this.$element; + }; + this.getElement = function() { + return this.$element || this.$init(); + }; + this.setText = function(text) { + dom.setInnerText(this.getElement(), text); + }; + this.setHtml = function(html) { + this.getElement().innerHTML = html; + }; + this.setPosition = function(x, y) { + this.getElement().style.left = x + "px"; + this.getElement().style.top = y + "px"; + }; + this.setClassName = function(className) { + dom.addCssClass(this.getElement(), className); + }; + this.show = function(text, x, y) { + if (text != null) + this.setText(text); + if (x != null && y != null) + this.setPosition(x, y); + if (!this.isOpen) { + this.getElement().style.display = "block"; + this.isOpen = true; + } + }; + + this.hide = function() { + if (this.isOpen) { + this.getElement().style.display = "none"; + this.isOpen = false; + } + }; + this.getHeight = function() { + return this.getElement().offsetHeight; + }; + this.getWidth = function() { + return this.getElement().offsetWidth; + }; + +}).call(Tooltip.prototype); + +exports.Tooltip = Tooltip; +}); + +ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(acequire, exports, module) { +"use strict"; +var dom = acequire("../lib/dom"); +var oop = acequire("../lib/oop"); +var event = acequire("../lib/event"); +var Tooltip = acequire("../tooltip").Tooltip; + +function GutterHandler(mouseHandler) { + var editor = mouseHandler.editor; + var gutter = editor.renderer.$gutterLayer; + var tooltip = new GutterTooltip(editor.container); + + mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) { + if (!editor.isFocused() || e.getButton() != 0) + return; + var gutterRegion = gutter.getRegion(e); + + if (gutterRegion == "foldWidgets") + return; + + var row = e.getDocumentPosition().row; + var selection = editor.session.selection; + + if (e.getShiftKey()) + selection.selectTo(row, 0); + else { + if (e.domEvent.detail == 2) { + editor.selectAll(); + return e.preventDefault(); + } + mouseHandler.$clickSelection = editor.selection.getLineRange(row); + } + mouseHandler.setState("selectByLines"); + mouseHandler.captureMouse(e); + return e.preventDefault(); + }); + + + var tooltipTimeout, mouseEvent, tooltipAnnotation; + + function showTooltip() { + var row = mouseEvent.getDocumentPosition().row; + var annotation = gutter.$annotations[row]; + if (!annotation) + return hideTooltip(); + + var maxRow = editor.session.getLength(); + if (row == maxRow) { + var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row; + var pos = mouseEvent.$pos; + if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column)) + return hideTooltip(); + } + + if (tooltipAnnotation == annotation) + return; + tooltipAnnotation = annotation.text.join("
"); + + tooltip.setHtml(tooltipAnnotation); + tooltip.show(); + editor._signal("showGutterTooltip", tooltip); + editor.on("mousewheel", hideTooltip); + + if (mouseHandler.$tooltipFollowsMouse) { + moveTooltip(mouseEvent); + } else { + var gutterElement = mouseEvent.domEvent.target; + var rect = gutterElement.getBoundingClientRect(); + var style = tooltip.getElement().style; + style.left = rect.right + "px"; + style.top = rect.bottom + "px"; + } + } + + function hideTooltip() { + if (tooltipTimeout) + tooltipTimeout = clearTimeout(tooltipTimeout); + if (tooltipAnnotation) { + tooltip.hide(); + tooltipAnnotation = null; + editor._signal("hideGutterTooltip", tooltip); + editor.removeEventListener("mousewheel", hideTooltip); + } + } + + function moveTooltip(e) { + tooltip.setPosition(e.x, e.y); + } + + mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) { + var target = e.domEvent.target || e.domEvent.srcElement; + if (dom.hasCssClass(target, "ace_fold-widget")) + return hideTooltip(); + + if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse) + moveTooltip(e); + + mouseEvent = e; + if (tooltipTimeout) + return; + tooltipTimeout = setTimeout(function() { + tooltipTimeout = null; + if (mouseEvent && !mouseHandler.isMousePressed) + showTooltip(); + else + hideTooltip(); + }, 50); + }); + + event.addListener(editor.renderer.$gutter, "mouseout", function(e) { + mouseEvent = null; + if (!tooltipAnnotation || tooltipTimeout) + return; + + tooltipTimeout = setTimeout(function() { + tooltipTimeout = null; + hideTooltip(); + }, 50); + }); + + editor.on("changeSession", hideTooltip); +} + +function GutterTooltip(parentNode) { + Tooltip.call(this, parentNode); +} + +oop.inherits(GutterTooltip, Tooltip); + +(function(){ + this.setPosition = function(x, y) { + var windowWidth = window.innerWidth || document.documentElement.clientWidth; + var windowHeight = window.innerHeight || document.documentElement.clientHeight; + var width = this.getWidth(); + var height = this.getHeight(); + x += 15; + y += 15; + if (x + width > windowWidth) { + x -= (x + width) - windowWidth; + } + if (y + height > windowHeight) { + y -= 20 + height; + } + Tooltip.prototype.setPosition.call(this, x, y); + }; + +}).call(GutterTooltip.prototype); + + + +exports.GutterHandler = GutterHandler; + +}); + +ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); +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; + + + 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 = useragent.isMac + ? function() { return this.domEvent.metaKey; } + : function() { return this.domEvent.ctrlKey; }; + +}).call(MouseEvent.prototype); + +}); + +ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); + +var AUTOSCROLL_DELAY = 200; +var SCROLL_CURSOR_DELAY = 200; +var SCROLL_CURSOR_HYSTERESIS = 5; + +function DragdropHandler(mouseHandler) { + + var editor = mouseHandler.editor; + + var blankImage = dom.createElement("img"); + blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (useragent.isOpera) + blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;"; + + var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"]; + + exports.forEach(function(x) { + mouseHandler[x] = this[x]; + }, this); + editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler)); + + + var mouseTarget = editor.container; + var dragSelectionMarker, x, y; + var timerId, range; + var dragCursor, counter = 0; + var dragOperation; + var isInternal; + var autoScrollStartTime; + var cursorMovedTime; + var cursorPointOnCaretMoved; + + this.onDragStart = function(e) { + if (this.cancelDrag || !mouseTarget.draggable) { + var self = this; + setTimeout(function(){ + self.startSelect(); + self.captureMouse(e); + }, 0); + return e.preventDefault(); + } + range = editor.getSelectionRange(); + + var dataTransfer = e.dataTransfer; + dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove"; + if (useragent.isOpera) { + editor.container.appendChild(blankImage); + blankImage.scrollTop = 0; + } + dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0); + if (useragent.isOpera) { + editor.container.removeChild(blankImage); + } + dataTransfer.clearData(); + dataTransfer.setData("Text", editor.session.getTextRange()); + + isInternal = true; + this.setState("drag"); + }; + + this.onDragEnd = function(e) { + mouseTarget.draggable = false; + isInternal = false; + this.setState(null); + if (!editor.getReadOnly()) { + var dropEffect = e.dataTransfer.dropEffect; + if (!dragOperation && dropEffect == "move") + editor.session.remove(editor.getSelectionRange()); + editor.renderer.$cursorLayer.setBlinking(true); + } + this.editor.unsetStyle("ace_dragging"); + this.editor.renderer.setCursorStyle(""); + }; + + this.onDragEnter = function(e) { + if (editor.getReadOnly() || !canAccept(e.dataTransfer)) + return; + x = e.clientX; + y = e.clientY; + if (!dragSelectionMarker) + addDragMarker(); + counter++; + e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); + return event.preventDefault(e); + }; + + this.onDragOver = function(e) { + if (editor.getReadOnly() || !canAccept(e.dataTransfer)) + return; + x = e.clientX; + y = e.clientY; + if (!dragSelectionMarker) { + addDragMarker(); + counter++; + } + if (onMouseMoveTimer !== null) + onMouseMoveTimer = null; + + e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); + return event.preventDefault(e); + }; + + this.onDragLeave = function(e) { + counter--; + if (counter <= 0 && dragSelectionMarker) { + clearDragMarker(); + dragOperation = null; + return event.preventDefault(e); + } + }; + + this.onDrop = function(e) { + if (!dragCursor) + return; + var dataTransfer = e.dataTransfer; + if (isInternal) { + switch (dragOperation) { + case "move": + if (range.contains(dragCursor.row, dragCursor.column)) { + range = { + start: dragCursor, + end: dragCursor + }; + } else { + range = editor.moveText(range, dragCursor); + } + break; + case "copy": + range = editor.moveText(range, dragCursor, true); + break; + } + } else { + var dropData = dataTransfer.getData('Text'); + range = { + start: dragCursor, + end: editor.session.insert(dragCursor, dropData) + }; + editor.focus(); + dragOperation = null; + } + clearDragMarker(); + return event.preventDefault(e); + }; + + event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler)); + event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler)); + event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler)); + event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler)); + event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler)); + event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler)); + + function scrollCursorIntoView(cursor, prevCursor) { + var now = Date.now(); + var vMovement = !prevCursor || cursor.row != prevCursor.row; + var hMovement = !prevCursor || cursor.column != prevCursor.column; + if (!cursorMovedTime || vMovement || hMovement) { + editor.$blockScrolling += 1; + editor.moveCursorToPosition(cursor); + editor.$blockScrolling -= 1; + cursorMovedTime = now; + cursorPointOnCaretMoved = {x: x, y: y}; + } else { + var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y); + if (distance > SCROLL_CURSOR_HYSTERESIS) { + cursorMovedTime = null; + } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) { + editor.renderer.scrollCursorIntoView(); + cursorMovedTime = null; + } + } + } + + function autoScroll(cursor, prevCursor) { + var now = Date.now(); + var lineHeight = editor.renderer.layerConfig.lineHeight; + var characterWidth = editor.renderer.layerConfig.characterWidth; + var editorRect = editor.renderer.scroller.getBoundingClientRect(); + var offsets = { + x: { + left: x - editorRect.left, + right: editorRect.right - x + }, + y: { + top: y - editorRect.top, + bottom: editorRect.bottom - y + } + }; + var nearestXOffset = Math.min(offsets.x.left, offsets.x.right); + var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom); + var scrollCursor = {row: cursor.row, column: cursor.column}; + if (nearestXOffset / characterWidth <= 2) { + scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2); + } + if (nearestYOffset / lineHeight <= 1) { + scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1); + } + var vScroll = cursor.row != scrollCursor.row; + var hScroll = cursor.column != scrollCursor.column; + var vMovement = !prevCursor || cursor.row != prevCursor.row; + if (vScroll || (hScroll && !vMovement)) { + if (!autoScrollStartTime) + autoScrollStartTime = now; + else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY) + editor.renderer.scrollCursorIntoView(scrollCursor); + } else { + autoScrollStartTime = null; + } + } + + function onDragInterval() { + var prevCursor = dragCursor; + dragCursor = editor.renderer.screenToTextCoordinates(x, y); + scrollCursorIntoView(dragCursor, prevCursor); + autoScroll(dragCursor, prevCursor); + } + + function addDragMarker() { + range = editor.selection.toOrientedRange(); + dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle()); + editor.clearSelection(); + if (editor.isFocused()) + editor.renderer.$cursorLayer.setBlinking(false); + clearInterval(timerId); + onDragInterval(); + timerId = setInterval(onDragInterval, 20); + counter = 0; + event.addListener(document, "mousemove", onMouseMove); + } + + function clearDragMarker() { + clearInterval(timerId); + editor.session.removeMarker(dragSelectionMarker); + dragSelectionMarker = null; + editor.$blockScrolling += 1; + editor.selection.fromOrientedRange(range); + editor.$blockScrolling -= 1; + if (editor.isFocused() && !isInternal) + editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly()); + range = null; + dragCursor = null; + counter = 0; + autoScrollStartTime = null; + cursorMovedTime = null; + event.removeListener(document, "mousemove", onMouseMove); + } + var onMouseMoveTimer = null; + function onMouseMove() { + if (onMouseMoveTimer == null) { + onMouseMoveTimer = setTimeout(function() { + if (onMouseMoveTimer != null && dragSelectionMarker) + clearDragMarker(); + }, 20); + } + } + + function canAccept(dataTransfer) { + var types = dataTransfer.types; + return !types || Array.prototype.some.call(types, function(type) { + return type == 'text/plain' || type == 'Text'; + }); + } + + function getDropEffect(e) { + var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized']; + var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized']; + + var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey; + var effectAllowed = "uninitialized"; + try { + effectAllowed = e.dataTransfer.effectAllowed.toLowerCase(); + } catch (e) {} + var dropEffect = "none"; + + if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "copy"; + else if (moveAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "move"; + else if (copyAllowed.indexOf(effectAllowed) >= 0) + dropEffect = "copy"; + + return dropEffect; + } +} + +(function() { + + this.dragWait = function() { + var interval = Date.now() - this.mousedownEvent.time; + if (interval > this.editor.getDragDelay()) + this.startDrag(); + }; + + this.dragWaitEnd = function() { + var target = this.editor.container; + target.draggable = false; + this.startSelect(this.mousedownEvent.getDocumentPosition()); + this.selectEnd(); + }; + + this.dragReadyEnd = function(e) { + this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly()); + this.editor.unsetStyle("ace_dragging"); + this.editor.renderer.setCursorStyle(""); + this.dragWaitEnd(); + }; + + this.startDrag = function(){ + this.cancelDrag = false; + var editor = this.editor; + var target = editor.container; + target.draggable = true; + editor.renderer.$cursorLayer.setBlinking(false); + editor.setStyle("ace_dragging"); + var cursorStyle = useragent.isWin ? "default" : "move"; + editor.renderer.setCursorStyle(cursorStyle); + this.setState("dragReady"); + }; + + this.onMouseDrag = function(e) { + var target = this.editor.container; + if (useragent.isIE && this.state == "dragReady") { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + if (distance > 3) + target.dragDrop(); + } + if (this.state === "dragWait") { + var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); + if (distance > 0) { + target.draggable = false; + this.startSelect(this.mousedownEvent.getDocumentPosition()); + } + } + }; + + this.onMouseDown = function(e) { + if (!this.$dragEnabled) + return; + this.mousedownEvent = e; + var editor = this.editor; + + var inSelection = e.inSelection(); + var button = e.getButton(); + var clickCount = e.domEvent.detail || 1; + if (clickCount === 1 && button === 0 && inSelection) { + if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey())) + return; + this.mousedownEvent.time = Date.now(); + var eventTarget = e.domEvent.target || e.domEvent.srcElement; + if ("unselectable" in eventTarget) + eventTarget.unselectable = "on"; + if (editor.getDragDelay()) { + if (useragent.isWebKit) { + this.cancelDrag = true; + var mouseTarget = editor.container; + mouseTarget.draggable = true; + } + this.setState("dragWait"); + } else { + this.startDrag(); + } + this.captureMouse(e, this.onMouseDrag.bind(this)); + e.defaultPrevented = true; + } + }; + +}).call(DragdropHandler.prototype); + + +function calcDistance(ax, ay, bx, by) { + return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); +} + +exports.DragdropHandler = DragdropHandler; + +}); + +ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; +var dom = acequire("./dom"); + +exports.get = function (url, callback) { + var xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + callback(xhr.responseText); + } + }; + xhr.send(null); +}; + +exports.loadScript = function(path, callback) { + var head = dom.getDocumentHead(); + var s = document.createElement('script'); + + s.src = path; + head.appendChild(s); + + s.onload = s.onreadystatechange = function(_, isAbort) { + if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") { + s = s.onload = s.onreadystatechange = null; + if (!isAbort) + callback(); + } + }; +}; +exports.qualifyURL = function(url) { + var a = document.createElement('a'); + a.href = url; + return a.href; +} + +}); + +ace.define("ace/lib/event_emitter",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +var EventEmitter = {}; +var stopPropagation = function() { this.propagationStopped = true; }; +var preventDefault = function() { this.defaultPrevented = true; }; + +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; + + if (typeof e != "object" || !e) + e = {}; + + if (!e.type) + e.type = eventName; + if (!e.stopPropagation) + e.stopPropagation = stopPropagation; + if (!e.preventDefault) + e.preventDefault = preventDefault; + + listeners = listeners.slice(); + for (var i=0; i 1) + base = parts[parts.length - 2]; + var path = options[component + "Path"]; + if (path == null) { + path = options.basePath; + } else if (sep == "/") { + component = sep = ""; + } + if (path && path.slice(-1) != "/") + path += "/"; + return path + component + sep + base + this.get("suffix"); +}; + +exports.setModuleUrl = function(name, subst) { + return options.$moduleUrls[name] = subst; +}; + +exports.$loading = {}; +exports.loadModule = function(moduleName, onLoad) { + var module, moduleType; + if (Array.isArray(moduleName)) { + moduleType = moduleName[0]; + moduleName = moduleName[1]; + } + + try { + module = acequire(moduleName); + } catch (e) {} + if (module && !exports.$loading[moduleName]) + return onLoad && onLoad(module); + + if (!exports.$loading[moduleName]) + exports.$loading[moduleName] = []; + + exports.$loading[moduleName].push(onLoad); + + if (exports.$loading[moduleName].length > 1) + return; + + var afterLoad = function() { + acequire([moduleName], function(module) { + exports._emit("load.module", {name: moduleName, module: module}); + var listeners = exports.$loading[moduleName]; + exports.$loading[moduleName] = null; + listeners.forEach(function(onLoad) { + onLoad && onLoad(module); + }); + }); + }; + + if (!exports.get("packaged")) + return afterLoad(); + net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad); +}; +init(true);function init(packaged) { + + if (!global || !global.document) + return; + + options.packaged = packaged || acequire.packaged || module.packaged || (global.define && __webpack_require__(41).packaged); + + var scriptOptions = {}; + var scriptUrl = ""; + var currentScript = (document.currentScript || document._currentScript ); // native or polyfill + var currentDocument = currentScript && currentScript.ownerDocument || document; + + var scripts = currentDocument.getElementsByTagName("script"); + for (var i=0; i [" + 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; + } + } + }; + this.comparePoint = function(p) { + return this.compare(p.row, p.column); + }; + this.containsRange = function(range) { + return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; + }; + this.intersects = function(range) { + var cmp = this.compareRange(range); + return (cmp == -1 || cmp == 0 || cmp == 1); + }; + this.isEnd = function(row, column) { + return this.end.row == row && this.end.column == column; + }; + this.isStart = function(row, column) { + return this.start.row == row && this.start.column == column; + }; + 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; + } + }; + 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; + } + }; + 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; + }; + this.insideStart = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isEnd(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + this.insideEnd = function(row, column) { + if (this.compare(row, column) == 0) { + if (this.isStart(row, column)) { + return false; + } else { + return true; + } + } + return false; + }; + 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); + } + }; + this.compareEnd = function(row, column) { + if (this.end.row == row && this.end.column == column) { + return 1; + } else { + return this.compare(row, column); + } + }; + 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); + } + }; + this.clipRows = function(firstRow, lastRow) { + if (this.end.row > lastRow) + var end = {row: lastRow + 1, column: 0}; + else if (this.end.row < firstRow) + var end = {row: firstRow, column: 0}; + + if (this.start.row > lastRow) + var start = {row: lastRow + 1, column: 0}; + else if (this.start.row < firstRow) + var start = {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 + ); + }; + this.moveBy = function(row, column) { + this.start.row += row; + this.start.column += column; + this.end.row += row; + this.end.column += column; + }; + +}).call(Range.prototype); +Range.fromPoints = function(start, end) { + return new Range(start.row, start.column, end.row, end.column); +}; +Range.comparePoints = comparePoints; + +Range.comparePoints = function(p1, p2) { + return p1.row - p2.row || p1.column - p2.column; +}; + + +exports.Range = Range; +}); + +ace.define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var lang = acequire("./lib/lang"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Range = acequire("./range").Range; +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); + } + if (this.getRange().isEmpty()) + this.$isEmpty = true; + 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.moveTo = function(row, column) { + this.clearSelection(); + this.moveCursorTo(row, column); + }; + this.moveToPosition = function(pos) { + this.clearSelection(); + 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 === true) + 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) { + 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); + var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0); + var beforeCursor = this.session.getDisplayLine( + row, null, firstColumnPosition.row, + firstColumnPosition.column + ); + + var leadingSpace = beforeCursor.match(/^\s*/); + if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart) + firstColumnPosition.column += leadingSpace[0].length; + this.moveCursorToPosition(firstColumnPosition); + }; + this.moveCursorLineEnd = function() { + var lead = this.lead; + var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column); + if (this.lead.column == lineEnd.column) { + var line = this.session.getLine(lineEnd.row); + if (lineEnd.column == line.length) { + var textEnd = line.search(/\s+$/); + if (textEnd > 0) + lineEnd.column = textEnd; + } + } + + this.moveCursorTo(lineEnd.row, lineEnd.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; + var fold = this.session.getFoldAt(row, column, 1); + if (fold) { + this.moveCursorTo(fold.end.row, fold.end.column); + return; + } + if (match = this.session.nonTokenRe.exec(rightOfCursor)) { + column += this.session.nonTokenRe.lastIndex; + this.session.nonTokenRe.lastIndex = 0; + rightOfCursor = line.substring(column); + } + if (column >= line.length) { + this.moveCursorTo(row, line.length); + this.moveCursorRight(); + if (row < this.doc.getLength() - 1) + this.moveCursorWordRight(); + return; + } + 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; + 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; + 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 (column <= 0) { + this.moveCursorTo(row, 0); + this.moveCursorLeft(); + if (row > 0) + this.moveCursorWordLeft(); + return; + } + 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); + + if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) { + if (this.session.lineWidgets && this.session.lineWidgets[docPos.row]) { + if (docPos.row > 0 || rows > 0) + docPos.row++; + } + } + 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) { + 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); + }; + 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; + }; + this.getRangeOfMovements = function(func) { + var start = this.getCursor(); + try { + func(this); + var end = this.getCursor(); + return Range.fromPoints(start,end); + } catch(e) { + return Range.fromPoints(start,start); + } finally { + this.moveCursorToPosition(start); + } + }; + + this.toJSON = function() { + if (this.rangeCount) { + var data = this.ranges.map(function(r) { + var r1 = r.clone(); + r1.isBackwards = r.cursor == r.start; + return r1; + }); + } else { + var data = this.getRange(); + data.isBackwards = this.isBackwards(); + } + return data; + }; + + this.fromJSON = function(data) { + if (data.start == undefined) { + if (this.rangeList) { + this.toSingleRange(data[0]); + for (var i = data.length; i--; ) { + var r = Range.fromPoints(data[i].start, data[i].end); + if (data[i].isBackwards) + r.cursor = r.start; + this.addRange(r, true); + } + return; + } else + data = data[0]; + } + if (this.rangeList) + this.toSingleRange(data); + this.setSelectionRange(data, data.isBackwards); + }; + + this.isEqual = function(data) { + if ((data.length || this.rangeCount) && data.length != this.rangeCount) + return false; + if (!data.length || !this.ranges) + return this.getRange().isEqual(data); + + for (var i = this.ranges.length; i--; ) { + if (!this.ranges[i].isEqual(data[i])) + return false; + } + return true; + }; + +}).call(Selection.prototype); + +exports.Selection = Selection; +}); + +ace.define("ace/tokenizer",["require","exports","module","ace/config"], function(acequire, exports, module) { +"use strict"; + +var config = acequire("./config"); +var MAX_TOKEN_COUNT = 2000; +var Tokenizer = function(rules) { + this.states = rules; + + this.regExps = {}; + this.matchMappings = {}; + for (var key in this.states) { + var state = this.states[key]; + var ruleRegExps = []; + var matchTotal = 0; + var mapping = this.matchMappings[key] = {defaultToken: "text"}; + var flag = "g"; + + var splitterRurles = []; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + if (rule.defaultToken) + mapping.defaultToken = rule.defaultToken; + if (rule.caseInsensitive) + flag = "gi"; + if (rule.regex == null) + continue; + + if (rule.regex instanceof RegExp) + rule.regex = rule.regex.toString().slice(1, -1); + var adjustedregex = rule.regex; + var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2; + if (Array.isArray(rule.token)) { + if (rule.token.length == 1 || matchcount == 1) { + rule.token = rule.token[0]; + } else if (matchcount - 1 != rule.token.length) { + this.reportError("number of classes and regexp groups doesn't match", { + rule: rule, + groupCount: matchcount - 1 + }); + rule.token = rule.token[0]; + } else { + rule.tokenArray = rule.token; + rule.token = null; + rule.onMatch = this.$arrayTokens; + } + } else if (typeof rule.token == "function" && !rule.onMatch) { + if (matchcount > 1) + rule.onMatch = this.$applyToken; + else + rule.onMatch = rule.token; + } + + if (matchcount > 1) { + if (/\\\d/.test(rule.regex)) { + adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) { + return "\\" + (parseInt(digit, 10) + matchTotal + 1); + }); + } else { + matchcount = 1; + adjustedregex = this.removeCapturingGroups(rule.regex); + } + if (!rule.splitRegex && typeof rule.token != "string") + splitterRurles.push(rule); // flag will be known only at the very end + } + + mapping[matchTotal] = i; + matchTotal += matchcount; + + ruleRegExps.push(adjustedregex); + if (!rule.onMatch) + rule.onMatch = null; + } + + if (!ruleRegExps.length) { + mapping[0] = 0; + ruleRegExps.push("$"); + } + + splitterRurles.forEach(function(rule) { + rule.splitRegex = this.createSplitterRegexp(rule.regex, flag); + }, this); + + this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag); + } +}; + +(function() { + this.$setMaxTokenCount = function(m) { + MAX_TOKEN_COUNT = m | 0; + }; + + this.$applyToken = function(str) { + var values = this.splitRegex.exec(str).slice(1); + var types = this.token.apply(this, values); + if (typeof types === "string") + return [{type: types, value: str}]; + + var tokens = []; + for (var i = 0, l = types.length; i < l; i++) { + if (values[i]) + tokens[tokens.length] = { + type: types[i], + value: values[i] + }; + } + return tokens; + }; + + this.$arrayTokens = function(str) { + if (!str) + return []; + var values = this.splitRegex.exec(str); + if (!values) + return "text"; + var tokens = []; + var types = this.tokenArray; + for (var i = 0, l = types.length; i < l; i++) { + if (values[i + 1]) + tokens[tokens.length] = { + type: types[i], + value: values[i + 1] + }; + } + return tokens; + }; + + this.removeCapturingGroups = function(src) { + var r = src.replace( + /\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g, + function(x, y) {return y ? "(?:" : x;} + ); + return r; + }; + + this.createSplitterRegexp = function(src, flag) { + if (src.indexOf("(?=") != -1) { + var stack = 0; + var inChClass = false; + var lastCapture = {}; + src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function( + m, esc, parenOpen, parenClose, square, index + ) { + if (inChClass) { + inChClass = square != "]"; + } else if (square) { + inChClass = true; + } else if (parenClose) { + if (stack == lastCapture.stack) { + lastCapture.end = index+1; + lastCapture.stack = -1; + } + stack--; + } else if (parenOpen) { + stack++; + if (parenOpen.length != 1) { + lastCapture.stack = stack + lastCapture.start = index; + } + } + return m; + }); + + if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end))) + src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end); + } + if (src.charAt(0) != "^") src = "^" + src; + if (src.charAt(src.length - 1) != "$") src += "$"; + + return new RegExp(src, (flag||"").replace("g", "")); + }; + this.getLineTokens = function(line, startState) { + if (startState && typeof startState != "string") { + var stack = startState.slice(0); + startState = stack[0]; + if (startState === "#tmp") { + stack.shift() + startState = stack.shift() + } + } else + var stack = []; + + var currentState = startState || "start"; + var state = this.states[currentState]; + if (!state) { + currentState = "start"; + state = this.states[currentState]; + } + var mapping = this.matchMappings[currentState]; + var re = this.regExps[currentState]; + re.lastIndex = 0; + + var match, tokens = []; + var lastIndex = 0; + var matchAttempts = 0; + + var token = {type: null, value: ""}; + + while (match = re.exec(line)) { + var type = mapping.defaultToken; + var rule = null; + var value = match[0]; + var index = re.lastIndex; + + if (index - value.length > lastIndex) { + var skipped = line.substring(lastIndex, index - value.length); + if (token.type == type) { + token.value += skipped; + } else { + if (token.type) + tokens.push(token); + token = {type: type, value: skipped}; + } + } + + for (var i = 0; i < match.length-2; i++) { + if (match[i + 1] === undefined) + continue; + + rule = state[mapping[i]]; + + if (rule.onMatch) + type = rule.onMatch(value, currentState, stack); + else + type = rule.token; + + if (rule.next) { + if (typeof rule.next == "string") { + currentState = rule.next; + } else { + currentState = rule.next(currentState, stack); + } + + state = this.states[currentState]; + if (!state) { + this.reportError("state doesn't exist", currentState); + currentState = "start"; + state = this.states[currentState]; + } + mapping = this.matchMappings[currentState]; + lastIndex = index; + re = this.regExps[currentState]; + re.lastIndex = index; + } + break; + } + + if (value) { + if (typeof type === "string") { + if ((!rule || rule.merge !== false) && token.type === type) { + token.value += value; + } else { + if (token.type) + tokens.push(token); + token = {type: type, value: value}; + } + } else if (type) { + if (token.type) + tokens.push(token); + token = {type: null, value: ""}; + for (var i = 0; i < type.length; i++) + tokens.push(type[i]); + } + } + + if (lastIndex == line.length) + break; + + lastIndex = index; + + if (matchAttempts++ > MAX_TOKEN_COUNT) { + if (matchAttempts > 2 * line.length) { + this.reportError("infinite loop with in ace tokenizer", { + startState: startState, + line: line + }); + } + while (lastIndex < line.length) { + if (token.type) + tokens.push(token); + token = { + value: line.substring(lastIndex, lastIndex += 2000), + type: "overflow" + }; + } + currentState = "start"; + stack = []; + break; + } + } + + if (token.type) + tokens.push(token); + + if (stack.length > 1) { + if (stack[0] !== currentState) + stack.unshift("#tmp", currentState); + } + return { + tokens : tokens, + state : stack.length ? stack : currentState + }; + }; + + this.reportError = config.reportError; + +}).call(Tokenizer.prototype); + +exports.Tokenizer = Tokenizer; +}); + +ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("../lib/lang"); + +var TextHighlightRules = function() { + + this.$rules = { + "start" : [{ + token : "empty_line", + regex : '^$' + }, { + defaultToken : "text" + }] + }; +}; + +(function() { + + this.addRules = function(rules, prefix) { + if (!prefix) { + for (var key in rules) + this.$rules[key] = rules[key]; + return; + } + 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.onMatch) { + if (typeof rule.next == "string") { + if (rule.next.indexOf(prefix) !== 0) + rule.next = prefix + rule.next; + } + if (rule.nextState && rule.nextState.indexOf(prefix) !== 0) + rule.nextState = prefix + rule.nextState; + } + } + this.$rules[prefix + key] = state; + } + }; + + this.getRules = function() { + return this.$rules; + }; + + this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) { + var embedRules = typeof HighlightRules == "function" + ? new HighlightRules().getRules() + : HighlightRules; + 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); + + if (escapeRules) { + var addRules = Array.prototype[append ? "push" : "unshift"]; + for (var i = 0; i < states.length; i++) + addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules)); + } + + if (!this.$embeds) + this.$embeds = []; + this.$embeds.push(prefix); + }; + + this.getEmbeds = function() { + return this.$embeds; + }; + + var pushState = function(currentState, stack) { + if (currentState != "start" || stack.length) + stack.unshift(this.nextState, currentState); + return this.nextState; + }; + var popState = function(currentState, stack) { + stack.shift(); + return stack.shift() || "start"; + }; + + this.normalizeRules = function() { + var id = 0; + var rules = this.$rules; + function processState(key) { + var state = rules[key]; + state.processed = true; + for (var i = 0; i < state.length; i++) { + var rule = state[i]; + var toInsert = null; + if (Array.isArray(rule)) { + toInsert = rule; + rule = {}; + } + if (!rule.regex && rule.start) { + rule.regex = rule.start; + if (!rule.next) + rule.next = []; + rule.next.push({ + defaultToken: rule.token + }, { + token: rule.token + ".end", + regex: rule.end || rule.start, + next: "pop" + }); + rule.token = rule.token + ".start"; + rule.push = true; + } + var next = rule.next || rule.push; + if (next && Array.isArray(next)) { + var stateName = rule.stateName; + if (!stateName) { + stateName = rule.token; + if (typeof stateName != "string") + stateName = stateName[0] || ""; + if (rules[stateName]) + stateName += id++; + } + rules[stateName] = next; + rule.next = stateName; + processState(stateName); + } else if (next == "pop") { + rule.next = popState; + } + + if (rule.push) { + rule.nextState = rule.next || rule.push; + rule.next = pushState; + delete rule.push; + } + + if (rule.rules) { + for (var r in rule.rules) { + if (rules[r]) { + if (rules[r].push) + rules[r].push.apply(rules[r], rule.rules[r]); + } else { + rules[r] = rule.rules[r]; + } + } + } + var includeName = typeof rule == "string" + ? rule + : typeof rule.include == "string" + ? rule.include + : ""; + if (includeName) { + toInsert = rules[includeName]; + } + + if (toInsert) { + var args = [i, 1].concat(toInsert); + if (rule.noEscape) + args = args.filter(function(x) {return !x.next;}); + state.splice.apply(state, args); + i--; + } + + if (rule.keywordMap) { + rule.token = this.createKeywordMapper( + rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive + ); + delete rule.defaultToken; + } + } + } + Object.keys(rules).forEach(processState, this); + }; + + this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) { + var keywords = Object.create(null); + Object.keys(map).forEach(function(className) { + var a = map[className]; + if (ignoreCase) + a = a.toLowerCase(); + var list = a.split(splitChar || "|"); + for (var i = list.length; i--; ) + keywords[list[i]] = className; + }); + if (Object.getPrototypeOf(keywords)) { + keywords.__proto__ = null; + } + this.$keywordList = Object.keys(keywords); + map = null; + return ignoreCase + ? function(value) {return keywords[value.toLowerCase()] || defaultToken } + : function(value) {return keywords[value] || defaultToken }; + }; + + this.getKeywords = function() { + return this.$keywords; + }; + +}).call(TextHighlightRules.prototype); + +exports.TextHighlightRules = TextHighlightRules; +}); + +ace.define("ace/mode/behaviour",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +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; +}); + +ace.define("ace/token_iterator",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +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() { + 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() { + this.$tokenIndex += 1; + var rowCount; + while (this.$tokenIndex >= this.$rowTokens.length) { + this.$row += 1; + if (!rowCount) + rowCount = this.$session.getLength(); + 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; + var column = rowTokens[tokenIndex].start; + if (column !== undefined) + return column; + + column = 0; + while (tokenIndex > 0) { + tokenIndex -= 1; + column += rowTokens[tokenIndex].value.length; + } + + return column; + }; + this.getCurrentTokenPosition = function() { + return {row: this.$row, column: this.getCurrentTokenColumn()}; + }; + +}).call(TokenIterator.prototype); + +exports.TokenIterator = TokenIterator; +}); + +ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Behaviour = acequire("../behaviour").Behaviour; +var TokenIterator = acequire("../../token_iterator").TokenIterator; +var lang = acequire("../../lib/lang"); + +var SAFE_INSERT_IN_TOKENS = + ["text", "paren.rparen", "punctuation.operator"]; +var SAFE_INSERT_BEFORE_TOKENS = + ["text", "paren.rparen", "punctuation.operator", "comment"]; + +var context; +var contextCache = {}; +var initContext = function(editor) { + var id = -1; + if (editor.multiSelect) { + id = editor.selection.index; + if (contextCache.rangeCount != editor.multiSelect.rangeCount) + contextCache = {rangeCount: editor.multiSelect.rangeCount}; + } + if (contextCache[id]) + return context = contextCache[id]; + context = contextCache[id] = { + autoInsertedBrackets: 0, + autoInsertedRow: -1, + autoInsertedLineEnd: "", + maybeInsertedBrackets: 0, + maybeInsertedRow: -1, + maybeInsertedLineStart: "", + maybeInsertedLineEnd: "" + }; +}; + +var getWrapped = function(selection, selected, opening, closing) { + var rowDiff = selection.end.row - selection.start.row; + return { + text: opening + selected + closing, + selection: [ + 0, + selection.start.column + 1, + rowDiff, + selection.end.column + (rowDiff ? 0 : 1) + ] + }; +}; + +var CstyleBehaviour = function() { + this.add("braces", "insertion", function(state, action, editor, session, text) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (text == '{') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '{', '}'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { + CstyleBehaviour.recordAutoInsert(editor, session, "}"); + return { + text: '{}', + selection: [1, 1] + }; + } else { + CstyleBehaviour.recordMaybeInsert(editor, session, "{"); + return { + text: '{', + selection: [1, 1] + }; + } + } + } else if (text == '}') { + initContext(editor); + 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 && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } else if (text == "\n" || text == "\r\n") { + initContext(editor); + var closing = ""; + if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { + closing = lang.stringRepeat("}", context.maybeInsertedBrackets); + CstyleBehaviour.clearMaybeInsertedClosing(); + } + 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 next_indent = this.$getIndent(session.getLine(openBracePos.row)); + } else if (closing) { + var next_indent = this.$getIndent(line); + } else { + CstyleBehaviour.clearMaybeInsertedClosing(); + return; + } + var indent = next_indent + session.getTabString(); + + return { + text: '\n' + indent + '\n' + next_indent + closing, + selection: [1, indent.length, 1, indent.length] + }; + } else { + CstyleBehaviour.clearMaybeInsertedClosing(); + } + }); + + this.add("braces", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '{') { + initContext(editor); + 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; + } else { + context.maybeInsertedBrackets--; + } + } + }); + + this.add("parens", "insertion", function(state, action, editor, session, text) { + if (text == '(') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '(', ')'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + CstyleBehaviour.recordAutoInsert(editor, session, ")"); + return { + text: '()', + selection: [1, 1] + }; + } + } else if (text == ')') { + initContext(editor); + 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 && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + 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 == '(') { + initContext(editor); + 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("brackets", "insertion", function(state, action, editor, session, text) { + if (text == '[') { + initContext(editor); + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, '[', ']'); + } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { + CstyleBehaviour.recordAutoInsert(editor, session, "]"); + return { + text: '[]', + selection: [1, 1] + }; + } + } else if (text == ']') { + initContext(editor); + 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 && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { + CstyleBehaviour.popAutoInsertedClosing(); + return { + text: '', + selection: [1, 1] + }; + } + } + } + }); + + this.add("brackets", "deletion", function(state, action, editor, session, range) { + var selected = session.doc.getTextRange(range); + if (!range.isMultiLine() && selected == '[') { + initContext(editor); + 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 == "'") { + if (this.lineCommentStart && this.lineCommentStart.indexOf(text) != -1) + return; + initContext(editor); + var quote = text; + var selection = editor.getSelectionRange(); + var selected = session.doc.getTextRange(selection); + if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { + return getWrapped(selection, selected, quote, quote); + } else if (!selected) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + var leftChar = line.substring(cursor.column-1, cursor.column); + var rightChar = line.substring(cursor.column, cursor.column + 1); + + var token = session.getTokenAt(cursor.row, cursor.column); + var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); + if (leftChar == "\\" && token && /escape/.test(token.type)) + return null; + + var stringBefore = token && /string|escape/.test(token.type); + var stringAfter = !rightToken || /string|escape/.test(rightToken.type); + + var pair; + if (rightChar == quote) { + pair = stringBefore !== stringAfter; + if (pair && /string\.end/.test(rightToken.type)) + pair = false; + } else { + if (stringBefore && !stringAfter) + return null; // wrap string with different quote + if (stringBefore && stringAfter) + return null; // do not pair quotes inside strings + var wordRe = session.$mode.tokenRe; + wordRe.lastIndex = 0; + var isWordBefore = wordRe.test(leftChar); + wordRe.lastIndex = 0; + var isWordAfter = wordRe.test(leftChar); + if (isWordBefore || isWordAfter) + return null; // before or after alphanumeric + if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) + return null; // there is rightChar and it isn't closing + pair = true; + } + return { + text: pair ? quote + quote : "", + 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 == "'")) { + initContext(editor); + var line = session.doc.getLine(range.start.row); + var rightChar = line.substring(range.start.column + 1, range.start.column + 2); + if (rightChar == selected) { + range.end.column++; + return range; + } + } + }); + +}; + + +CstyleBehaviour.isSaneInsertion = function(editor, session) { + var cursor = editor.getCursorPosition(); + var iterator = new TokenIterator(session, cursor.row, cursor.column); + if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { + var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); + if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) + return false; + } + iterator.stepForward(); + return iterator.getCurrentTokenRow() !== cursor.row || + this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); +}; + +CstyleBehaviour.$matchTokenType = function(token, types) { + return types.indexOf(token.type || token) > -1; +}; + +CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) + context.autoInsertedBrackets = 0; + context.autoInsertedRow = cursor.row; + context.autoInsertedLineEnd = bracket + line.substr(cursor.column); + context.autoInsertedBrackets++; +}; + +CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { + var cursor = editor.getCursorPosition(); + var line = session.doc.getLine(cursor.row); + if (!this.isMaybeInsertedClosing(cursor, line)) + context.maybeInsertedBrackets = 0; + context.maybeInsertedRow = cursor.row; + context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; + context.maybeInsertedLineEnd = line.substr(cursor.column); + context.maybeInsertedBrackets++; +}; + +CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { + return context.autoInsertedBrackets > 0 && + cursor.row === context.autoInsertedRow && + bracket === context.autoInsertedLineEnd[0] && + line.substr(cursor.column) === context.autoInsertedLineEnd; +}; + +CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { + return context.maybeInsertedBrackets > 0 && + cursor.row === context.maybeInsertedRow && + line.substr(cursor.column) === context.maybeInsertedLineEnd && + line.substr(0, cursor.column) == context.maybeInsertedLineStart; +}; + +CstyleBehaviour.popAutoInsertedClosing = function() { + context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); + context.autoInsertedBrackets--; +}; + +CstyleBehaviour.clearMaybeInsertedClosing = function() { + if (context) { + context.maybeInsertedBrackets = 0; + context.maybeInsertedRow = -1; + } +}; + + + +oop.inherits(CstyleBehaviour, Behaviour); + +exports.CstyleBehaviour = CstyleBehaviour; +}); + +ace.define("ace/unicode",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +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$&"); +} + +}); + +ace.define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour/cstyle","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Tokenizer = acequire("../tokenizer").Tokenizer; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var unicode = acequire("../unicode"); +var lang = acequire("../lib/lang"); +var TokenIterator = acequire("../token_iterator").TokenIterator; +var Range = acequire("../range").Range; + +var Mode = function() { + this.HighlightRules = TextHighlightRules; +}; + +(function() { + this.$defaultBehaviour = new CstyleBehaviour(); + + 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() { + if (!this.$tokenizer) { + this.$highlightRules = this.$highlightRules || new this.HighlightRules(this.$highlightRuleConfig); + this.$tokenizer = new Tokenizer(this.$highlightRules.getRules()); + } + return this.$tokenizer; + }; + + this.lineCommentStart = ""; + this.blockComment = ""; + + this.toggleCommentLines = function(state, session, startRow, endRow) { + var doc = session.doc; + + var ignoreBlankLines = true; + var shouldRemove = true; + var minIndent = Infinity; + var tabSize = session.getTabSize(); + var insertAtTabStop = false; + + if (!this.lineCommentStart) { + if (!this.blockComment) + return false; + var lineCommentStart = this.blockComment.start; + var lineCommentEnd = this.blockComment.end; + var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")"); + var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$"); + + var comment = function(line, i) { + if (testRemove(line, i)) + return; + if (!ignoreBlankLines || /\S/.test(line)) { + doc.insertInLine({row: i, column: line.length}, lineCommentEnd); + doc.insertInLine({row: i, column: minIndent}, lineCommentStart); + } + }; + + var uncomment = function(line, i) { + var m; + if (m = line.match(regexpEnd)) + doc.removeInLine(i, line.length - m[0].length, line.length); + if (m = line.match(regexpStart)) + doc.removeInLine(i, m[1].length, m[0].length); + }; + + var testRemove = function(line, row) { + if (regexpStart.test(line)) + return true; + var tokens = session.getTokens(row); + for (var i = 0; i < tokens.length; i++) { + if (tokens[i].type === "comment") + return true; + } + }; + } else { + if (Array.isArray(this.lineCommentStart)) { + var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|"); + var lineCommentStart = this.lineCommentStart[0]; + } else { + var regexpStart = lang.escapeRegExp(this.lineCommentStart); + var lineCommentStart = this.lineCommentStart; + } + regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?"); + + insertAtTabStop = session.getUseSoftTabs(); + + var uncomment = function(line, i) { + var m = line.match(regexpStart); + if (!m) return; + var start = m[1].length, end = m[0].length; + if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ") + end--; + doc.removeInLine(i, start, end); + }; + var commentWithSpace = lineCommentStart + " "; + var comment = function(line, i) { + if (!ignoreBlankLines || /\S/.test(line)) { + if (shouldInsertSpace(line, minIndent, minIndent)) + doc.insertInLine({row: i, column: minIndent}, commentWithSpace); + else + doc.insertInLine({row: i, column: minIndent}, lineCommentStart); + } + }; + var testRemove = function(line, i) { + return regexpStart.test(line); + }; + + var shouldInsertSpace = function(line, before, after) { + var spaces = 0; + while (before-- && line.charAt(before) == " ") + spaces++; + if (spaces % tabSize != 0) + return false; + var spaces = 0; + while (line.charAt(after++) == " ") + spaces++; + if (tabSize > 2) + return spaces % tabSize != tabSize - 1; + else + return spaces % tabSize == 0; + return true; + }; + } + + function iter(fun) { + for (var i = startRow; i <= endRow; i++) + fun(doc.getLine(i), i); + } + + + var minEmptyLength = Infinity; + iter(function(line, i) { + var indent = line.search(/\S/); + if (indent !== -1) { + if (indent < minIndent) + minIndent = indent; + if (shouldRemove && !testRemove(line, i)) + shouldRemove = false; + } else if (minEmptyLength > line.length) { + minEmptyLength = line.length; + } + }); + + if (minIndent == Infinity) { + minIndent = minEmptyLength; + ignoreBlankLines = false; + shouldRemove = false; + } + + if (insertAtTabStop && minIndent % tabSize != 0) + minIndent = Math.floor(minIndent / tabSize) * tabSize; + + iter(shouldRemove ? uncomment : comment); + }; + + this.toggleBlockComment = function(state, session, range, cursor) { + var comment = this.blockComment; + if (!comment) + return; + if (!comment.start && comment[0]) + comment = comment[0]; + + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + + var sel = session.selection; + var initialRange = session.selection.toOrientedRange(); + var startRow, colDiff; + + if (token && /comment/.test(token.type)) { + var startRange, endRange; + while (token && /comment/.test(token.type)) { + var i = token.value.indexOf(comment.start); + if (i != -1) { + var row = iterator.getCurrentTokenRow(); + var column = iterator.getCurrentTokenColumn() + i; + startRange = new Range(row, column, row, column + comment.start.length); + break; + } + token = iterator.stepBackward(); + } + + var iterator = new TokenIterator(session, cursor.row, cursor.column); + var token = iterator.getCurrentToken(); + while (token && /comment/.test(token.type)) { + var i = token.value.indexOf(comment.end); + if (i != -1) { + var row = iterator.getCurrentTokenRow(); + var column = iterator.getCurrentTokenColumn() + i; + endRange = new Range(row, column, row, column + comment.end.length); + break; + } + token = iterator.stepForward(); + } + if (endRange) + session.remove(endRange); + if (startRange) { + session.remove(startRange); + startRow = startRange.start.row; + colDiff = -comment.start.length; + } + } else { + colDiff = comment.start.length; + startRow = range.start.row; + session.insert(range.end, comment.end); + session.insert(range.start, comment.start); + } + if (initialRange.start.row == startRow) + initialRange.start.column += colDiff; + if (initialRange.end.row == startRow) + initialRange.end.column += colDiff; + session.selection.fromOrientedRange(initialRange); + }; + + this.getNextLineIndent = function(state, line, tab) { + return this.$getIndent(line); + }; + + this.checkOutdent = function(state, line, input) { + return false; + }; + + this.autoOutdent = function(state, doc, row) { + }; + + this.$getIndent = function(line) { + return line.match(/^\s*/)[0]; + }; + + this.createWorker = function(session) { + return null; + }; + + this.createModeDelegates = function (mapping) { + this.$embeds = []; + this.$modes = {}; + for (var i in mapping) { + if (mapping[i]) { + this.$embeds.push(i); + this.$modes[i] = new mapping[i](); + } + } + + var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent", + "checkOutdent", "autoOutdent", "transformAction", "getCompletions"]; + + 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]; + if (typeof state != "string") + state = state[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; + } + } + } + } + }; + + this.getKeywords = function(append) { + if (!this.completionKeywords) { + var rules = this.$tokenizer.rules; + var completionKeywords = []; + for (var rule in rules) { + var ruleItr = rules[rule]; + for (var r = 0, l = ruleItr.length; r < l; r++) { + if (typeof ruleItr[r].token === "string") { + if (/keyword|support|storage/.test(ruleItr[r].token)) + completionKeywords.push(ruleItr[r].regex); + } + else if (typeof ruleItr[r].token === "object") { + for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) { + if (/keyword|support|storage/.test(ruleItr[r].token[a])) { + var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a]; + completionKeywords.push(rule.substr(1, rule.length - 2)); + } + } + } + } + } + this.completionKeywords = completionKeywords; + } + if (!append) + return this.$keywordList; + return completionKeywords.concat(this.$keywordList || []); + }; + + this.$createKeywordList = function() { + if (!this.$highlightRules) + this.getTokenizer(); + return this.$keywordList = this.$highlightRules.$keywordList || []; + }; + + this.getCompletions = function(state, session, pos, prefix) { + var keywords = this.$keywordList || this.$createKeywordList(); + return keywords.map(function(word) { + return { + name: word, + value: word, + score: 0, + meta: "keyword" + }; + }); + }; + + this.$id = "ace/mode/text"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + +ace.define("ace/apply_delta",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +function throwDeltaError(delta, errorText){ + console.log("Invalid Delta:", delta); + throw "Invalid Delta: " + errorText; +} + +function positionInDocument(docLines, position) { + return position.row >= 0 && position.row < docLines.length && + position.column >= 0 && position.column <= docLines[position.row].length; +} + +function validateDelta(docLines, delta) { + if (delta.action != "insert" && delta.action != "remove") + throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); + if (!(delta.lines instanceof Array)) + throwDeltaError(delta, "delta.lines must be an Array"); + if (!delta.start || !delta.end) + throwDeltaError(delta, "delta.start/end must be an present"); + var start = delta.start; + if (!positionInDocument(docLines, delta.start)) + throwDeltaError(delta, "delta.start must be contained in document"); + var end = delta.end; + if (delta.action == "remove" && !positionInDocument(docLines, end)) + throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); + var numRangeRows = end.row - start.row; + var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); + if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) + throwDeltaError(delta, "delta.range must match delta lines"); +} + +exports.applyDelta = function(docLines, delta, doNotValidate) { + + var row = delta.start.row; + var startColumn = delta.start.column; + var line = docLines[row] || ""; + switch (delta.action) { + case "insert": + var lines = delta.lines; + if (lines.length === 1) { + docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); + } else { + var args = [row, 1].concat(delta.lines); + docLines.splice.apply(docLines, args); + docLines[row] = line.substring(0, startColumn) + docLines[row]; + docLines[row + delta.lines.length - 1] += line.substring(startColumn); + } + break; + case "remove": + var endColumn = delta.end.column; + var endRow = delta.end.row; + if (row === endRow) { + docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); + } else { + docLines.splice( + row, endRow - row + 1, + line.substring(0, startColumn) + docLines[endRow].substring(endColumn) + ); + } + break; + } +} +}); + +ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; + +var Anchor = exports.Anchor = function(doc, row, column) { + this.$onChange = this.onChange.bind(this); + this.attach(doc); + + if (typeof column == "undefined") + this.setPosition(row.row, row.column); + else + this.setPosition(row, column); +}; + +(function() { + + oop.implement(this, EventEmitter); + this.getPosition = function() { + return this.$clipPositionToDocument(this.row, this.column); + }; + this.getDocument = function() { + return this.document; + }; + this.$insertRight = false; + this.onChange = function(delta) { + if (delta.start.row == delta.end.row && delta.start.row != this.row) + return; + + if (delta.start.row > this.row) + return; + + var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); + this.setPosition(point.row, point.column, true); + }; + + function $pointsInOrder(point1, point2, equalPointsInOrder) { + var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; + return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); + } + + function $getTransformedPoint(delta, point, moveIfEqual) { + var deltaIsInsert = delta.action == "insert"; + var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); + var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); + var deltaStart = delta.start; + var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. + if ($pointsInOrder(point, deltaStart, moveIfEqual)) { + return { + row: point.row, + column: point.column + }; + } + if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { + return { + row: point.row + deltaRowShift, + column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) + }; + } + + return { + row: deltaStart.row, + column: deltaStart.column + }; + } + this.setPosition = function(row, column, noClip) { + var pos; + if (noClip) { + pos = { + row: row, + column: column + }; + } else { + pos = this.$clipPositionToDocument(row, column); + } + + if (this.row == pos.row && this.column == pos.column) + return; + + var old = { + row: this.row, + column: this.column + }; + + this.row = pos.row; + this.column = pos.column; + this._signal("change", { + old: old, + value: pos + }); + }; + this.detach = function() { + this.document.removeEventListener("change", this.$onChange); + }; + this.attach = function(doc) { + this.document = doc || this.document; + this.document.on("change", this.$onChange); + }; + this.$clipPositionToDocument = function(row, column) { + var pos = {}; + + if (row >= this.document.getLength()) { + pos.row = Math.max(0, this.document.getLength() - 1); + pos.column = this.document.getLine(pos.row).length; + } + else if (row < 0) { + pos.row = 0; + pos.column = 0; + } + else { + pos.row = row; + pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); + } + + if (column < 0) + pos.column = 0; + + return pos; + }; + +}).call(Anchor.prototype); + +}); + +ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var applyDelta = acequire("./apply_delta").applyDelta; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Range = acequire("./range").Range; +var Anchor = acequire("./anchor").Anchor; + +var Document = function(textOrLines) { + this.$lines = [""]; + if (textOrLines.length === 0) { + this.$lines = [""]; + } else if (Array.isArray(textOrLines)) { + this.insertMergedLines({row: 0, column: 0}, textOrLines); + } else { + this.insert({row: 0, column:0}, textOrLines); + } +}; + +(function() { + + oop.implement(this, EventEmitter); + this.setValue = function(text) { + var len = this.getLength() - 1; + this.remove(new Range(0, 0, len, this.getLine(len).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); + }; + 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); + this.$autoNewLine = match ? match[1] : "\n"; + this._signal("changeNewLineMode"); + }; + this.getNewLineCharacter = function() { + switch (this.$newLineMode) { + case "windows": + return "\r\n"; + case "unix": + return "\n"; + default: + return this.$autoNewLine || "\n"; + } + }; + + this.$autoNewLine = ""; + this.$newLineMode = "auto"; + this.setNewLineMode = function(newLineMode) { + if (this.$newLineMode === newLineMode) + return; + + this.$newLineMode = newLineMode; + this._signal("changeNewLineMode"); + }; + 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) { + return this.getLinesForRange(range).join(this.getNewLineCharacter()); + }; + this.getLinesForRange = function(range) { + var lines; + if (range.start.row === range.end.row) { + lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; + } else { + lines = this.getLines(range.start.row, range.end.row); + lines[0] = (lines[0] || "").substring(range.start.column); + var l = lines.length - 1; + if (range.end.row - range.start.row == l) + lines[l] = lines[l].substring(0, range.end.column); + } + return lines; + }; + this.insertLines = function(row, lines) { + console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); + return this.insertFullLines(row, lines); + }; + this.removeLines = function(firstRow, lastRow) { + console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); + return this.removeFullLines(firstRow, lastRow); + }; + this.insertNewLine = function(position) { + console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); + return this.insertMergedLines(position, ["", ""]); + }; + this.insert = function(position, text) { + if (this.getLength() <= 1) + this.$detectNewLine(text); + + return this.insertMergedLines(position, this.$split(text)); + }; + this.insertInLine = function(position, text) { + var start = this.clippedPos(position.row, position.column); + var end = this.pos(position.row, position.column + text.length); + + this.applyDelta({ + start: start, + end: end, + action: "insert", + lines: [text] + }, true); + + return this.clonePos(end); + }; + + this.clippedPos = function(row, column) { + var length = this.getLength(); + if (row === undefined) { + row = length; + } else if (row < 0) { + row = 0; + } else if (row >= length) { + row = length - 1; + column = undefined; + } + var line = this.getLine(row); + if (column == undefined) + column = line.length; + column = Math.min(Math.max(column, 0), line.length); + return {row: row, column: column}; + }; + + this.clonePos = function(pos) { + return {row: pos.row, column: pos.column}; + }; + + this.pos = function(row, column) { + return {row: row, column: column}; + }; + + 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; + } else { + position.row = Math.max(0, position.row); + position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); + } + return position; + }; + this.insertFullLines = function(row, lines) { + row = Math.min(Math.max(row, 0), this.getLength()); + var column = 0; + if (row < this.getLength()) { + lines = lines.concat([""]); + column = 0; + } else { + lines = [""].concat(lines); + row--; + column = this.$lines[row].length; + } + this.insertMergedLines({row: row, column: column}, lines); + }; + this.insertMergedLines = function(position, lines) { + var start = this.clippedPos(position.row, position.column); + var end = { + row: start.row + lines.length - 1, + column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length + }; + + this.applyDelta({ + start: start, + end: end, + action: "insert", + lines: lines + }); + + return this.clonePos(end); + }; + this.remove = function(range) { + var start = this.clippedPos(range.start.row, range.start.column); + var end = this.clippedPos(range.end.row, range.end.column); + this.applyDelta({ + start: start, + end: end, + action: "remove", + lines: this.getLinesForRange({start: start, end: end}) + }); + return this.clonePos(start); + }; + this.removeInLine = function(row, startColumn, endColumn) { + var start = this.clippedPos(row, startColumn); + var end = this.clippedPos(row, endColumn); + + this.applyDelta({ + start: start, + end: end, + action: "remove", + lines: this.getLinesForRange({start: start, end: end}) + }, true); + + return this.clonePos(start); + }; + this.removeFullLines = function(firstRow, lastRow) { + firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); + lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); + var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; + var deleteLastNewLine = lastRow < this.getLength() - 1; + var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); + var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); + var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); + var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); + var range = new Range(startRow, startCol, endRow, endCol); + var deletedLines = this.$lines.slice(firstRow, lastRow + 1); + + this.applyDelta({ + start: range.start, + end: range.end, + action: "remove", + lines: this.getLinesForRange(range) + }); + return deletedLines; + }; + this.removeNewLine = function(row) { + if (row < this.getLength() - 1 && row >= 0) { + this.applyDelta({ + start: this.pos(row, this.getLine(row).length), + end: this.pos(row + 1, 0), + action: "remove", + lines: ["", ""] + }); + } + }; + this.replace = function(range, text) { + if (!(range instanceof Range)) + range = Range.fromPoints(range.start, range.end); + if (text.length === 0 && range.isEmpty()) + return range.start; + if (text == this.getTextRange(range)) + return range.end; + + this.remove(range); + var end; + if (text) { + end = this.insert(range.start, text); + } + else { + end = range.start; + } + + return end; + }; + this.applyDeltas = function(deltas) { + for (var i=0; i=0; i--) { + this.revertDelta(deltas[i]); + } + }; + this.applyDelta = function(delta, doNotValidate) { + var isInsert = delta.action == "insert"; + if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] + : !Range.comparePoints(delta.start, delta.end)) { + return; + } + + if (isInsert && delta.lines.length > 20000) + this.$splitAndapplyLargeDelta(delta, 20000); + applyDelta(this.$lines, delta, doNotValidate); + this._signal("change", delta); + }; + + this.$splitAndapplyLargeDelta = function(delta, MAX) { + var lines = delta.lines; + var l = lines.length; + var row = delta.start.row; + var column = delta.start.column; + var from = 0, to = 0; + do { + from = to; + to += MAX - 1; + var chunk = lines.slice(from, to); + if (to > l) { + delta.lines = chunk; + delta.start.row = row + from; + delta.start.column = column; + break; + } + chunk.push(""); + this.applyDelta({ + start: this.pos(row + from, column), + end: this.pos(row + to, column = 0), + action: delta.action, + lines: chunk + }, true); + } while(true); + }; + this.revertDelta = function(delta) { + this.applyDelta({ + start: this.clonePos(delta.start), + end: this.clonePos(delta.end), + action: (delta.action == "insert" ? "remove" : "insert"), + lines: delta.lines.slice() + }); + }; + this.indexToPosition = function(index, startRow) { + var lines = this.$lines || this.getAllLines(); + var newlineLength = this.getNewLineCharacter().length; + for (var i = startRow || 0, l = lines.length; i < l; i++) { + index -= lines[i].length + newlineLength; + if (index < 0) + return {row: i, column: index + lines[i].length + newlineLength}; + } + return {row: l-1, column: lines[l-1].length}; + }; + this.positionToIndex = function(pos, startRow) { + var lines = this.$lines || this.getAllLines(); + var newlineLength = this.getNewLineCharacter().length; + var index = 0; + var row = Math.min(pos.row, lines.length); + for (var i = startRow || 0; i < row; ++i) + index += lines[i].length + newlineLength; + + return index + pos.column; + }; + +}).call(Document.prototype); + +exports.Document = Document; +}); + +ace.define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; + +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 currentLine = self.currentLine; + var endLine = -1; + var doc = self.doc; + + var startLine = currentLine; + while (self.lines[currentLine]) + currentLine++; + + var len = doc.getLength(); + var processedLines = 0; + self.running = false; + while (currentLine < len) { + self.$tokenizeRow(currentLine); + endLine = currentLine; + do { + currentLine++; + } while (self.lines[currentLine]); + processedLines ++; + if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) { + self.running = setTimeout(self.$worker, 20); + break; + } + } + self.currentLine = currentLine; + + if (startLine <= endLine) + self.fireUpdateEvent(startLine, endLine); + }; +}; + +(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._signal("update", {data: data}); + }; + this.start = function(startRow) { + this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength()); + this.lines.splice(this.currentLine, this.lines.length); + this.states.splice(this.currentLine, this.states.length); + + this.stop(); + this.running = setTimeout(this.$worker, 700); + }; + + this.scheduleStart = function() { + if (!this.running) + this.running = setTimeout(this.$worker, 700); + } + + this.$updateOnChange = function(delta) { + var startRow = delta.start.row; + var len = delta.end.row - startRow; + + if (len === 0) { + this.lines[startRow] = null; + } else if (delta.action == "remove") { + 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(); + }; + 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]; + + var data = this.tokenizer.getLineTokens(line, state, row); + + 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; +}); + +ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("./lib/lang"); +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; + +var SearchHighlight = function(regExp, clazz, type) { + this.setRegexp(regExp); + this.clazz = clazz; + this.type = type || "text"; +}; + +(function() { + this.MAX_RANGES = 500; + + 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); + if (ranges.length > this.MAX_RANGES) + ranges = ranges.slice(0, this.MAX_RANGES); + 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); + } + } + }; + +}).call(SearchHighlight.prototype); + +exports.SearchHighlight = SearchHighlight; +}); + +ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../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() { + 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 new Error("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 new Error("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, + cmp, 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]; + + cmp = fold.range.compareStart(endRow, endColumn); + if (cmp == -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 (stop || cmp === 0) { + return; + } + 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) + { + 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 pos = this.getNextFoldTo(row, column); + + if (!pos || pos.kind == "inside") + return null; + + var fold = pos.fold; + var folds = this.folds; + var foldData = this.foldData; + + var i = folds.indexOf(fold); + var foldBefore = folds[i - 1]; + this.end.row = foldBefore.end.row; + this.end.column = foldBefore.end.column; + 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]); + } + 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; + + 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; +}); + +ace.define("ace/range_list",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; +var Range = acequire("./range").Range; +var comparePoints = Range.comparePoints; + +var RangeList = function() { + this.ranges = []; +}; + +(function() { + this.comparePoints = comparePoints; + + this.pointIndex = function(pos, excludeEdges, startIndex) { + var list = this.ranges; + + for (var i = startIndex || 0; i < list.length; i++) { + var range = list[i]; + var cmpEnd = comparePoints(pos, range.end); + if (cmpEnd > 0) + continue; + var cmpStart = comparePoints(pos, range.start); + if (cmpEnd === 0) + return excludeEdges && cmpStart !== 0 ? -i-2 : i; + if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges)) + return i; + + return -i-1; + } + return -i - 1; + }; + + this.add = function(range) { + var excludeEdges = !range.isEmpty(); + var startIndex = this.pointIndex(range.start, excludeEdges); + if (startIndex < 0) + startIndex = -startIndex - 1; + + var endIndex = this.pointIndex(range.end, excludeEdges, 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.apply(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); + }; + this.merge = function() { + var removed = []; + var list = this.ranges; + + list = list.sort(function(a, b) { + return comparePoints(a.start, b.start); + }); + + var next = list[0], range; + for (var i = 1; i < list.length; i++) { + range = next; + next = list[i]; + var cmp = comparePoints(range.end, next.start); + if (cmp < 0) + continue; + + if (cmp == 0 && !range.isEmpty() && !next.isEmpty()) + continue; + + if (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--; + } + + this.ranges = list; + + 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(delta) { + if (delta.action == "insert"){ + var start = delta.start; + var end = delta.end; + } else { + var end = delta.start; + var start = delta.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 ) { + if (r.start.column == start.column && this.$insertRight) { + } else { + r.start.column += colDiff; + r.start.row += lineDif; + } + } + if (r.end.row == startRow && r.end.column >= start.column) { + if (r.end.column == start.column && this.$insertRight) { + continue; + } + if (r.end.column == start.column && colDiff > 0 && i < n - 1) { + if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column) + r.end.column -= colDiff; + } + 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; +}); + +ace.define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var RangeList = acequire("../range_list").RangeList; +var oop = acequire("../lib/oop") +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 = this.ranges = []; +}; + +oop.inherits(Fold, RangeList); + +(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()); + }); + fold.collapseChildren = this.collapseChildren; + return fold; + }; + + this.addSubFold = function(fold) { + if (this.range.isEqual(fold)) + return; + + if (!this.range.containsRange(fold)) + throw new Error("A fold can't intersect already existing fold" + fold.range + this.range); + consumeRange(fold, this.start); + + var row = fold.start.row, column = fold.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); + 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 new Error("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; + }; + + this.restoreRange = function(range) { + return restoreRange(range, this.start); + }; + +}).call(Fold.prototype); + +function consumePoint(point, anchor) { + point.row -= anchor.row; + if (point.row == 0) + point.column -= anchor.column; +} +function consumeRange(range, anchor) { + consumePoint(range.start, anchor); + consumePoint(range.end, anchor); +} +function restorePoint(point, anchor) { + if (point.row == 0) + point.column += anchor.column; + point.row += anchor.row; +} +function restoreRange(range, anchor) { + restorePoint(range.start, anchor); + restorePoint(range.end, anchor); +} + +}); + +ace.define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var FoldLine = acequire("./fold_line").FoldLine; +var Fold = acequire("./fold").Fold; +var TokenIterator = acequire("../token_iterator").TokenIterator; + +function Folding() { + 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) { + 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) { + continue; + } + else if (cmp == -2) { + 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 + if (cmp == 42) { + break; + } + foundFolds.push(fold); + } + } + start.column -= 1; + end.column += 1; + + return foundFolds; + }; + + this.getFoldsInRangeList = function(ranges) { + if (Array.isArray(ranges)) { + var folds = []; + ranges.forEach(function(range) { + folds = folds.concat(this.getFoldsInRange(range)); + }, this); + } else { + var folds = this.getFoldsInRange(ranges); + } + return folds; + }; + this.getAllFolds = function() { + var folds = []; + var foldLines = this.$foldData; + + for (var i = 0; i < foldLines.length; i++) + for (var j = 0; j < foldLines[i].folds.length; j++) + folds.push(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 } + }; + 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; + }; + 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); + fold.collapseChildren = range.collapseChildren; + } + this.$clipRangeToDocument(fold.range); + + var startRow = fold.start.row; + var startColumn = fold.start.column; + var endRow = fold.end.row; + var endColumn = fold.end.column; + if (!(startRow < endRow || + startRow == endRow && startColumn <= endColumn - 2)) + throw new Error("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)) + this.removeFold(startFold); + + if (endFold && !endFold.range.isEnd(endRow, endColumn)) + this.removeFold(endFold); + var folds = this.getFoldsInRange(fold.range); + if (folds.length > 0) { + this.removeFolds(folds); + folds.forEach(function(subFold) { + fold.addSubFold(subFold); + }); + } + + 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) { + var foldLineNext = foldData[i + 1]; + if (foldLineNext && foldLineNext.start.row == endRow) { + 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); + this.$modified = true; + this._signal("changeFold", { data: fold, action: "add" }); + + 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; + if (folds.length == 1) { + foldLines.splice(foldLines.indexOf(foldLine), 1); + } else + 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 (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 + if (fold.sameRow) { + folds.splice(folds.indexOf(fold), 1); + } else + { + 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.$updating) { + if (this.$useWrapMode) + this.$updateWrapData(startRow, endRow); + else + this.$updateRowLengthCache(startRow, endRow); + } + this.$modified = true; + this._signal("changeFold", { data: fold, action: "remove" }); + }; + + this.removeFolds = function(folds) { + 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(subFold) { + fold.restoreRange(subFold); + this.addFold(subFold); + }, this); + if (fold.collapseChildren > 0) { + this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1); + } + 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); + expandInner = true; + } 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.getFoldsInRangeList(range); + if (expandInner) { + this.removeFolds(folds); + } else { + var subFolds = folds; + while (subFolds.length) { + this.expandFolds(subFolds); + subFolds = this.getFoldsInRangeList(range); + } + } + if (folds.length) + return folds; + }; + 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.getRowFoldStart = function(docRow, startFoldRow) { + var foldLine = this.getFoldLine(docRow, startFoldRow); + return foldLine ? foldLine.start.row : docRow; + }; + + this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) { + if (startRow == null) + startRow = foldLine.start.row; + if (startColumn == null) + startColumn = 0; + if (endRow == null) + endRow = foldLine.end.row; + if (endColumn == null) + endColumn = this.getLine(endRow).length; + var doc = this.doc; + var textLine = ""; + + foldLine.walk(function(placeholder, row, column, lastColumn) { + if (row < startRow) + return; + if (row == startRow) { + if (column < startColumn) + return; + lastColumn = Math.max(startColumn, lastColumn); + } + + if (placeholder != null) { + textLine += placeholder; + } else { + textLine += doc.getLine(row).substring(lastColumn, column); + } + }, 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, dir) { + 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(/\..*/, "\\.")); + if (dir != 1) { + 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); + + if (dir != -1) { + do { + token = iterator.stepForward(); + } while (token && re.test(token.type)); + token = iterator.stepBackward(); + } else + token = iterator.getCurrentToken(); + + range.end.row = iterator.getCurrentTokenRow(); + range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2; + return range; + } + }; + + this.foldAll = function(startRow, endRow, depth) { + if (depth == undefined) + depth = 100000; // JSON.stringify doesn't hanle Infinity + var foldWidgets = this.foldWidgets; + if (!foldWidgets) + return; // mode doesn't support folding + endRow = endRow || this.getLength(); + startRow = startRow || 0; + for (var row = startRow; row < endRow; row++) { + if (foldWidgets[row] == null) + foldWidgets[row] = this.getFoldWidget(row); + if (foldWidgets[row] != "start") + continue; + + var range = this.getFoldWidgetRange(row); + if (range && range.isMultiLine() + && range.end.row <= endRow + && range.start.row >= startRow + ) { + row = range.end.row; + try { + var fold = this.addFold("...", range); + if (fold) + fold.collapseChildren = depth; + } 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(); + var mode = this.$foldMode; + this.$setFolding(null); + this.$setFolding(mode); + }; + + this.$setFolding = function(foldMode) { + if (this.$foldMode == foldMode) + return; + + this.$foldMode = foldMode; + + this.off('change', this.$updateFoldWidgets); + this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); + this._signal("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.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this); + this.on('change', this.$updateFoldWidgets); + this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); + }; + + this.getParentFoldRangeData = function (row, ignoreCurrent) { + var fw = this.foldWidgets; + if (!fw || (ignoreCurrent && fw[row])) + return {}; + + var i = row - 1, firstRange; + while (i >= 0) { + var c = fw[i]; + if (c == null) + c = fw[i] = this.getFoldWidget(i); + + if (c == "start") { + var range = this.getFoldWidgetRange(i); + if (!firstRange) + firstRange = range; + if (range && range.end.row >= row) + break; + } + i--; + } + + return { + range: i !== -1 && range, + firstRange: firstRange + }; + }; + + this.onFoldWidgetClick = function(row, e) { + e = e.domEvent; + var options = { + children: e.shiftKey, + all: e.ctrlKey || e.metaKey, + siblings: e.altKey + }; + + var range = this.$toggleFoldWidget(row, options); + if (!range) { + var el = (e.target || e.srcElement); + if (el && /ace_fold-widget/.test(el.className)) + el.className += " ace_invalid"; + } + }; + + this.$toggleFoldWidget = function(row, options) { + if (!this.getFoldWidget) + return; + var type = this.getFoldWidget(row); + var line = this.getLine(row); + + var dir = type === "end" ? -1 : 1; + var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir); + + if (fold) { + if (options.children || options.all) + this.removeFold(fold); + else + this.expandFold(fold); + return fold; + } + + var range = this.getFoldWidgetRange(row, true); + if (range && !range.isMultiLine()) { + fold = this.getFoldAt(range.start.row, range.start.column, 1); + if (fold && range.isEqual(fold.range)) { + this.removeFold(fold); + return fold; + } + } + + if (options.siblings) { + var data = this.getParentFoldRangeData(row); + if (data.range) { + var startRow = data.range.start.row + 1; + var endRow = data.range.end.row; + } + this.foldAll(startRow, endRow, options.all ? 10000 : 0); + } else if (options.children) { + endRow = range ? range.end.row : this.getLength(); + this.foldAll(row + 1, endRow, options.all ? 10000 : 0); + } else if (range) { + if (options.all) + range.collapseChildren = 10000; + this.addFold("...", range); + } + + return range; + }; + + + + this.toggleFoldWidget = function(toggleParent) { + var row = this.selection.getCursor().row; + row = this.getRowFoldStart(row); + var range = this.$toggleFoldWidget(row, {}); + + if (range) + return; + var data = this.getParentFoldRangeData(row, true); + range = data.range || data.firstRange; + + if (range) { + row = range.start.row; + var fold = this.getFoldAt(row, this.getLine(row).length, 1); + + if (fold) { + this.removeFold(fold); + } else { + this.addFold("...", range); + } + } + }; + + this.updateFoldWidgets = function(delta) { + var firstRow = delta.start.row; + var len = delta.end.row - firstRow; + + if (len === 0) { + this.foldWidgets[firstRow] = null; + } else if (delta.action == 'remove') { + this.foldWidgets.splice(firstRow, len + 1, null); + } else { + var args = Array(len + 1); + args.unshift(firstRow, 1); + this.foldWidgets.splice.apply(this.foldWidgets, args); + } + }; + this.tokenizerUpdateFoldWidgets = function(e) { + var rows = e.data; + if (rows.first != rows.last) { + if (this.foldWidgets.length > rows.first) + this.foldWidgets.splice(rows.first, this.foldWidgets.length); + } + }; +} + +exports.Folding = Folding; + +}); + +ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(acequire, exports, module) { +"use strict"; + +var TokenIterator = acequire("../token_iterator").TokenIterator; +var Range = acequire("../range").Range; + + +function BracketMatch() { + + this.findMatchingBracket = function(position, chr) { + if (position.column == 0) return null; + + var charBeforeCursor = chr || 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.getBracketRange = function(pos) { + var line = this.getLine(pos.row); + var before = true, range; + + var chr = line.charAt(pos.column-1); + var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); + if (!match) { + chr = line.charAt(pos.column); + pos = {row: pos.row, column: pos.column + 1}; + match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); + before = false; + } + if (!match) + return null; + + if (match[1]) { + var bracketPos = this.$findClosingBracket(match[1], pos); + if (!bracketPos) + return null; + range = Range.fromPoints(pos, bracketPos); + if (!before) { + range.end.column++; + range.start.column--; + } + range.cursor = range.end; + } else { + var bracketPos = this.$findOpeningBracket(match[2], pos); + if (!bracketPos) + return null; + range = Range.fromPoints(bracketPos, pos); + if (!before) { + range.start.column++; + range.end.column--; + } + range.cursor = range.start; + } + + return range; + }; + + 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") + .replace(/\b(?:end)\b/, "(?:start|begin|end)") + + ")+" + ); + } + 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; + } + 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) { + 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") + .replace(/\b(?:start|begin)\b/, "(?:start|begin|end)") + + ")+" + ); + } + 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; + } + do { + token = iterator.stepForward(); + } while (token && !typeRe.test(token.type)); + + if (token == null) + break; + + valueIndex = 0; + } + + return null; + }; +} +exports.BracketMatch = BracketMatch; + +}); + +ace.define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/config","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(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var lang = acequire("./lib/lang"); +var config = acequire("./config"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var Selection = acequire("./selection").Selection; +var TextMode = acequire("./mode/text").Mode; +var Range = acequire("./range").Range; +var Document = acequire("./document").Document; +var BackgroundTokenizer = acequire("./background_tokenizer").BackgroundTokenizer; +var SearchHighlight = acequire("./search_highlight").SearchHighlight; + +var EditSession = function(text, mode) { + this.$breakpoints = []; + this.$decorations = []; + this.$frontMarkers = {}; + this.$backMarkers = {}; + this.$markerId = 1; + this.$undoSelect = true; + + this.$foldData = []; + this.id = "session" + (++EditSession.$uid); + this.$foldData.toString = function() { + return this.join("\n"); + }; + this.on("changeFold", this.onChangeFold.bind(this)); + this.$onChange = this.onChange.bind(this); + + if (typeof text != "object" || !text.getLine) + text = new Document(text); + + this.setDocument(text); + this.selection = new Selection(this); + + config.resetOptions(this); + this.setMode(mode); + config._signal("session", this); +}; + + +(function() { + + oop.implement(this, EventEmitter); + this.setDocument = function(doc) { + if (this.doc) + this.doc.removeListener("change", this.$onChange); + + this.doc = doc; + doc.on("change", this.$onChange); + + if (this.bgTokenizer) + this.bgTokenizer.setDocument(this.getDocument()); + + this.resetCaches(); + }; + this.getDocument = function() { + return this.doc; + }; + this.$resetRowCache = function(docRow) { + if (!docRow) { + this.$docRowCache = []; + this.$screenRowCache = []; + return; + } + var l = this.$docRowCache.length; + var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1; + if (l > i) { + 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 -1; + }; + + this.resetCaches = function() { + this.$modified = true; + this.$wrapData = []; + this.$rowLengthCache = []; + this.$resetRowCache(0); + if (this.bgTokenizer) + this.bgTokenizer.start(0); + }; + + this.onChangeFold = function(e) { + var fold = e.data; + this.$resetRowCache(fold.start.row); + }; + + this.onChange = function(delta) { + this.$modified = true; + + this.$resetRowCache(delta.start.row); + + var removedFolds = this.$updateInternalDataOnChange(delta); + 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 && this.bgTokenizer.$updateOnChange(delta); + this._signal("change", delta); + }; + this.setValue = function(text) { + this.doc.setValue(text); + this.selection.moveTo(0, 0); + + this.$resetRowCache(0); + this.$deltas = []; + this.$deltasDoc = []; + this.$deltasFold = []; + this.setUndoManager(this.$undoManager); + this.getUndoManager().reset(); + }; + 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.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], + merge: self.mergeUndoDeltas + }); + } + self.mergeUndoDeltas = false; + self.$deltas = []; + }; + this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager); + } + }; + this.markUndoGroup = function() { + if (this.$syncInformUndoManager) + this.$syncInformUndoManager(); + }; + + this.$defaultUndoManager = { + undo: function() {}, + redo: function() {}, + reset: function() {} + }; + this.getUndoManager = function() { + return this.$undoManager || this.$defaultUndoManager; + }; + this.getTabString = function() { + if (this.getUseSoftTabs()) { + return lang.stringRepeat(" ", this.getTabSize()); + } else { + return "\t"; + } + }; + this.setUseSoftTabs = function(val) { + this.setOption("useSoftTabs", val); + }; + this.getUseSoftTabs = function() { + return this.$useSoftTabs && !this.$mode.$indentWithTabs; + }; + this.setTabSize = function(tabSize) { + this.setOption("tabSize", tabSize); + }; + 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) { + this.setOption("overwrite", overwrite); + }; + this.getOverwrite = function() { + return this.$overwrite; + }; + this.toggleOverwrite = function() { + this.setOverwrite(!this.$overwrite); + }; + this.addGutterDecoration = function(row, className) { + if (!this.$decorations[row]) + this.$decorations[row] = ""; + this.$decorations[row] += " " + className; + this._signal("changeBreakpoint", {}); + }; + this.removeGutterDecoration = function(row, className) { + this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, ""); + this._signal("changeBreakpoint", {}); + }; + this.getBreakpoints = function() { + return this.$breakpoints; + }; + this.setBreakpoints = function(rows) { + this.$breakpoints = []; + for (var i=0; i 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.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); }; + this.getUseWorker = function() { return this.$useWorker; }; + this.onReloadTokenizer = function(e) { + var rows = e.data; + this.bgTokenizer.start(rows.first); + this._signal("tokenizerUpdate", e); + }; + + this.$modes = {}; + this.$mode = null; + this.$modeId = null; + this.setMode = function(mode, cb) { + if (mode && typeof mode === "object") { + if (mode.getTokenizer) + return this.$onChangeMode(mode); + var options = mode; + var path = options.path; + } else { + path = mode || "ace/mode/text"; + } + if (!this.$modes["ace/mode/text"]) + this.$modes["ace/mode/text"] = new TextMode(); + + if (this.$modes[path] && !options) { + this.$onChangeMode(this.$modes[path]); + cb && cb(); + return; + } + this.$modeId = path; + config.loadModule(["mode", path], function(m) { + if (this.$modeId !== path) + return cb && cb(); + if (this.$modes[path] && !options) { + this.$onChangeMode(this.$modes[path]); + } else if (m && m.Mode) { + m = new m.Mode(options); + if (!options) { + this.$modes[path] = m; + m.$id = path; + } + this.$onChangeMode(m); + } + cb && cb(); + }.bind(this)); + if (!this.$mode) + this.$onChangeMode(this.$modes["ace/mode/text"], true); + }; + + this.$onChangeMode = function(mode, $isPlaceholder) { + if (!$isPlaceholder) + this.$modeId = mode.$id; + if (this.$mode === mode) + return; + + this.$mode = mode; + + 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._signal("tokenizerUpdate", e); + }); + } else { + this.bgTokenizer.setTokenizer(tokenizer); + } + + this.bgTokenizer.setDocument(this.getDocument()); + + this.tokenRe = mode.tokenRe; + this.nonTokenRe = mode.nonTokenRe; + + + if (!$isPlaceholder) { + if (mode.attachToSession) + mode.attachToSession(this); + this.$options.wrapMethod.set.call(this, this.$wrapMethod); + this.$setFolding(mode.foldingRules); + this.bgTokenizer.start(0); + this._emit("changeMode"); + } + }; + + this.$stopWorker = function() { + if (this.$worker) { + this.$worker.terminate(); + this.$worker = null; + } + }; + + this.$startWorker = function() { + try { + this.$worker = this.$mode.createWorker(this); + } catch (e) { + config.warn("Could not load worker", e); + this.$worker = null; + } + }; + this.getMode = function() { + return this.$mode; + }; + + this.$scrollTop = 0; + this.setScrollTop = function(scrollTop) { + if (this.$scrollTop === scrollTop || isNaN(scrollTop)) + return; + + this.$scrollTop = scrollTop; + this._signal("changeScrollTop", scrollTop); + }; + this.getScrollTop = function() { + return this.$scrollTop; + }; + + this.$scrollLeft = 0; + this.setScrollLeft = function(scrollLeft) { + if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft)) + return; + + this.$scrollLeft = scrollLeft; + this._signal("changeScrollLeft", scrollLeft); + }; + this.getScrollLeft = function() { + return this.$scrollLeft; + }; + this.getScreenWidth = function() { + this.$computeWidth(); + if (this.lineWidgets) + return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth); + return this.screenWidth; + }; + + this.getLineWidgetMaxWidth = function() { + if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth; + var width = 0; + this.lineWidgets.forEach(function(w) { + if (w && w.screenWidth > width) + width = w.screenWidth; + }); + return this.lineWidgetWidth = width; + }; + + 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.removeFullLines = function(firstRow, lastRow){ + return this.doc.removeFullLines(firstRow, lastRow); + }; + 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) { + return isUndo ? delta.action !== "insert" : delta.action === "insert"; + } + + var delta = deltas[0]; + var range, point; + var lastDeltaIsInsert = false; + if (isInsert(delta)) { + range = Range.fromPoints(delta.start, delta.end); + lastDeltaIsInsert = true; + } else { + range = Range.fromPoints(delta.start, delta.start); + lastDeltaIsInsert = false; + } + + for (var i = 1; i < deltas.length; i++) { + delta = deltas[i]; + if (isInsert(delta)) { + point = delta.start; + if (range.compare(point.row, point.column) == -1) { + range.setStart(point); + } + point = delta.end; + if (range.compare(point.row, point.column) == 1) { + range.setEnd(point); + } + lastDeltaIsInsert = true; + } else { + point = delta.start; + if (range.compare(point.row, point.column) == -1) { + range = Range.fromPoints(delta.start, delta.start); + } + lastDeltaIsInsert = false; + } + } + if (lastUndoRange != null) { + if (Range.comparePoints(lastUndoRange.start, range.start) === 0) { + lastUndoRange.start.column += range.end.column - range.start.column; + lastUndoRange.end.column += range.end.column - range.start.column; + } + + var cmp = lastUndoRange.compareRange(range); + if (cmp == 1) { + range.setStart(lastUndoRange.start); + } else if (cmp == -1) { + range.setEnd(lastUndoRange.end); + } + } + + return range; + }; + this.replace = function(range, text) { + return this.doc.replace(range, text); + }; + this.moveText = function(fromRange, toPosition, copy) { + var text = this.getTextRange(fromRange); + var folds = this.getFoldsInRange(fromRange); + + var toRange = Range.fromPoints(toPosition, toPosition); + if (!copy) { + this.remove(fromRange); + var rowDiff = fromRange.start.row - fromRange.end.row; + var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column; + if (collDiff) { + if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column) + toRange.start.column += collDiff; + if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column) + toRange.end.column += collDiff; + } + if (rowDiff && toRange.start.row >= fromRange.end.row) { + toRange.start.row += rowDiff; + toRange.end.row += rowDiff; + } + } + + toRange.end = this.insert(toRange.start, text); + if (folds.length) { + var oldStart = fromRange.start; + var newStart = toRange.start; + var rowDiff = newStart.row - oldStart.row; + var collDiff = newStart.column - oldStart.column; + this.addFolds(folds.map(function(x) { + x = x.clone(); + if (x.start.row == oldStart.row) + x.start.column += collDiff; + if (x.end.row == oldStart.row) + x.end.column += collDiff; + x.start.row += rowDiff; + x.end.row += rowDiff; + return x; + })); + } + + return toRange; + }; + this.indentRows = function(startRow, endRow, indentString) { + indentString = indentString.replace(/\t/g, this.getTabString()); + for (var row=startRow; row<=endRow; row++) + this.doc.insertInLine({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.$moveLines = function(firstRow, lastRow, dir) { + firstRow = this.getRowFoldStart(firstRow); + lastRow = this.getRowFoldEnd(lastRow); + if (dir < 0) { + var row = this.getRowFoldStart(firstRow + dir); + if (row < 0) return 0; + var diff = row-firstRow; + } else if (dir > 0) { + var row = this.getRowFoldEnd(lastRow + dir); + if (row > this.doc.getLength()-1) return 0; + var diff = row-lastRow; + } else { + firstRow = this.$clipRowToDocument(firstRow); + lastRow = this.$clipRowToDocument(lastRow); + var diff = lastRow - firstRow + 1; + } + + var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE); + var folds = this.getFoldsInRange(range).map(function(x){ + x = x.clone(); + x.start.row += diff; + x.end.row += diff; + return x; + }); + + var lines = dir == 0 + ? this.doc.getLines(firstRow, lastRow) + : this.doc.removeFullLines(firstRow, lastRow); + this.doc.insertFullLines(firstRow+diff, lines); + folds.length && this.addFolds(folds); + return diff; + }; + this.moveLinesUp = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, -1); + }; + this.moveLinesDown = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, 1); + }; + this.duplicateLines = function(firstRow, lastRow) { + return this.$moveLines(firstRow, lastRow, 0); + }; + + + 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; + }; + 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 (useWrapMode) { + var len = this.getLength(); + this.$wrapData = Array(len); + this.$updateWrapData(0, len - 1); + } + + this._signal("changeWrapMode"); + } + }; + this.getUseWrapMode = function() { + return this.$useWrapMode; + }; + this.setWrapLimitRange = function(min, max) { + if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) { + this.$wrapLimitRange = { min: min, max: max }; + this.$modified = true; + if (this.$useWrapMode) + this._signal("changeWrapMode"); + } + }; + this.adjustWrapLimit = function(desiredLimit, $printMargin) { + var limits = this.$wrapLimitRange; + if (limits.max < 0) + limits = {min: $printMargin, max: $printMargin}; + var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max); + if (wrapLimit != this.$wrapLimit && wrapLimit > 1) { + this.$wrapLimit = wrapLimit; + this.$modified = true; + if (this.$useWrapMode) { + this.$updateWrapData(0, this.getLength() - 1); + this.$resetRowCache(0); + this._signal("changeWrapLimit"); + } + return true; + } + return false; + }; + + this.$constrainWrapLimit = function(wrapLimit, min, max) { + if (min) + wrapLimit = Math.max(min, wrapLimit); + + if (max) + wrapLimit = Math.min(max, wrapLimit); + + return wrapLimit; + }; + this.getWrapLimit = function() { + return this.$wrapLimit; + }; + this.setWrapLimit = function (limit) { + this.setWrapLimitRange(limit, limit); + }; + this.getWrapLimitRange = function() { + return { + min : this.$wrapLimitRange.min, + max : this.$wrapLimitRange.max + }; + }; + + this.$updateInternalDataOnChange = function(delta) { + var useWrapMode = this.$useWrapMode; + var action = delta.action; + var start = delta.start; + var end = delta.end; + var firstRow = start.row; + var lastRow = end.row; + var len = lastRow - firstRow; + var removedFolds = null; + + this.$updating = true; + if (len != 0) { + if (action === "remove") { + this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len); + + var foldLines = this.$foldData; + removedFolds = this.getFoldsInRange(delta); + 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 = Array(len); + args.unshift(firstRow, 0); + var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache + arr.splice.apply(arr, args); + var foldLines = this.$foldData; + var foldLine = this.getFoldLine(firstRow); + var idx = 0; + if (foldLine) { + var cmp = foldLine.range.compareInside(start.row, start.column); + if (cmp == 0) { + foldLine = foldLine.split(start.row, start.column); + if (foldLine) { + foldLine.shiftRow(len); + foldLine.addRemoveChars(lastRow, 0, end.column - start.column); + } + } else + if (cmp == -1) { + foldLine.addRemoveChars(firstRow, 0, end.column - start.column); + foldLine.shiftRow(len); + } + idx = foldLines.indexOf(foldLine) + 1; + } + + for (idx; idx < foldLines.length; idx++) { + var foldLine = foldLines[idx]; + if (foldLine.start.row >= firstRow) { + foldLine.shiftRow(len); + } + } + } + } else { + len = Math.abs(delta.start.column - delta.end.column); + if (action === "remove") { + removedFolds = this.getFoldsInRange(delta); + 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!"); + } + this.$updating = false; + + if (useWrapMode) + this.$updateWrapData(firstRow, lastRow); + else + this.$updateRowLengthCache(firstRow, lastRow); + + return removedFolds; + }; + + this.$updateRowLengthCache = function(firstRow, lastRow, b) { + this.$rowLengthCache[firstRow] = null; + this.$rowLengthCache[lastRow] = null; + }; + + 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(lines[row]); + wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); + row ++; + } else { + tokens = []; + foldLine.walk(function(placeholder, row, column, lastColumn) { + var walkTokens; + if (placeholder != null) { + 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 + ); + + wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); + row = foldLine.end.row + 1; + } + } + }; + 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, tabSize) { + if (tokens.length == 0) { + return []; + } + + var splits = []; + var displayLength = tokens.length; + var lastSplit = 0, lastDocSplit = 0; + + var isCode = this.$wrapAsCode; + + var indentedSoftWrap = this.$indentedSoftWrap; + var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8) + || indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2); + + function getWrapIndent() { + var indentation = 0; + if (maxIndent === 0) + return indentation; + if (indentedSoftWrap) { + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + if (token == SPACE) + indentation += 1; + else if (token == TAB) + indentation += tabSize; + else if (token == TAB_SPACE) + continue; + else + break; + } + } + if (isCode && indentedSoftWrap !== false) + indentation += tabSize; + return Math.min(indentation, maxIndent); + } + function addSplit(screenPos) { + var displayed = tokens.slice(lastSplit, screenPos); + var len = displayed.length; + displayed.join("") + .replace(/12/g, function() { + len -= 1; + }) + .replace(/2/g, function() { + len -= 1; + }); + + if (!splits.length) { + indent = getWrapIndent(); + splits.indent = indent; + } + lastDocSplit += len; + splits.push(lastDocSplit); + lastSplit = screenPos; + } + var indent = 0; + while (displayLength - lastSplit > wrapLimit - indent) { + var split = lastSplit + wrapLimit - indent; + if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) { + addSplit(split); + continue; + } + if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) { + for (split; split != lastSplit - 1; split--) { + if (tokens[split] == PLACEHOLDER_START) { + break; + } + } + if (split > lastSplit) { + addSplit(split); + continue; + } + split = lastSplit + wrapLimit; + for (split; split < tokens.length; split++) { + if (tokens[split] != PLACEHOLDER_BODY) { + break; + } + } + if (split == tokens.length) { + break; // Breaks the while-loop. + } + addSplit(split); + continue; + } + var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1); + while (split > minSplit && tokens[split] < PLACEHOLDER_START) { + split --; + } + if (isCode) { + while (split > minSplit && tokens[split] < PLACEHOLDER_START) { + split --; + } + while (split > minSplit && tokens[split] == PUNCTUATION) { + split --; + } + } else { + while (split > minSplit && tokens[split] < SPACE) { + split --; + } + } + if (split > minSplit) { + addSplit(++split); + continue; + } + split = lastSplit + wrapLimit; + if (tokens[split] == CHAR_EXT) + split--; + addSplit(split - indent); + } + return splits; + }; + 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); + if (c == 9) { + tabSize = this.getScreenTabSize(arr.length + offset); + arr.push(TAB); + for (var n = 1; n < tabSize; n++) { + arr.push(TAB_SPACE); + } + } + else if (c == 32) { + arr.push(SPACE); + } else if((c > 39 && c < 48) || (c > 57 && c < 64)) { + arr.push(PUNCTUATION); + } + else if (c >= 0x1100 && isFullWidth(c)) { + arr.push(CHAR, CHAR_EXT); + } else { + arr.push(CHAR); + } + } + return arr; + }; + 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); + if (c == 9) { + screenColumn += this.getScreenTabSize(screenColumn); + } + else if (c >= 0x1100 && isFullWidth(c)) { + screenColumn += 2; + } else { + screenColumn += 1; + } + if (screenColumn > maxScreenColumn) { + break; + } + } + + return [screenColumn, column]; + }; + + this.lineWidgets = null; + this.getRowLength = function(row) { + if (this.lineWidgets) + var h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; + else + h = 0 + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1 + h; + } else { + return this.$wrapData[row].length + 1 + h; + } + }; + this.getRowLineCount = function(row) { + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1; + } else { + return this.$wrapData[row].length + 1; + } + }; + + this.getRowWrapIndent = function(screenRow) { + if (this.$useWrapMode) { + var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); + var splits = this.$wrapData[pos.row]; + return splits.length && splits[0] < pos.column ? splits.indent : 0; + } else { + return 0; + } + } + 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 l = rowCache.length; + if (l && i >= 0) { + var row = rowCache[i]; + var docRow = this.$docRowCache[i]; + var doCache = screenRow > rowCache[l - 1]; + } else { + var doCache = !l; + } + + 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 > 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) { + return { + row: maxRow, + column: this.getLine(maxRow).length + }; + } else { + line = this.getLine(docRow); + foldLine = null; + } + var wrapIndent = 0; + if (this.$useWrapMode) { + var splits = this.$wrapData[docRow]; + if (splits) { + var splitIndex = Math.floor(screenRow - row); + column = splits[splitIndex]; + if(splitIndex > 0 && splits.length) { + wrapIndent = splits.indent; + docColumn = splits[splitIndex - 1] || splits[splits.length - 1]; + line = line.substring(docColumn); + } + } + } + + docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1]; + if (this.$useWrapMode && docColumn >= column) + docColumn = column - 1; + + if (foldLine) + return foldLine.idxToPosition(docColumn); + + return {row: docRow, column: docColumn}; + }; + this.documentToScreenPosition = function(docRow, docColumn) { + 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; + 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); + var l = rowCache.length; + if (l && i >= 0) { + var row = rowCache[i]; + var screenRow = this.$screenRowCache[i]; + var doCache = docRow > rowCache[l - 1]; + } else { + var doCache = !l; + } + + 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); + } + } + var textLine = ""; + if (foldLine && row >= foldStart) { + textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn); + foldStartRow = foldLine.start.row; + } else { + textLine = this.getLine(docRow).substring(0, docColumn); + foldStartRow = docRow; + } + var wrapIndent = 0; + if (this.$useWrapMode) { + var wrapRow = this.$wrapData[foldStartRow]; + if (wrapRow) { + var screenRowOffset = 0; + while (textLine.length >= wrapRow[screenRowOffset]) { + screenRow ++; + screenRowOffset++; + } + textLine = textLine.substring( + wrapRow[screenRowOffset - 1] || 0, textLine.length + ); + wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0; + } + } + + return { + row: screenRow, + column: wrapIndent + 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(); + 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) { + var splits = this.$wrapData[row]; + screenRows += splits ? splits.length + 1 : 1; + row ++; + if (row > foldStart) { + row = fold.end.row+1; + fold = this.$foldData[i++]; + foldStart = fold ?fold.start.row :Infinity; + } + } + } + if (this.lineWidgets) + screenRows += this.$getWidgetScreenLength(); + + return screenRows; + }; + this.$setFontMetrics = function(fm) { + if (!this.$enableVarChar) return; + this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { + if (maxScreenColumn === 0) + return [0, 0]; + if (!maxScreenColumn) + maxScreenColumn = Infinity; + screenColumn = screenColumn || 0; + + var c, column; + for (column = 0; column < str.length; column++) { + c = str.charAt(column); + if (c === "\t") { + screenColumn += this.getScreenTabSize(screenColumn); + } else { + screenColumn += fm.getCharacterWidth(c); + } + if (screenColumn > maxScreenColumn) { + break; + } + } + + return [screenColumn, column]; + }; + }; + + this.destroy = function() { + if (this.bgTokenizer) { + this.bgTokenizer.setDocument(null); + this.bgTokenizer = null; + } + this.$stopWorker(); + }; + 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); + +acequire("./edit_session/folding").Folding.call(EditSession.prototype); +acequire("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype); + + +config.defineOptions(EditSession.prototype, "session", { + wrap: { + set: function(value) { + if (!value || value == "off") + value = false; + else if (value == "free") + value = true; + else if (value == "printMargin") + value = -1; + else if (typeof value == "string") + value = parseInt(value, 10) || false; + + if (this.$wrap == value) + return; + this.$wrap = value; + if (!value) { + this.setUseWrapMode(false); + } else { + var col = typeof value == "number" ? value : null; + this.setWrapLimitRange(col, col); + this.setUseWrapMode(true); + } + }, + get: function() { + if (this.getUseWrapMode()) { + if (this.$wrap == -1) + return "printMargin"; + if (!this.getWrapLimitRange().min) + return "free"; + return this.$wrap; + } + return "off"; + }, + handlesSet: true + }, + wrapMethod: { + set: function(val) { + val = val == "auto" + ? this.$mode.type != "text" + : val != "text"; + if (val != this.$wrapAsCode) { + this.$wrapAsCode = val; + if (this.$useWrapMode) { + this.$modified = true; + this.$resetRowCache(0); + this.$updateWrapData(0, this.getLength() - 1); + } + } + }, + initialValue: "auto" + }, + indentedSoftWrap: { initialValue: true }, + firstLineNumber: { + set: function() {this._signal("changeBreakpoint");}, + initialValue: 1 + }, + useWorker: { + set: function(useWorker) { + this.$useWorker = useWorker; + + this.$stopWorker(); + if (useWorker) + this.$startWorker(); + }, + initialValue: true + }, + useSoftTabs: {initialValue: true}, + tabSize: { + set: function(tabSize) { + if (isNaN(tabSize) || this.$tabSize === tabSize) return; + + this.$modified = true; + this.$rowLengthCache = []; + this.$tabSize = tabSize; + this._signal("changeTabSize"); + }, + initialValue: 4, + handlesSet: true + }, + overwrite: { + set: function(val) {this._signal("changeOverwrite");}, + initialValue: false + }, + newLineMode: { + set: function(val) {this.doc.setNewLineMode(val)}, + get: function() {return this.doc.getNewLineMode()}, + handlesSet: true + }, + mode: { + set: function(val) { this.setMode(val) }, + get: function() { return this.$modeId } + } +}); + +exports.EditSession = EditSession; +}); + +ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("./lib/lang"); +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; + +var Search = function() { + this.$options = {}; +}; + +(function() { + 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 options = this.$options; + var iterator = this.$matchIterator(session, 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); + if (!range.length && options.start && options.start.start + && options.skipCurrent != false && firstRange.isEqual(options.start) + ) { + firstRange = null; + return false; + } + } else + firstRange = range; + return true; + }); + + return firstRange; + }; + this.findAll = function(session) { + var options = this.$options; + if (!options.needle) + return []; + this.$assembleRegExp(options); + + var range = options.range; + var lines = range + ? session.getLines(range.start.row, range.end.row) + : session.doc.getAllLines(); + + var ranges = []; + var re = options.re; + if (options.$isMultiLine) { + var len = re.length; + var maxRow = lines.length - len; + var prevRange; + outer: for (var row = re.offset || 0; row <= maxRow; row++) { + for (var j = 0; j < len; j++) + if (lines[row + j].search(re[j]) == -1) + continue outer; + + var startLine = lines[row]; + var line = lines[row + len - 1]; + var startIndex = startLine.length - startLine.match(re[0])[0].length; + var endIndex = line.match(re[len - 1])[0].length; + + if (prevRange && prevRange.end.row === row && + prevRange.end.column > startIndex + ) { + continue; + } + ranges.push(prevRange = new Range( + row, startIndex, row + len - 1, endIndex + )); + if (len > 2) + row = row + len - 2; + } + } 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 (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--; + + ranges = ranges.slice(i, j + 1); + for (i = 0, j = ranges.length; i < j; i++) { + ranges[i].start.row += range.start.row; + ranges[i].end.row += range.start.row; + } + } + + 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 callback; + 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 (options.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; + }; + } + + var lineIterator = this.$lineIterator(session, options); + + return { + forEach: function(_callback) { + callback = _callback; + lineIterator.forEach(matchIterator); + } + }; + }; + + this.$assembleRegExp = function(options, $disableFakeMultiline) { + 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 = addWordBoundary(needle, options); + + var modifier = options.caseSensitive ? "gm" : "gmi"; + + options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle); + if (options.$isMultiLine) + return options.re = this.$assembleMultilineRegExp(needle, modifier); + + try { + var re = new RegExp(needle, modifier); + } catch(e) { + 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 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 lastRow = range ? range.end.row : session.getLength() - 1; + + var forEach = backwards ? 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; + } : 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; + }; + + return {forEach: forEach}; + }; + +}).call(Search.prototype); + +function addWordBoundary(needle, options) { + function wordBoundary(c) { + if (/\w/.test(c) || options.regExp) return "\\b"; + return ""; + } + return wordBoundary(needle[0]) + needle + + wordBoundary(needle[needle.length - 1]); +} + +exports.Search = Search; +}); + +ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { +"use strict"; + +var keyUtil = acequire("../lib/keys"); +var useragent = acequire("../lib/useragent"); +var KEY_MODS = keyUtil.KEY_MODS; + +function HashHandler(config, platform) { + this.platform = platform || (useragent.isMac ? "mac" : "win"); + this.commands = {}; + this.commandKeyBinding = {}; + this.addCommands(config); + this.$singleCommand = true; +} + +function MultiHashHandler(config, platform) { + HashHandler.call(this, config, platform); + this.$singleCommand = false; +} + +MultiHashHandler.prototype = HashHandler.prototype; + +(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, keepCommand) { + var name = command && (typeof command === 'string' ? command : command.name); + command = this.commands[name]; + if (!keepCommand) + delete this.commands[name]; + var ckb = this.commandKeyBinding; + for (var keyId in ckb) { + var cmdGroup = ckb[keyId]; + if (cmdGroup == command) { + delete ckb[keyId]; + } else if (Array.isArray(cmdGroup)) { + var i = cmdGroup.indexOf(command); + if (i != -1) { + cmdGroup.splice(i, 1); + if (cmdGroup.length == 1) + ckb[keyId] = cmdGroup[0]; + } + } + } + }; + + this.bindKey = function(key, command, position) { + if (typeof key == "object" && key) { + if (position == undefined) + position = key.position; + key = key[this.platform]; + } + if (!key) + return; + if (typeof command == "function") + return this.addCommand({exec: command, bindKey: key, name: command.name || key}); + + key.split("|").forEach(function(keyPart) { + var chain = ""; + if (keyPart.indexOf(" ") != -1) { + var parts = keyPart.split(/\s+/); + keyPart = parts.pop(); + parts.forEach(function(keyPart) { + var binding = this.parseKeys(keyPart); + var id = KEY_MODS[binding.hashId] + binding.key; + chain += (chain ? " " : "") + id; + this._addCommandToBinding(chain, "chainKeys"); + }, this); + chain += " "; + } + var binding = this.parseKeys(keyPart); + var id = KEY_MODS[binding.hashId] + binding.key; + this._addCommandToBinding(chain + id, command, position); + }, this); + }; + + function getPosition(command) { + return typeof command == "object" && command.bindKey + && command.bindKey.position || 0; + } + this._addCommandToBinding = function(keyId, command, position) { + var ckb = this.commandKeyBinding, i; + if (!command) { + delete ckb[keyId]; + } else if (!ckb[keyId] || this.$singleCommand) { + ckb[keyId] = command; + } else { + if (!Array.isArray(ckb[keyId])) { + ckb[keyId] = [ckb[keyId]]; + } else if ((i = ckb[keyId].indexOf(command)) != -1) { + ckb[keyId].splice(i, 1); + } + + if (typeof position != "number") { + if (position || command.isDefault) + position = -100; + else + position = getPosition(command); + } + var commands = ckb[keyId]; + for (i = 0; i < commands.length; i++) { + var other = commands[i]; + var otherPos = getPosition(other); + if (otherPos > position) + break; + } + commands.splice(i, 0, command); + } + }; + + this.addCommands = function(commands) { + commands && Object.keys(commands).forEach(function(name) { + var command = commands[name]; + if (!command) + return; + + if (typeof command === "string") + return this.bindKey(command, name); + + if (typeof command === "function") + command = { exec: command }; + + if (typeof command !== "object") + return; + + 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) { + this.bindKey(command.bindKey, command); + }; + this.parseKeys = function(keys) { + var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x}); + var key = parts.pop(); + + var keyCode = keyUtil[key]; + if (keyUtil.FUNCTION_KEYS[keyCode]) + key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase(); + else if (!parts.length) + return {key: key, hashId: -1}; + else if (parts.length == 1 && parts[0] == "shift") + return {key: key.toUpperCase(), hashId: -1}; + + var hashId = 0; + for (var i = parts.length; i--;) { + var modifier = keyUtil.KEY_MODS[parts[i]]; + if (modifier == null) { + if (typeof console != "undefined") + console.error("invalid modifier " + parts[i] + " in " + keys); + return false; + } + hashId |= modifier; + } + return {key: key, hashId: hashId}; + }; + + this.findKeyCommand = function findKeyCommand(hashId, keyString) { + var key = KEY_MODS[hashId] + keyString; + return this.commandKeyBinding[key]; + }; + + this.handleKeyboard = function(data, hashId, keyString, keyCode) { + if (keyCode < 0) return; + var key = KEY_MODS[hashId] + keyString; + var command = this.commandKeyBinding[key]; + if (data.$keyChain) { + data.$keyChain += " " + key; + command = this.commandKeyBinding[data.$keyChain] || command; + } + + if (command) { + if (command == "chainKeys" || command[command.length - 1] == "chainKeys") { + data.$keyChain = data.$keyChain || key; + return {command: "null"}; + } + } + + if (data.$keyChain) { + if ((!hashId || hashId == 4) && keyString.length == 1) + data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input + else if (hashId == -1 || keyCode > 0) + data.$keyChain = ""; // reset keyChain + } + return {command: command}; + }; + + this.getStatusText = function(editor, data) { + return data.$keyChain || ""; + }; + +}).call(HashHandler.prototype); + +exports.HashHandler = HashHandler; +exports.MultiHashHandler = MultiHashHandler; +}); + +ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var MultiHashHandler = acequire("../keyboard/hash_handler").MultiHashHandler; +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var CommandManager = function(platform, commands) { + MultiHashHandler.call(this, commands, platform); + this.byName = this.commands; + this.setDefaultHandler("exec", function(e) { + return e.command.exec(e.editor, e.args || {}); + }); +}; + +oop.inherits(CommandManager, MultiHashHandler); + +(function() { + + oop.implement(this, EventEmitter); + + this.exec = function(command, editor, args) { + if (Array.isArray(command)) { + for (var i = command.length; i--; ) { + if (this.exec(command[i], editor, args)) return true; + } + return false; + } + + if (typeof command === "string") + command = this.commands[command]; + + if (!command) + return false; + + if (editor && editor.$readOnly && !command.readOnly) + return false; + + var e = {editor: editor, command: command, args: args}; + e.returnValue = this._emit("exec", e); + this._signal("afterExec", e); + + return e.returnValue === false ? false : true; + }; + + this.toggleRecording = function(editor) { + if (this.$inReplay) + return; + + editor && editor._emit("changeStatus"); + if (this.recording) { + this.macro.pop(); + this.removeEventListener("exec", this.$addCommandToMacro); + + if (!this.macro.length) + this.macro = this.oldMacro; + + return this.recording = false; + } + if (!this.$addCommandToMacro) { + this.$addCommandToMacro = function(e) { + this.macro.push([e.command, e.args]); + }.bind(this); + } + + this.oldMacro = this.macro; + this.macro = []; + this.on("exec", this.$addCommandToMacro); + return this.recording = true; + }; + + this.replay = function(editor) { + if (this.$inReplay || !this.macro) + return; + + if (this.recording) + return this.toggleRecording(editor); + + try { + this.$inReplay = true; + this.macro.forEach(function(x) { + if (typeof x == "string") + this.exec(x, editor); + else + this.exec(x[0], editor, x[1]); + }, this); + } finally { + this.$inReplay = false; + } + }; + + this.trimMacro = function(m) { + return m.map(function(x){ + if (typeof x[0] != "string") + x[0] = x[0].name; + if (!x[1]) + x = x[0]; + return x; + }); + }; + +}).call(CommandManager.prototype); + +exports.CommandManager = CommandManager; + +}); + +ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(acequire, exports, module) { +"use strict"; + +var lang = acequire("../lib/lang"); +var config = acequire("../config"); +var Range = acequire("../range").Range; + +function bindKey(win, mac) { + return {win: win, mac: mac}; +} +exports.commands = [{ + name: "showSettingsMenu", + bindKey: bindKey("Ctrl-,", "Command-,"), + exec: function(editor) { + config.loadModule("ace/ext/settings_menu", function(module) { + module.init(editor); + editor.showSettingsMenu(); + }); + }, + readOnly: true +}, { + name: "goToNextError", + bindKey: bindKey("Alt-E", "F4"), + exec: function(editor) { + config.loadModule("ace/ext/error_marker", function(module) { + module.showErrorMarker(editor, 1); + }); + }, + scrollIntoView: "animate", + readOnly: true +}, { + name: "goToPreviousError", + bindKey: bindKey("Alt-Shift-E", "Shift-F4"), + exec: function(editor) { + config.loadModule("ace/ext/error_marker", function(module) { + module.showErrorMarker(editor, -1); + }); + }, + scrollIntoView: "animate", + readOnly: true +}, { + 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|Ctrl-F1", "Command-Alt-L|Command-F1"), + exec: function(editor) { editor.session.toggleFold(false); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "unfold", + bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"), + exec: function(editor) { editor.session.toggleFold(true); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "toggleFoldWidget", + bindKey: bindKey("F2", "F2"), + exec: function(editor) { editor.session.toggleFoldWidget(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "toggleParentFoldWidget", + bindKey: bindKey("Alt-F2", "Alt-F2"), + exec: function(editor) { editor.session.toggleFoldWidget(true); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "foldall", + bindKey: bindKey(null, "Ctrl-Command-Option-0"), + exec: function(editor) { editor.session.foldAll(); }, + scrollIntoView: "center", + readOnly: true +}, { + name: "foldOther", + bindKey: bindKey("Alt-0", "Command-Option-0"), + exec: function(editor) { + editor.session.foldAll(); + editor.session.unfold(editor.selection.getAllRanges()); + }, + scrollIntoView: "center", + readOnly: true +}, { + name: "unfoldall", + bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"), + exec: function(editor) { editor.session.unfold(); }, + scrollIntoView: "center", + readOnly: true +}, { + name: "findnext", + bindKey: bindKey("Ctrl-K", "Command-G"), + exec: function(editor) { editor.findNext(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "findprevious", + bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"), + exec: function(editor) { editor.findPrevious(); }, + multiSelectAction: "forEach", + scrollIntoView: "center", + readOnly: true +}, { + name: "selectOrFindNext", + bindKey: bindKey("Alt-K", "Ctrl-G"), + exec: function(editor) { + if (editor.selection.isEmpty()) + editor.selection.selectWord(); + else + editor.findNext(); + }, + readOnly: true +}, { + name: "selectOrFindPrevious", + bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"), + exec: function(editor) { + if (editor.selection.isEmpty()) + editor.selection.selectWord(); + else + editor.findPrevious(); + }, + readOnly: true +}, { + name: "find", + bindKey: bindKey("Ctrl-F", "Command-F"), + exec: function(editor) { + config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor)}); + }, + readOnly: true +}, { + name: "overwrite", + bindKey: "Insert", + exec: function(editor) { editor.toggleOverwrite(); }, + readOnly: true +}, { + name: "selecttostart", + bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Home|Command-Shift-Up"), + exec: function(editor) { editor.getSelection().selectFileStart(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "gotostart", + bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"), + exec: function(editor) { editor.navigateFileStart(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "selectup", + bindKey: bindKey("Shift-Up", "Shift-Up|Ctrl-Shift-P"), + exec: function(editor) { editor.getSelection().selectUp(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "golineup", + bindKey: bindKey("Up", "Up|Ctrl-P"), + exec: function(editor, args) { editor.navigateUp(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttoend", + bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-End|Command-Shift-Down"), + exec: function(editor) { editor.getSelection().selectFileEnd(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "gotoend", + bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"), + exec: function(editor) { editor.navigateFileEnd(); }, + multiSelectAction: "forEach", + readOnly: true, + scrollIntoView: "animate", + aceCommandGroup: "fileJump" +}, { + name: "selectdown", + bindKey: bindKey("Shift-Down", "Shift-Down|Ctrl-Shift-N"), + exec: function(editor) { editor.getSelection().selectDown(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "golinedown", + bindKey: bindKey("Down", "Down|Ctrl-N"), + exec: function(editor, args) { editor.navigateDown(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectwordleft", + bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), + exec: function(editor) { editor.getSelection().selectWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotowordleft", + bindKey: bindKey("Ctrl-Left", "Option-Left"), + exec: function(editor) { editor.navigateWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttolinestart", + bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left|Ctrl-Shift-A"), + exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotolinestart", + bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), + exec: function(editor) { editor.navigateLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectleft", + bindKey: bindKey("Shift-Left", "Shift-Left|Ctrl-Shift-B"), + exec: function(editor) { editor.getSelection().selectLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotoleft", + bindKey: bindKey("Left", "Left|Ctrl-B"), + exec: function(editor, args) { editor.navigateLeft(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectwordright", + bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), + exec: function(editor) { editor.getSelection().selectWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotowordright", + bindKey: bindKey("Ctrl-Right", "Option-Right"), + exec: function(editor) { editor.navigateWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selecttolineend", + bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right|Shift-End|Ctrl-Shift-E"), + exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotolineend", + bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), + exec: function(editor) { editor.navigateLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectright", + bindKey: bindKey("Shift-Right", "Shift-Right"), + exec: function(editor) { editor.getSelection().selectRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "gotoright", + bindKey: bindKey("Right", "Right|Ctrl-F"), + exec: function(editor, args) { editor.navigateRight(args.times); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectpagedown", + bindKey: "Shift-PageDown", + exec: function(editor) { editor.selectPageDown(); }, + readOnly: true +}, { + name: "pagedown", + bindKey: bindKey(null, "Option-PageDown"), + exec: function(editor) { editor.scrollPageDown(); }, + readOnly: true +}, { + name: "gotopagedown", + bindKey: bindKey("PageDown", "PageDown|Ctrl-V"), + exec: function(editor) { editor.gotoPageDown(); }, + readOnly: true +}, { + name: "selectpageup", + bindKey: "Shift-PageUp", + exec: function(editor) { editor.selectPageUp(); }, + readOnly: true +}, { + name: "pageup", + bindKey: bindKey(null, "Option-PageUp"), + exec: function(editor) { editor.scrollPageUp(); }, + readOnly: true +}, { + name: "gotopageup", + bindKey: "PageUp", + exec: function(editor) { editor.gotoPageUp(); }, + readOnly: true +}, { + name: "scrollup", + bindKey: bindKey("Ctrl-Up", null), + exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); }, + readOnly: true +}, { + name: "scrolldown", + bindKey: bindKey("Ctrl-Down", null), + exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); }, + readOnly: true +}, { + name: "selectlinestart", + bindKey: "Shift-Home", + exec: function(editor) { editor.getSelection().selectLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectlineend", + bindKey: "Shift-End", + exec: function(editor) { editor.getSelection().selectLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "togglerecording", + bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"), + exec: function(editor) { editor.commands.toggleRecording(editor); }, + 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-P", "Ctrl-P"), + exec: function(editor) { editor.jumpToMatching(); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "selecttomatching", + bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"), + exec: function(editor) { editor.jumpToMatching(true); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "expandToMatching", + bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"), + exec: function(editor) { editor.jumpToMatching(true, true); }, + multiSelectAction: "forEach", + scrollIntoView: "animate", + readOnly: true +}, { + name: "passKeysToBrowser", + bindKey: bindKey(null, null), + exec: function() {}, + passEvent: true, + readOnly: true +}, { + name: "copy", + exec: function(editor) { + }, + readOnly: true +}, +{ + name: "cut", + exec: function(editor) { + var range = editor.getSelectionRange(); + editor._emit("cut", range); + + if (!editor.selection.isEmpty()) { + editor.session.remove(range); + editor.clearSelection(); + } + }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "paste", + exec: function(editor, args) { + editor.$handlePaste(args); + }, + scrollIntoView: "cursor" +}, { + name: "removeline", + bindKey: bindKey("Ctrl-D", "Command-D"), + exec: function(editor) { editor.removeLines(); }, + scrollIntoView: "cursor", + multiSelectAction: "forEachLine" +}, { + name: "duplicateSelection", + bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"), + exec: function(editor) { editor.duplicateSelection(); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "sortlines", + bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"), + exec: function(editor) { editor.sortLines(); }, + scrollIntoView: "selection", + multiSelectAction: "forEachLine" +}, { + name: "togglecomment", + bindKey: bindKey("Ctrl-/", "Command-/"), + exec: function(editor) { editor.toggleCommentLines(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "toggleBlockComment", + bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"), + exec: function(editor) { editor.toggleBlockComment(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "modifyNumberUp", + bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"), + exec: function(editor) { editor.modifyNumber(1); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "modifyNumberDown", + bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"), + exec: function(editor) { editor.modifyNumber(-1); }, + scrollIntoView: "cursor", + multiSelectAction: "forEach" +}, { + name: "replace", + bindKey: bindKey("Ctrl-H", "Command-Option-F"), + exec: function(editor) { + config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true)}); + } +}, { + 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("Alt-Shift-Up", "Command-Option-Up"), + exec: function(editor) { editor.copyLinesUp(); }, + scrollIntoView: "cursor" +}, { + name: "movelinesup", + bindKey: bindKey("Alt-Up", "Option-Up"), + exec: function(editor) { editor.moveLinesUp(); }, + scrollIntoView: "cursor" +}, { + name: "copylinesdown", + bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"), + exec: function(editor) { editor.copyLinesDown(); }, + scrollIntoView: "cursor" +}, { + name: "movelinesdown", + bindKey: bindKey("Alt-Down", "Option-Down"), + exec: function(editor) { editor.moveLinesDown(); }, + scrollIntoView: "cursor" +}, { + name: "del", + bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"), + exec: function(editor) { editor.remove("right"); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "backspace", + bindKey: bindKey( + "Shift-Backspace|Backspace", + "Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H" + ), + exec: function(editor) { editor.remove("left"); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "cut_or_delete", + bindKey: bindKey("Shift-Delete", null), + exec: function(editor) { + if (editor.selection.isEmpty()) { + editor.remove("left"); + } else { + return false; + } + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolinestart", + bindKey: bindKey("Alt-Backspace", "Command-Backspace"), + exec: function(editor) { editor.removeToLineStart(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removetolineend", + bindKey: bindKey("Alt-Delete", "Ctrl-K"), + exec: function(editor) { editor.removeToLineEnd(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removewordleft", + bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), + exec: function(editor) { editor.removeWordLeft(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "removewordright", + bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), + exec: function(editor) { editor.removeWordRight(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "outdent", + bindKey: bindKey("Shift-Tab", "Shift-Tab"), + exec: function(editor) { editor.blockOutdent(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "indent", + bindKey: bindKey("Tab", "Tab"), + exec: function(editor) { editor.indent(); }, + multiSelectAction: "forEach", + scrollIntoView: "selectionPart" +}, { + name: "blockoutdent", + bindKey: bindKey("Ctrl-[", "Ctrl-["), + exec: function(editor) { editor.blockOutdent(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "blockindent", + bindKey: bindKey("Ctrl-]", "Ctrl-]"), + exec: function(editor) { editor.blockIndent(); }, + multiSelectAction: "forEachLine", + scrollIntoView: "selectionPart" +}, { + name: "insertstring", + exec: function(editor, str) { editor.insert(str); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "inserttext", + exec: function(editor, args) { + editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "splitline", + bindKey: bindKey(null, "Ctrl-O"), + exec: function(editor) { editor.splitLine(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "transposeletters", + bindKey: bindKey("Ctrl-T", "Ctrl-T"), + exec: function(editor) { editor.transposeLetters(); }, + multiSelectAction: function(editor) {editor.transposeSelections(1); }, + scrollIntoView: "cursor" +}, { + name: "touppercase", + bindKey: bindKey("Ctrl-U", "Ctrl-U"), + exec: function(editor) { editor.toUpperCase(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "tolowercase", + bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), + exec: function(editor) { editor.toLowerCase(); }, + multiSelectAction: "forEach", + scrollIntoView: "cursor" +}, { + name: "expandtoline", + bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"), + exec: function(editor) { + var range = editor.selection.getRange(); + + range.start.column = range.end.column = 0; + range.end.row++; + editor.selection.setRange(range, false); + }, + multiSelectAction: "forEach", + scrollIntoView: "cursor", + readOnly: true +}, { + name: "joinlines", + bindKey: bindKey(null, null), + exec: function(editor) { + var isBackwards = editor.selection.isBackwards(); + var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor(); + var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead(); + var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length; + var selectedText = editor.session.doc.getTextRange(editor.selection.getRange()); + var selectedCount = selectedText.replace(/\n\s*/, " ").length; + var insertLine = editor.session.doc.getLine(selectionStart.row); + + for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) { + var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i))); + if (curLine.length !== 0) { + curLine = " " + curLine; + } + insertLine += curLine; + } + + if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) { + insertLine += editor.session.doc.getNewLineCharacter(); + } + + editor.clearSelection(); + editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine); + + if (selectedCount > 0) { + editor.selection.moveCursorTo(selectionStart.row, selectionStart.column); + editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount); + } else { + firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol; + editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol); + } + }, + multiSelectAction: "forEach", + readOnly: true +}, { + name: "invertSelection", + bindKey: bindKey(null, null), + exec: function(editor) { + var endRow = editor.session.doc.getLength() - 1; + var endCol = editor.session.doc.getLine(endRow).length; + var ranges = editor.selection.rangeList.ranges; + var newRanges = []; + if (ranges.length < 1) { + ranges = [editor.selection.getRange()]; + } + + for (var i = 0; i < ranges.length; i++) { + if (i == (ranges.length - 1)) { + if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) { + newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol)); + } + } + + if (i === 0) { + if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) { + newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column)); + } + } else { + newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column)); + } + } + + editor.exitMultiSelectMode(); + editor.clearSelection(); + + for(var i = 0; i < newRanges.length; i++) { + editor.selection.addRange(newRanges[i], false); + } + }, + readOnly: true, + scrollIntoView: "none" +}]; + +}); + +ace.define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","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","ace/config","ace/token_iterator"], function(acequire, exports, module) { +"use strict"; + +acequire("./lib/fixoldbrowsers"); + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var lang = acequire("./lib/lang"); +var useragent = acequire("./lib/useragent"); +var TextInput = acequire("./keyboard/textinput").TextInput; +var MouseHandler = acequire("./mouse/mouse_handler").MouseHandler; +var FoldHandler = acequire("./mouse/fold_handler").FoldHandler; +var KeyBinding = acequire("./keyboard/keybinding").KeyBinding; +var EditSession = acequire("./edit_session").EditSession; +var Search = acequire("./search").Search; +var Range = acequire("./range").Range; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var CommandManager = acequire("./commands/command_manager").CommandManager; +var defaultCommands = acequire("./commands/default_commands").commands; +var config = acequire("./config"); +var TokenIterator = acequire("./token_iterator").TokenIterator; +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); + this.$mouseHandler = new MouseHandler(this); + new FoldHandler(this); + + this.$blockScrolling = 0; + this.$search = new Search().set({ + wrap: true + }); + + this.$historyTracker = this.$historyTracker.bind(this); + this.commands.on("exec", this.$historyTracker); + + this.$initOperationListeners(); + + this._$emitInputEvent = lang.delayedCall(function() { + this._signal("input", {}); + if (this.session && this.session.bgTokenizer) + this.session.bgTokenizer.scheduleStart(); + }.bind(this)); + + this.on("change", function(_, _self) { + _self._$emitInputEvent.schedule(31); + }); + + this.setSession(session || new EditSession("")); + config.resetOptions(this); + config._signal("editor", this); +}; + +(function(){ + + oop.implement(this, EventEmitter); + + this.$initOperationListeners = function() { + function last(a) {return a[a.length - 1]} + + this.selections = []; + this.commands.on("exec", this.startOperation.bind(this), true); + this.commands.on("afterExec", this.endOperation.bind(this), true); + + this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this)); + + this.on("change", function() { + this.curOp || this.startOperation(); + this.curOp.docChanged = true; + }.bind(this), true); + + this.on("changeSelection", function() { + this.curOp || this.startOperation(); + this.curOp.selectionChanged = true; + }.bind(this), true); + }; + + this.curOp = null; + this.prevOp = {}; + this.startOperation = function(commadEvent) { + if (this.curOp) { + if (!commadEvent || this.curOp.command) + return; + this.prevOp = this.curOp; + } + if (!commadEvent) { + this.previousCommand = null; + commadEvent = {}; + } + + this.$opResetTimer.schedule(); + this.curOp = { + command: commadEvent.command || {}, + args: commadEvent.args, + scrollTop: this.renderer.scrollTop + }; + if (this.curOp.command.name && this.curOp.command.scrollIntoView !== undefined) + this.$blockScrolling++; + }; + + this.endOperation = function(e) { + if (this.curOp) { + if (e && e.returnValue === false) + return this.curOp = null; + this._signal("beforeEndOperation"); + var command = this.curOp.command; + if (command.name && this.$blockScrolling > 0) + this.$blockScrolling--; + var scrollIntoView = command && command.scrollIntoView; + if (scrollIntoView) { + switch (scrollIntoView) { + case "center-animate": + scrollIntoView = "animate"; + case "center": + this.renderer.scrollCursorIntoView(null, 0.5); + break; + case "animate": + case "cursor": + this.renderer.scrollCursorIntoView(); + break; + case "selectionPart": + var range = this.selection.getRange(); + var config = this.renderer.layerConfig; + if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) { + this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead); + } + break; + default: + break; + } + if (scrollIntoView == "animate") + this.renderer.animateScrolling(this.curOp.scrollTop); + } + + this.prevOp = this.curOp; + this.curOp = null; + } + }; + this.$mergeableCommands = ["backspace", "del", "insertstring"]; + this.$historyTracker = function(e) { + if (!this.$mergeUndoDeltas) + return; + + var prev = this.prevOp; + var mergeableCommands = this.$mergeableCommands; + var shouldMerge = prev.command && (e.command.name == prev.command.name); + if (e.command.name == "insertstring") { + var text = e.args; + if (this.mergeNextCommand === undefined) + this.mergeNextCommand = true; + + shouldMerge = shouldMerge + && this.mergeNextCommand // previous command allows to coalesce with + && (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type + + this.mergeNextCommand = true; + } else { + shouldMerge = shouldMerge + && mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable + } + + if ( + this.$mergeUndoDeltas != "always" + && Date.now() - this.sequenceStartTime > 2000 + ) { + shouldMerge = false; // the sequence is too long + } + + if (shouldMerge) + this.session.mergeUndoDeltas = true; + else if (mergeableCommands.indexOf(e.command.name) !== -1) + this.sequenceStartTime = Date.now(); + }; + this.setKeyboardHandler = function(keyboardHandler, cb) { + if (keyboardHandler && typeof keyboardHandler === "string") { + this.$keybindingId = keyboardHandler; + var _self = this; + config.loadModule(["keybinding", keyboardHandler], function(module) { + if (_self.$keybindingId == keyboardHandler) + _self.keyBinding.setKeyboardHandler(module && module.handler); + cb && cb(); + }); + } else { + this.$keybindingId = null; + this.keyBinding.setKeyboardHandler(keyboardHandler); + cb && cb(); + } + }; + this.getKeyboardHandler = function() { + return this.keyBinding.getKeyboardHandler(); + }; + this.setSession = function(session) { + if (this.session == session) + return; + if (this.curOp) this.endOperation(); + this.curOp = {}; + + var oldSession = this.session; + if (oldSession) { + this.session.off("change", this.$onDocumentChange); + this.session.off("changeMode", this.$onChangeMode); + this.session.off("tokenizerUpdate", this.$onTokenizerUpdate); + this.session.off("changeTabSize", this.$onChangeTabSize); + this.session.off("changeWrapLimit", this.$onChangeWrapLimit); + this.session.off("changeWrapMode", this.$onChangeWrapMode); + this.session.off("changeFold", this.$onChangeFold); + this.session.off("changeFrontMarker", this.$onChangeFrontMarker); + this.session.off("changeBackMarker", this.$onChangeBackMarker); + this.session.off("changeBreakpoint", this.$onChangeBreakpoint); + this.session.off("changeAnnotation", this.$onChangeAnnotation); + this.session.off("changeOverwrite", this.$onCursorChange); + this.session.off("changeScrollTop", this.$onScrollTopChange); + this.session.off("changeScrollLeft", this.$onScrollLeftChange); + + var selection = this.session.getSelection(); + selection.off("changeCursor", this.$onCursorChange); + selection.off("changeSelection", this.$onSelectionChange); + } + + this.session = session; + if (session) { + this.$onDocumentChange = this.onDocumentChange.bind(this); + session.on("change", this.$onDocumentChange); + this.renderer.setSession(session); + + this.$onChangeMode = this.onChangeMode.bind(this); + session.on("changeMode", this.$onChangeMode); + + this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this); + session.on("tokenizerUpdate", this.$onTokenizerUpdate); + + this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer); + session.on("changeTabSize", this.$onChangeTabSize); + + this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this); + session.on("changeWrapLimit", this.$onChangeWrapLimit); + + this.$onChangeWrapMode = this.onChangeWrapMode.bind(this); + session.on("changeWrapMode", this.$onChangeWrapMode); + + this.$onChangeFold = this.onChangeFold.bind(this); + session.on("changeFold", this.$onChangeFold); + + this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this); + this.session.on("changeFrontMarker", this.$onChangeFrontMarker); + + this.$onChangeBackMarker = this.onChangeBackMarker.bind(this); + this.session.on("changeBackMarker", this.$onChangeBackMarker); + + this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this); + this.session.on("changeBreakpoint", this.$onChangeBreakpoint); + + this.$onChangeAnnotation = this.onChangeAnnotation.bind(this); + this.session.on("changeAnnotation", this.$onChangeAnnotation); + + this.$onCursorChange = this.onCursorChange.bind(this); + this.session.on("changeOverwrite", this.$onCursorChange); + + this.$onScrollTopChange = this.onScrollTopChange.bind(this); + this.session.on("changeScrollTop", this.$onScrollTopChange); + + this.$onScrollLeftChange = this.onScrollLeftChange.bind(this); + this.session.on("changeScrollLeft", this.$onScrollLeftChange); + + this.selection = session.getSelection(); + this.selection.on("changeCursor", this.$onCursorChange); + + this.$onSelectionChange = this.onSelectionChange.bind(this); + this.selection.on("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(); + } else { + this.selection = null; + this.renderer.setSession(session); + } + + this._signal("changeSession", { + session: session, + oldSession: oldSession + }); + + this.curOp = null; + + oldSession && oldSession._signal("changeEditor", {oldEditor: this}); + session && session._signal("changeEditor", {editor: this}); + }; + 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, cb) { + this.renderer.setTheme(theme, cb); + }; + this.getTheme = function() { + return this.renderer.getTheme(); + }; + this.setStyle = function(style) { + this.renderer.setStyle(style); + }; + this.unsetStyle = function(style) { + this.renderer.unsetStyle(style); + }; + this.getFontSize = function () { + return this.getOption("fontSize") || + dom.computedStyle(this.container, "fontSize"); + }; + this.setFontSize = function(size) { + this.setOption("fontSize", size); + }; + + this.$highlightBrackets = function() { + if (this.session.$bracketHighlight) { + this.session.removeMarker(this.session.$bracketHighlight); + this.session.$bracketHighlight = null; + } + + if (this.$highlightPending) { + return; + } + var self = this; + this.$highlightPending = true; + setTimeout(function() { + self.$highlightPending = false; + var session = self.session; + if (!session || !session.bgTokenizer) return; + var pos = session.findMatchingBracket(self.getCursorPosition()); + if (pos) { + var range = new Range(pos.row, pos.column, pos.row, pos.column + 1); + } else if (session.$mode.getMatching) { + var range = session.$mode.getMatching(self.session); + } + if (range) + session.$bracketHighlight = session.addMarker(range, "ace_bracket", "text"); + }, 50); + }; + this.$highlightTags = function() { + if (this.$highlightTagPending) + return; + var self = this; + this.$highlightTagPending = true; + setTimeout(function() { + self.$highlightTagPending = false; + + var session = self.session; + if (!session || !session.bgTokenizer) return; + + var pos = self.getCursorPosition(); + var iterator = new TokenIterator(self.session, pos.row, pos.column); + var token = iterator.getCurrentToken(); + + if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) { + session.removeMarker(session.$tagHighlight); + session.$tagHighlight = null; + return; + } + + if (token.type.indexOf("tag-open") != -1) { + token = iterator.stepForward(); + if (!token) + return; + } + + var tag = token.value; + var depth = 0; + var prevToken = iterator.stepBackward(); + + if (prevToken.value == '<'){ + do { + prevToken = token; + token = iterator.stepForward(); + + if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { + if (prevToken.value === '<'){ + depth++; + } else if (prevToken.value === '= 0); + } else { + do { + token = prevToken; + prevToken = iterator.stepBackward(); + + if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { + if (prevToken.value === '<') { + depth++; + } else if (prevToken.value === ' 1)) + highlight = false; + } + + if (session.$highlightLineMarker && !highlight) { + session.removeMarker(session.$highlightLineMarker.id); + session.$highlightLineMarker = null; + } else if (!session.$highlightLineMarker && highlight) { + var range = new Range(highlight.row, highlight.column, highlight.row, Infinity); + range.id = session.addMarker(range, "ace_active-line", "screenLine"); + session.$highlightLineMarker = range; + } else if (highlight) { + session.$highlightLineMarker.start.row = highlight.row; + session.$highlightLineMarker.end.row = highlight.row; + session.$highlightLineMarker.start.column = highlight.column; + session._signal("changeBackMarker"); + } + }; + + 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._signal("changeSelection"); + }; + + 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)); + 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(e) { + this.renderer.updateText(); + this._emit("changeMode", e); + }; + + + this.onChangeWrapLimit = function() { + this.renderer.updateFull(); + }; + + this.onChangeWrapMode = function() { + this.renderer.onResize(true); + }; + + + this.onChangeFold = function() { + this.$updateHighlightActiveLine(); + this.renderer.updateFull(); + }; + this.getSelectedText = function() { + return this.session.getTextRange(this.getSelectionRange()); + }; + this.getCopyText = function() { + var text = this.getSelectedText(); + this._signal("copy", text); + return text; + }; + this.onCopy = function() { + this.commands.exec("copy", this); + }; + this.onCut = function() { + this.commands.exec("cut", this); + }; + this.onPaste = function(text, event) { + var e = {text: text, event: event}; + this.commands.exec("paste", this, e); + }; + + this.$handlePaste = function(e) { + if (typeof e == "string") + e = {text: e}; + this._signal("paste", e); + var text = e.text; + if (!this.inMultiSelectMode || this.inVirtualSelectionMode) { + this.insert(text); + } else { + 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.execCommand = function(command, args) { + return this.commands.exec(command, this, args); + }; + this.insert = function(text, pasted) { + var session = this.session; + var mode = session.getMode(); + var cursor = this.getCursorPosition(); + + if (this.getBehavioursEnabled() && !pasted) { + var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text); + if (transform) { + if (text !== transform.text) { + this.session.mergeUndoDeltas = false; + this.$mergeNextCommand = false; + } + text = transform.text; + + } + } + + if (text == "\t") + text = this.session.getTabString(); + if (!this.selection.isEmpty()) { + var range = this.getSelectionRange(); + cursor = this.session.remove(range); + this.clearSelection(); + } + else if (this.session.getOverwrite()) { + var range = new Range.fromPoints(cursor, cursor); + range.end.column += text.length; + this.session.remove(range); + } + + if (text == "\n" || text == "\r\n") { + var line = session.getLine(cursor.row); + if (cursor.column > line.search(/\S|$/)) { + var d = line.substr(cursor.column).search(/\S|$/); + session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d); + } + } + this.clearSelection(); + + var start = cursor.column; + var lineState = session.getState(cursor.row); + var line = session.getLine(cursor.row); + var shouldOutdent = mode.checkOutdent(lineState, line, text); + 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])); + } + } + + if (session.getDocument().isNewLine(text)) { + var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString()); + + session.insert({row: cursor.row+1, column: 0}, 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.setOption("scrollSpeed", speed); + }; + this.getScrollSpeed = function() { + return this.getOption("scrollSpeed"); + }; + this.setDragDelay = function(dragDelay) { + this.setOption("dragDelay", dragDelay); + }; + this.getDragDelay = function() { + return this.getOption("dragDelay"); + }; + this.setSelectionStyle = function(val) { + this.setOption("selectionStyle", val); + }; + this.getSelectionStyle = function() { + return this.getOption("selectionStyle"); + }; + this.setHighlightActiveLine = function(shouldHighlight) { + this.setOption("highlightActiveLine", shouldHighlight); + }; + this.getHighlightActiveLine = function() { + return this.getOption("highlightActiveLine"); + }; + this.setHighlightGutterLine = function(shouldHighlight) { + this.setOption("highlightGutterLine", shouldHighlight); + }; + + this.getHighlightGutterLine = function() { + return this.getOption("highlightGutterLine"); + }; + this.setHighlightSelectedWord = function(shouldHighlight) { + this.setOption("highlightSelectedWord", shouldHighlight); + }; + 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) { + this.renderer.setShowInvisibles(showInvisibles); + }; + this.getShowInvisibles = function() { + return this.renderer.getShowInvisibles(); + }; + + this.setDisplayIndentGuides = function(display) { + this.renderer.setDisplayIndentGuides(display); + }; + + this.getDisplayIndentGuides = function() { + return this.renderer.getDisplayIndentGuides(); + }; + 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.setReadOnly = function(readOnly) { + this.setOption("readOnly", readOnly); + }; + this.getReadOnly = function() { + return this.getOption("readOnly"); + }; + this.setBehavioursEnabled = function (enabled) { + this.setOption("behavioursEnabled", enabled); + }; + this.getBehavioursEnabled = function () { + return this.getOption("behavioursEnabled"); + }; + this.setWrapBehavioursEnabled = function (enabled) { + this.setOption("wrapBehavioursEnabled", enabled); + }; + this.getWrapBehavioursEnabled = function () { + return this.getOption("wrapBehavioursEnabled"); + }; + this.setShowFoldWidgets = function(show) { + this.setOption("showFoldWidgets", show); + + }; + this.getShowFoldWidgets = function() { + return this.getOption("showFoldWidgets"); + }; + + this.setFadeFoldWidgets = function(fade) { + this.setOption("fadeFoldWidgets", fade); + }; + + this.getFadeFoldWidgets = function() { + return this.getOption("fadeFoldWidgets"); + }; + 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 (range.end.column === 0) { + var text = session.getTextRange(range); + if (text[text.length - 1] == "\n") { + var line = session.getLine(range.end.row); + if (/^\s+$/.test(line)) { + range.end.column = line.length; + } + } + } + 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) { + var rows = this.$getSelectedRows(); + session.indentRows(rows.first, rows.last, "\t"); + return; + } else if (range.start.column < range.end.column) { + var text = session.getTextRange(range); + if (!/^\s+$/.test(text)) { + var rows = this.$getSelectedRows(); + session.indentRows(rows.first, rows.last, "\t"); + return; + } + } + + var line = session.getLine(range.start.row); + var position = range.start; + var size = session.getTabSize(); + var column = session.documentToScreenColumn(position.row, position.column); + + if (this.session.getUseSoftTabs()) { + var count = (size - column % size); + var indentString = lang.stringRepeat(" ", count); + } else { + var count = column % size; + while (line[range.start.column - 1] == " " && count) { + range.start.column--; + count--; + } + this.selection.setSelectionRange(range); + indentString = "\t"; + } + return this.insert(indentString); + }; + this.blockIndent = function() { + var rows = this.$getSelectedRows(); + this.session.indentRows(rows.first, rows.last, "\t"); + }; + this.blockOutdent = function() { + var selection = this.session.getSelection(); + this.session.outdentRows(selection.getRange()); + }; + this.sortLines = function() { + var rows = this.$getSelectedRows(); + var session = this.session; + + var lines = []; + for (i = rows.first; i <= rows.last; i++) + lines.push(session.getLine(i)); + + lines.sort(function(a, b) { + if (a.toLowerCase() < b.toLowerCase()) return -1; + if (a.toLowerCase() > b.toLowerCase()) return 1; + return 0; + }); + + var deleteRange = new Range(0, 0, 0, 0); + for (var i = rows.first; i <= rows.last; i++) { + var line = session.getLine(i); + deleteRange.start.row = i; + deleteRange.end.row = i; + deleteRange.end.column = line.length; + session.replace(deleteRange, lines[i-rows.first]); + } + }; + 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.toggleBlockComment = function() { + var cursor = this.getCursorPosition(); + var state = this.session.getState(cursor.row); + var range = this.getSelectionRange(); + this.session.getMode().toggleBlockComment(state, this.session, range, cursor); + }; + this.getNumberAt = function(row, column) { + var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g; + _numberRx.lastIndex = 0; + + var s = this.session.getLine(row); + while (_numberRx.lastIndex < column) { + var m = _numberRx.exec(s); + if(m.index <= column && m.index+m[0].length >= column){ + var number = { + value: m[0], + start: m.index, + end: m.index+m[0].length + }; + return number; + } + } + return null; + }; + this.modifyNumber = function(amount) { + var row = this.selection.getCursor().row; + var column = this.selection.getCursor().column; + var charRange = new Range(row, column-1, row, column); + + var c = this.session.getTextRange(charRange); + if (!isNaN(parseFloat(c)) && isFinite(c)) { + var nr = this.getNumberAt(row, column); + if (nr) { + var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end; + var decimals = nr.start + nr.value.length - fp; + + var t = parseFloat(nr.value); + t *= Math.pow(10, decimals); + + + if(fp !== nr.end && column < fp){ + amount *= Math.pow(10, nr.end - column - 1); + } else { + amount *= Math.pow(10, nr.end - column); + } + + t += amount; + t /= Math.pow(10, decimals); + var nnr = t.toFixed(decimals); + var replaceRange = new Range(row, nr.start, row, nr.end); + this.session.replace(replaceRange, nnr); + this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length)); + + } + } + }; + this.removeLines = function() { + var rows = this.$getSelectedRows(); + this.session.removeFullLines(rows.first, rows.last); + this.clearSelection(); + }; + + this.duplicateSelection = function() { + var sel = this.selection; + var doc = this.session; + var range = sel.getRange(); + var reverse = sel.isBackwards(); + if (range.isEmpty()) { + var row = range.start.row; + doc.duplicateLines(row, row); + } else { + var point = reverse ? range.start : range.end; + var endPoint = doc.insert(point, doc.getTextRange(range), false); + range.start = point; + range.end = endPoint; + + sel.setSelectionRange(range, reverse); + } + }; + this.moveLinesDown = function() { + this.$moveLines(1, false); + }; + this.moveLinesUp = function() { + this.$moveLines(-1, false); + }; + this.moveText = function(range, toPosition, copy) { + return this.session.moveText(range, toPosition, copy); + }; + this.copyLinesUp = function() { + this.$moveLines(-1, true); + }; + this.copyLinesDown = function() { + this.$moveLines(1, true); + }; + this.$moveLines = function(dir, copy) { + var rows, moved; + var selection = this.selection; + if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) { + var range = selection.toOrientedRange(); + rows = this.$getSelectedRows(range); + moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir); + if (copy && dir == -1) moved = 0; + range.moveBy(moved, 0); + selection.fromOrientedRange(range); + } else { + var ranges = selection.rangeList.ranges; + selection.rangeList.detach(this.session); + this.inVirtualSelectionMode = true; + + var diff = 0; + var totalDiff = 0; + var l = ranges.length; + for (var i = 0; i < l; i++) { + var rangeIndex = i; + ranges[i].moveBy(diff, 0); + rows = this.$getSelectedRows(ranges[i]); + var first = rows.first; + var last = rows.last; + while (++i < l) { + if (totalDiff) ranges[i].moveBy(totalDiff, 0); + var subRows = this.$getSelectedRows(ranges[i]); + if (copy && subRows.first != last) + break; + else if (!copy && subRows.first > last + 1) + break; + last = subRows.last; + } + i--; + diff = this.session.$moveLines(first, last, copy ? 0 : dir); + if (copy && dir == -1) rangeIndex = i + 1; + while (rangeIndex <= i) { + ranges[rangeIndex].moveBy(diff, 0); + rangeIndex++; + } + if (!copy) diff = 0; + totalDiff += diff; + } + + selection.fromOrientedRange(selection.ranges[0]); + selection.rangeList.attach(this.session); + this.inVirtualSelectionMode = false; + } + }; + this.$getSelectedRows = function(range) { + range = (range || this.getSelectionRange()).collapseRows(); + + return { + first: this.session.getRowFoldStart(range.start.row), + last: this.session.getRowFoldEnd(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 pos = { + row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2), + column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2) + }; + this.renderer.alignCursor(pos, 0.5); + }; + 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(select, expand) { + var cursor = this.getCursorPosition(); + var iterator = new TokenIterator(this.session, cursor.row, cursor.column); + var prevToken = iterator.getCurrentToken(); + var token = prevToken || iterator.stepForward(); + + if (!token) return; + var matchType; + var found = false; + var depth = {}; + var i = cursor.column - token.start; + var bracketType; + var brackets = { + ")": "(", + "(": "(", + "]": "[", + "[": "[", + "{": "{", + "}": "{" + }; + + do { + if (token.value.match(/[{}()\[\]]/g)) { + for (; i < token.value.length && !found; i++) { + if (!brackets[token.value[i]]) { + continue; + } + + bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen"); + + if (isNaN(depth[bracketType])) { + depth[bracketType] = 0; + } + + switch (token.value[i]) { + case '(': + case '[': + case '{': + depth[bracketType]++; + break; + case ')': + case ']': + case '}': + depth[bracketType]--; + + if (depth[bracketType] === -1) { + matchType = 'bracket'; + found = true; + } + break; + } + } + } + else if (token && token.type.indexOf('tag-name') !== -1) { + if (isNaN(depth[token.value])) { + depth[token.value] = 0; + } + + if (prevToken.value === '<') { + depth[token.value]++; + } + else if (prevToken.value === '= 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; + } + 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(); + this._signal("destroy", this); + if (this.session) { + this.session.destroy(); + } + }; + this.setAutoScrollEditorIntoView = function(enable) { + if (!enable) + return; + var rect; + var self = this; + var shouldScroll = false; + if (!this.$scrollAnchor) + this.$scrollAnchor = document.createElement("div"); + var scrollAnchor = this.$scrollAnchor; + scrollAnchor.style.cssText = "position:absolute"; + this.container.insertBefore(scrollAnchor, this.container.firstChild); + var onChangeSelection = this.on("changeSelection", function() { + shouldScroll = true; + }); + var onBeforeRender = this.renderer.on("beforeRender", function() { + if (shouldScroll) + rect = self.renderer.container.getBoundingClientRect(); + }); + var onAfterRender = this.renderer.on("afterRender", function() { + if (shouldScroll && rect && (self.isFocused() + || self.searchBox && self.searchBox.isFocused()) + ) { + var renderer = self.renderer; + var pos = renderer.$cursorLayer.$pixelPos; + var config = renderer.layerConfig; + var top = pos.top - config.offset; + if (pos.top >= 0 && top + rect.top < 0) { + shouldScroll = true; + } else if (pos.top < config.height && + pos.top + rect.top + config.lineHeight > window.innerHeight) { + shouldScroll = false; + } else { + shouldScroll = null; + } + if (shouldScroll != null) { + scrollAnchor.style.top = top + "px"; + scrollAnchor.style.left = pos.left + "px"; + scrollAnchor.style.height = config.lineHeight + "px"; + scrollAnchor.scrollIntoView(shouldScroll); + } + shouldScroll = rect = null; + } + }); + this.setAutoScrollEditorIntoView = function(enable) { + if (enable) + return; + delete this.setAutoScrollEditorIntoView; + this.off("changeSelection", onChangeSelection); + this.renderer.off("afterRender", onAfterRender); + this.renderer.off("beforeRender", onBeforeRender); + }; + }; + + + this.$resetCursorStyle = function() { + var style = this.$cursorStyle || "ace"; + var cursorLayer = this.renderer.$cursorLayer; + if (!cursorLayer) + return; + cursorLayer.setSmoothBlinking(/smooth/.test(style)); + cursorLayer.isBlinking = !this.$readOnly && style != "wide"; + dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style)); + }; + +}).call(Editor.prototype); + + + +config.defineOptions(Editor.prototype, "editor", { + selectionStyle: { + set: function(style) { + this.onSelectionChange(); + this._signal("changeSelectionStyle", {data: style}); + }, + initialValue: "line" + }, + highlightActiveLine: { + set: function() {this.$updateHighlightActiveLine();}, + initialValue: true + }, + highlightSelectedWord: { + set: function(shouldHighlight) {this.$onSelectionChange();}, + initialValue: true + }, + readOnly: { + set: function(readOnly) { + this.$resetCursorStyle(); + }, + initialValue: false + }, + cursorStyle: { + set: function(val) { this.$resetCursorStyle(); }, + values: ["ace", "slim", "smooth", "wide"], + initialValue: "ace" + }, + mergeUndoDeltas: { + values: [false, true, "always"], + initialValue: true + }, + behavioursEnabled: {initialValue: true}, + wrapBehavioursEnabled: {initialValue: true}, + autoScrollEditorIntoView: { + set: function(val) {this.setAutoScrollEditorIntoView(val)} + }, + keyboardHandler: { + set: function(val) { this.setKeyboardHandler(val); }, + get: function() { return this.keybindingId; }, + handlesSet: true + }, + + hScrollBarAlwaysVisible: "renderer", + vScrollBarAlwaysVisible: "renderer", + highlightGutterLine: "renderer", + animatedScroll: "renderer", + showInvisibles: "renderer", + showPrintMargin: "renderer", + printMarginColumn: "renderer", + printMargin: "renderer", + fadeFoldWidgets: "renderer", + showFoldWidgets: "renderer", + showLineNumbers: "renderer", + showGutter: "renderer", + displayIndentGuides: "renderer", + fontSize: "renderer", + fontFamily: "renderer", + maxLines: "renderer", + minLines: "renderer", + scrollPastEnd: "renderer", + fixedWidthGutter: "renderer", + theme: "renderer", + + scrollSpeed: "$mouseHandler", + dragDelay: "$mouseHandler", + dragEnabled: "$mouseHandler", + focusTimout: "$mouseHandler", + tooltipFollowsMouse: "$mouseHandler", + + firstLineNumber: "session", + overwrite: "session", + newLineMode: "session", + useWorker: "session", + useSoftTabs: "session", + tabSize: "session", + wrap: "session", + indentedSoftWrap: "session", + foldStyle: "session", + mode: "session" +}); + +exports.Editor = Editor; +}); + +ace.define("ace/undomanager",["require","exports","module"], function(acequire, exports, module) { +"use strict"; +var UndoManager = function() { + this.reset(); +}; + +(function() { + this.execute = function(options) { + var deltaSets = options.args[0]; + this.$doc = options.args[1]; + if (options.merge && this.hasUndo()){ + this.dirtyCounter--; + deltaSets = this.$undoStack.pop().concat(deltaSets); + } + this.$undoStack.push(deltaSets); + this.$redoStack = []; + if (this.dirtyCounter < 0) { + this.dirtyCounter = NaN; + } + this.dirtyCounter++; + }; + this.undo = function(dontSelect) { + var deltaSets = this.$undoStack.pop(); + var undoSelectionRange = null; + if (deltaSets) { + undoSelectionRange = this.$doc.undoChanges(deltaSets, dontSelect); + this.$redoStack.push(deltaSets); + this.dirtyCounter--; + } + + return undoSelectionRange; + }; + this.redo = function(dontSelect) { + var deltaSets = this.$redoStack.pop(); + var redoSelectionRange = null; + if (deltaSets) { + redoSelectionRange = + this.$doc.redoChanges(this.$deserializeDeltas(deltaSets), dontSelect); + this.$undoStack.push(deltaSets); + this.dirtyCounter++; + } + return redoSelectionRange; + }; + this.reset = function() { + this.$undoStack = []; + this.$redoStack = []; + this.dirtyCounter = 0; + }; + this.hasUndo = function() { + return this.$undoStack.length > 0; + }; + this.hasRedo = function() { + return this.$redoStack.length > 0; + }; + this.markClean = function() { + this.dirtyCounter = 0; + }; + this.isClean = function() { + return this.dirtyCounter === 0; + }; + this.$serializeDeltas = function(deltaSets) { + return cloneDeltaSetsObj(deltaSets, $serializeDelta); + }; + this.$deserializeDeltas = function(deltaSets) { + return cloneDeltaSetsObj(deltaSets, $deserializeDelta); + }; + + function $serializeDelta(delta){ + return { + action: delta.action, + start: delta.start, + end: delta.end, + lines: delta.lines.length == 1 ? null : delta.lines, + text: delta.lines.length == 1 ? delta.lines[0] : null + }; + } + + function $deserializeDelta(delta) { + return { + action: delta.action, + start: delta.start, + end: delta.end, + lines: delta.lines || [delta.text] + }; + } + + function cloneDeltaSetsObj(deltaSets_old, fnGetModifiedDelta) { + var deltaSets_new = new Array(deltaSets_old.length); + for (var i = 0; i < deltaSets_old.length; i++) { + var deltaSet_old = deltaSets_old[i]; + var deltaSet_new = { group: deltaSet_old.group, deltas: new Array(deltaSet_old.length)}; + + for (var j = 0; j < deltaSet_old.deltas.length; j++) { + var delta_old = deltaSet_old.deltas[j]; + deltaSet_new.deltas[j] = fnGetModifiedDelta(delta_old); + } + + deltaSets_new[i] = deltaSet_new; + } + return deltaSets_new; + } + +}).call(UndoManager.prototype); + +exports.UndoManager = UndoManager; +}); + +ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var oop = acequire("../lib/oop"); +var lang = acequire("../lib/lang"); +var EventEmitter = acequire("../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.$annotations = []; + this.$updateAnnotations = this.$updateAnnotations.bind(this); + + this.$cells = []; +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.setSession = function(session) { + if (this.session) + this.session.removeEventListener("change", this.$updateAnnotations); + this.session = session; + if (session) + session.on("change", this.$updateAnnotations); + }; + + this.addGutterDecoration = function(row, className){ + if (window.console) + console.warn && console.warn("deprecated use session.addGutterDecoration"); + this.session.addGutterDecoration(row, className); + }; + + this.removeGutterDecoration = function(row, className){ + if (window.console) + console.warn && console.warn("deprecated use session.removeGutterDecoration"); + this.session.removeGutterDecoration(row, className); + }; + + this.setAnnotations = function(annotations) { + this.$annotations = []; + for (var i = 0; i < annotations.length; i++) { + var annotation = annotations[i]; + var row = annotation.row; + var rowInfo = this.$annotations[row]; + if (!rowInfo) + rowInfo = this.$annotations[row] = {text: []}; + + var annoText = annotation.text; + annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || ""; + + if (rowInfo.text.indexOf(annoText) === -1) + rowInfo.text.push(annoText); + + var type = annotation.type; + if (type == "error") + rowInfo.className = " ace_error"; + else if (type == "warning" && rowInfo.className != " ace_error") + rowInfo.className = " ace_warning"; + else if (type == "info" && (!rowInfo.className)) + rowInfo.className = " ace_info"; + } + }; + + this.$updateAnnotations = function (delta) { + if (!this.$annotations.length) + return; + var firstRow = delta.start.row; + var len = delta.end.row - firstRow; + if (len === 0) { + } else if (delta.action == 'remove') { + this.$annotations.splice(firstRow, len + 1, null); + } else { + var args = new Array(len + 1); + args.unshift(firstRow, 1); + this.$annotations.splice.apply(this.$annotations, args); + } + }; + + this.update = function(config) { + var session = this.session; + var firstRow = config.firstRow; + var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar + session.getLength() - 1); + var fold = session.getNextFoldLine(firstRow); + var foldStart = fold ? fold.start.row : Infinity; + var foldWidgets = this.$showFoldWidgets && session.foldWidgets; + var breakpoints = session.$breakpoints; + var decorations = session.$decorations; + var firstLineNumber = session.$firstLineNumber; + var lastLineNumber = 0; + + var gutterRenderer = session.gutterRenderer || this.$renderer; + + var cell = null; + var index = -1; + var row = firstRow; + while (true) { + if (row > foldStart) { + row = fold.end.row + 1; + fold = session.getNextFoldLine(row, fold); + foldStart = fold ? fold.start.row : Infinity; + } + if (row > lastRow) { + while (this.$cells.length > index + 1) { + cell = this.$cells.pop(); + this.element.removeChild(cell.element); + } + break; + } + + cell = this.$cells[++index]; + if (!cell) { + cell = {element: null, textNode: null, foldWidget: null}; + cell.element = dom.createElement("div"); + cell.textNode = document.createTextNode(''); + cell.element.appendChild(cell.textNode); + this.element.appendChild(cell.element); + this.$cells[index] = cell; + } + + var className = "ace_gutter-cell "; + if (breakpoints[row]) + className += breakpoints[row]; + if (decorations[row]) + className += decorations[row]; + if (this.$annotations[row]) + className += this.$annotations[row].className; + if (cell.element.className != className) + cell.element.className = className; + + var height = session.getRowLength(row) * config.lineHeight + "px"; + if (height != cell.element.style.height) + cell.element.style.height = height; + + if (foldWidgets) { + var c = foldWidgets[row]; + if (c == null) + c = foldWidgets[row] = session.getFoldWidget(row); + } + + if (c) { + if (!cell.foldWidget) { + cell.foldWidget = dom.createElement("span"); + cell.element.appendChild(cell.foldWidget); + } + var className = "ace_fold-widget ace_" + c; + if (c == "start" && row == foldStart && row < fold.end.row) + className += " ace_closed"; + else + className += " ace_open"; + if (cell.foldWidget.className != className) + cell.foldWidget.className = className; + + var height = config.lineHeight + "px"; + if (cell.foldWidget.style.height != height) + cell.foldWidget.style.height = height; + } else { + if (cell.foldWidget) { + cell.element.removeChild(cell.foldWidget); + cell.foldWidget = null; + } + } + + var text = lastLineNumber = gutterRenderer + ? gutterRenderer.getText(session, row) + : row + firstLineNumber; + if (text != cell.textNode.data) + cell.textNode.data = text; + + row++; + } + + this.element.style.height = config.minHeight + "px"; + + if (this.$fixedWidth || session.$useWrapMode) + lastLineNumber = session.getLength() + firstLineNumber; + + var gutterWidth = gutterRenderer + ? gutterRenderer.getWidth(session, lastLineNumber, config) + : lastLineNumber.toString().length * config.characterWidth; + + var padding = this.$padding || this.$computePadding(); + gutterWidth += padding.left + padding.right; + if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) { + this.gutterWidth = gutterWidth; + this.element.style.width = Math.ceil(this.gutterWidth) + "px"; + this._emit("changeGutterWidth", gutterWidth); + } + }; + + this.$fixedWidth = false; + + this.$showLineNumbers = true; + this.$renderer = ""; + this.setShowLineNumbers = function(show) { + this.$renderer = !show && { + getWidth: function() {return ""}, + getText: function() {return ""} + }; + }; + + this.getShowLineNumbers = function() { + return this.$showLineNumbers; + }; + + this.$showFoldWidgets = true; + this.setShowFoldWidgets = function(show) { + if (show) + dom.addCssClass(this.element, "ace_folding-enabled"); + else + dom.removeCssClass(this.element, "ace_folding-enabled"); + + this.$showFoldWidgets = show; + this.$padding = null; + }; + + this.getShowFoldWidgets = function() { + return this.$showFoldWidgets; + }; + + this.$computePadding = function() { + if (!this.element.firstChild) + return {left: 0, right: 0}; + var style = dom.computedStyle(this.element.firstChild); + this.$padding = {}; + this.$padding.left = parseInt(style.paddingLeft) + 1 || 0; + this.$padding.right = parseInt(style.paddingRight) || 0; + return this.$padding; + }; + + this.getRegion = function(point) { + var padding = this.$padding || this.$computePadding(); + var rect = this.element.getBoundingClientRect(); + if (point.x < padding.left + rect.left) + return "markers"; + if (this.$showFoldWidgets && point.x > rect.right - padding.right) + return "foldWidgets"; + }; + +}).call(Gutter.prototype); + +exports.Gutter = Gutter; + +}); + +ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../range").Range; +var dom = acequire("../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 = this.$padding + range.start.column * config.characterWidth; + marker.renderer(html, range, left, top, config); + } else if (marker.type == "fullLine") { + this.drawFullLineMarker(html, range, marker.clazz, config); + } else if (marker.type == "screenLine") { + this.drawScreenLineMarker(html, range, marker.clazz, config); + } else if (range.isMultiLine()) { + if (marker.type == "text") + this.drawTextMarker(html, range, marker.clazz, config); + else + this.drawMultiLineMarker(html, range, marker.clazz, config); + } else { + this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config); + } + } + this.element.innerHTML = html.join(""); + }; + + this.$getTop = function(row, layerConfig) { + return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight; + }; + + function getBorderClass(tl, tr, br, bl) { + return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0); + } + this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) { + var session = this.session; + var start = range.start.row; + var end = range.end.row; + var row = start; + var prev = 0; + var curr = 0; + var next = session.getScreenLastRowColumn(row); + var lineRange = new Range(row, range.start.column, row, curr); + for (; row <= end; row++) { + lineRange.start.row = lineRange.end.row = row; + lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row); + lineRange.end.column = next; + prev = curr; + curr = next; + next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column; + this.drawSingleLineMarker(stringBuilder, lineRange, + clazz + (row == start ? " ace_start" : "") + " ace_br" + + getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end), + layerConfig, row == end ? 0 : 1, extraStyle); + } + }; + this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var padding = this.$padding; + var height = config.lineHeight; + var top = this.$getTop(range.start.row, config); + var left = padding + range.start.column * config.characterWidth; + extraStyle = extraStyle || ""; + + stringBuilder.push( + "
" + ); + top = this.$getTop(range.end.row, config); + var width = range.end.column * config.characterWidth; + + stringBuilder.push( + "
" + ); + height = (range.end.row - range.start.row - 1) * config.lineHeight; + if (height <= 0) + return; + top = this.$getTop(range.start.row + 1, config); + + var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8); + + stringBuilder.push( + "
" + ); + }; + this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { + var height = config.lineHeight; + var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth; + + var top = this.$getTop(range.start.row, config); + var left = this.$padding + range.start.column * config.characterWidth; + + stringBuilder.push( + "
" + ); + }; + + this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var top = this.$getTop(range.start.row, config); + var height = config.lineHeight; + if (range.start.row != range.end.row) + height += this.$getTop(range.end.row, config) - top; + + stringBuilder.push( + "
" + ); + }; + + this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { + var top = this.$getTop(range.start.row, config); + var height = config.lineHeight; + + stringBuilder.push( + "
" + ); + }; + +}).call(Marker.prototype); + +exports.Marker = Marker; + +}); + +ace.define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var dom = acequire("../lib/dom"); +var lang = acequire("../lib/lang"); +var useragent = acequire("../lib/useragent"); +var EventEmitter = acequire("../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.$updateEolChar = this.$updateEolChar.bind(this); +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.EOF_CHAR = "\xB6"; + this.EOL_CHAR_LF = "\xAC"; + this.EOL_CHAR_CRLF = "\xa4"; + this.EOL_CHAR = this.EOL_CHAR_LF; + this.TAB_CHAR = "\u2014"; //"\u21E5"; + this.SPACE_CHAR = "\xB7"; + this.$padding = 0; + + this.$updateEolChar = function() { + var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n" + ? this.EOL_CHAR_LF + : this.EOL_CHAR_CRLF; + if (this.EOL_CHAR != EOL_CHAR) { + this.EOL_CHAR = EOL_CHAR; + return true; + } + } + + this.setPadding = function(padding) { + this.$padding = padding; + this.element.style.padding = "0 " + padding + "px"; + }; + + this.getLineHeight = function() { + return this.$fontMetrics.$characterSize.height || 0; + }; + + this.getCharacterWidth = function() { + return this.$fontMetrics.$characterSize.width || 0; + }; + + this.$setFontMetrics = function(measure) { + this.$fontMetrics = measure; + this.$fontMetrics.on("changeCharacterSize", function(e) { + this._signal("changeCharacterSize", e); + }.bind(this)); + this.$pollSizeChanges(); + } + + this.checkForSizeChanges = function() { + this.$fontMetrics.checkForSizeChanges(); + }; + this.$pollSizeChanges = function() { + return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges(); + }; + this.setSession = function(session) { + this.session = session; + if (session) + this.$computeTabString(); + }; + + this.showInvisibles = false; + this.setShowInvisibles = function(showInvisibles) { + if (this.showInvisibles == showInvisibles) + return false; + + this.showInvisibles = showInvisibles; + this.$computeTabString(); + return true; + }; + + this.displayIndentGuides = true; + this.setDisplayIndentGuides = function(display) { + if (this.displayIndentGuides == display) + return false; + + this.displayIndentGuides = display; + this.$computeTabString(); + return true; + }; + + this.$tabStrings = []; + this.onChangeTabSize = + this.$computeTabString = function() { + var tabSize = this.session.getTabSize(); + this.tabSize = tabSize; + var tabStr = this.$tabStrings = [0]; + for (var i = 1; i < tabSize + 1; i++) { + if (this.showInvisibles) { + tabStr.push("" + + lang.stringRepeat(this.TAB_CHAR, i) + + ""); + } else { + tabStr.push(lang.stringRepeat(" ", i)); + } + } + if (this.displayIndentGuides) { + this.$indentGuideRe = /\s\S| \t|\t |\s$/; + var className = "ace_indent-guide"; + var spaceClass = ""; + var tabClass = ""; + if (this.showInvisibles) { + className += " ace_invisible"; + spaceClass = " ace_invisible_space"; + tabClass = " ace_invisible_tab"; + var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize); + var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize); + } else{ + var spaceContent = lang.stringRepeat(" ", this.tabSize); + var tabContent = spaceContent; + } + + this.$tabStrings[" "] = "" + spaceContent + ""; + this.$tabStrings["\t"] = "" + tabContent + ""; + } + }; + + this.updateLines = function(config, firstRow, lastRow) { + if (this.config.lastRow != config.lastRow || + this.config.firstRow != config.firstRow) { + this.scrollLines(config); + } + this.config = config; + + var first = Math.max(firstRow, config.firstRow); + var last = Math.min(lastRow, config.lastRow); + + var lineElements = this.element.childNodes; + var lineElementsIdx = 0; + + for (var row = config.firstRow; row < first; row++) { + var foldLine = this.session.getFoldLine(row); + if (foldLine) { + if (foldLine.containsRow(first)) { + first = foldLine.start.row; + break; + } else { + row = foldLine.end.row; + } + } + lineElementsIdx ++; + } + + var row = first; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row :Infinity; + } + if (row > last) + break; + + var lineElement = lineElements[lineElementsIdx++]; + if (lineElement) { + var html = []; + this.$renderLine( + html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false + ); + lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; + lineElement.innerHTML = html.join(""); + } + row++; + } + }; + + this.scrollLines = function(config) { + var oldConfig = this.config; + this.config = config; + + if (!oldConfig || oldConfig.lastRow < config.firstRow) + return this.update(config); + + if (config.lastRow < oldConfig.firstRow) + return this.update(config); + + var el = this.element; + if (oldConfig.firstRow < config.firstRow) + for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--) + el.removeChild(el.firstChild); + + if (oldConfig.lastRow > config.lastRow) + for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--) + el.removeChild(el.lastChild); + + if (config.firstRow < oldConfig.firstRow) { + var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1); + if (el.firstChild) + el.insertBefore(fragment, el.firstChild); + else + el.appendChild(fragment); + } + + if (config.lastRow > oldConfig.lastRow) { + var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow); + el.appendChild(fragment); + } + }; + + this.$renderLinesFragment = function(config, firstRow, lastRow) { + var fragment = this.element.ownerDocument.createDocumentFragment(); + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row : Infinity; + } + if (row > lastRow) + break; + + var container = dom.createElement("div"); + + var html = []; + this.$renderLine(html, row, false, row == foldStart ? foldLine : false); + container.innerHTML = html.join(""); + if (this.$useLineGroups()) { + container.className = 'ace_line_group'; + fragment.appendChild(container); + container.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; + + } else { + while(container.firstChild) + fragment.appendChild(container.firstChild); + } + + row++; + } + return fragment; + }; + + this.update = function(config) { + this.config = config; + + var html = []; + var firstRow = config.firstRow, lastRow = config.lastRow; + + var row = firstRow; + var foldLine = this.session.getNextFoldLine(row); + var foldStart = foldLine ? foldLine.start.row : Infinity; + + while (true) { + if (row > foldStart) { + row = foldLine.end.row+1; + foldLine = this.session.getNextFoldLine(row, foldLine); + foldStart = foldLine ? foldLine.start.row :Infinity; + } + if (row > lastRow) + break; + + if (this.$useLineGroups()) + html.push("
") + + this.$renderLine(html, row, false, row == foldStart ? foldLine : false); + + if (this.$useLineGroups()) + html.push("
"); // end the line group + + row++; + } + this.element.innerHTML = html.join(""); + }; + + this.$textToken = { + "text": true, + "rparen": true, + "lparen": true + }; + + this.$renderToken = function(stringBuilder, screenColumn, token, value) { + var self = this; + var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g; + var replaceFunc = function(c, a, b, tabIdx, idx4) { + if (a) { + return self.showInvisibles + ? "" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "" + : c; + } else if (c == "&") { + return "&"; + } else if (c == "<") { + return "<"; + } else if (c == ">") { + return ">"; + } else if (c == "\t") { + var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx); + screenColumn += tabSize - 1; + return self.$tabStrings[tabSize]; + } else if (c == "\u3000") { + var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk"; + var space = self.showInvisibles ? self.SPACE_CHAR : ""; + screenColumn += 1; + return "" + space + ""; + } else if (b) { + return "" + self.SPACE_CHAR + ""; + } else { + screenColumn += 1; + return "" + c + ""; + } + }; + + 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("", output, ""); + } + else { + stringBuilder.push(output); + } + return screenColumn + value.length; + }; + + this.renderIndentGuide = function(stringBuilder, value, max) { + var cols = value.search(this.$indentGuideRe); + if (cols <= 0 || cols >= max) + return value; + if (value[0] == " ") { + cols -= cols % this.tabSize; + stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize)); + return value.substr(cols); + } else if (value[0] == "\t") { + stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols)); + return value.substr(cols); + } + return value; + }; + + this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) { + var chars = 0; + var split = 0; + var splitChars = splits[0]; + var screenColumn = 0; + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i]; + var value = token.value; + if (i == 0 && this.displayIndentGuides) { + chars = value.length; + value = this.renderIndentGuide(stringBuilder, value, splitChars); + if (!value) + continue; + chars -= value.length; + } + + if (chars + value.length < splitChars) { + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + chars += value.length; + } else { + while (chars + value.length >= splitChars) { + screenColumn = this.$renderToken( + stringBuilder, screenColumn, + token, value.substring(0, splitChars - chars) + ); + value = value.substring(splitChars - chars); + chars = splitChars; + + if (!onlyContents) { + stringBuilder.push("", + "
" + ); + } + + stringBuilder.push(lang.stringRepeat("\xa0", splits.indent)); + + split ++; + screenColumn = 0; + splitChars = splits[split] || Number.MAX_VALUE; + } + if (value.length != 0) { + chars += value.length; + screenColumn = this.$renderToken( + stringBuilder, screenColumn, token, value + ); + } + } + } + }; + + this.$renderSimpleLine = function(stringBuilder, tokens) { + var screenColumn = 0; + var token = tokens[0]; + var value = token.value; + if (this.displayIndentGuides) + value = this.renderIndentGuide(stringBuilder, value); + if (value) + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + for (var i = 1; i < tokens.length; i++) { + token = tokens[i]; + value = token.value; + screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); + } + }; + this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) { + if (!foldLine && foldLine != false) + foldLine = this.session.getFoldLine(row); + + if (foldLine) + var tokens = this.$getFoldLineTokens(row, foldLine); + else + var tokens = this.session.getTokens(row); + + + if (!onlyContents) { + stringBuilder.push( + "
" + ); + } + + if (tokens.length) { + var splits = this.session.getRowSplitData(row); + if (splits && splits.length) + this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents); + else + this.$renderSimpleLine(stringBuilder, tokens); + } + + if (this.showInvisibles) { + if (foldLine) + row = foldLine.end.row + + stringBuilder.push( + "", + row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR, + "" + ); + } + if (!onlyContents) + stringBuilder.push("
"); + }; + + this.$getFoldLineTokens = function(row, foldLine) { + var session = this.session; + var renderTokens = []; + + function addTokens(tokens, from, to) { + var idx = 0, col = 0; + while ((col + tokens[idx].value.length) < from) { + col += tokens[idx].value.length; + idx++; + + if (idx == tokens.length) + return; + } + if (col != from) { + var value = tokens[idx].value.substring(from - col); + if (value.length > (to - from)) + value = value.substring(0, to - from); + + renderTokens.push({ + type: tokens[idx].type, + value: value + }); + + col = from + value.length; + idx += 1; + } + + while (col < to && idx < tokens.length) { + var value = tokens[idx].value; + if (value.length + col > to) { + renderTokens.push({ + type: tokens[idx].type, + value: value.substring(0, to - col) + }); + } else + renderTokens.push(tokens[idx]); + col += value.length; + idx += 1; + } + } + + var tokens = session.getTokens(row); + foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) { + if (placeholder != null) { + renderTokens.push({ + type: "fold", + value: placeholder + }); + } else { + if (isNewRow) + tokens = session.getTokens(row); + + if (tokens.length) + addTokens(tokens, lastColumn, column); + } + }, foldLine.end.row, this.session.getLine(foldLine.end.row).length); + + return renderTokens; + }; + + this.$useLineGroups = function() { + return this.session.getUseWrapMode(); + }; + + this.destroy = function() { + clearInterval(this.$pollSizeChangesTimer); + if (this.$measureNode) + this.$measureNode.parentNode.removeChild(this.$measureNode); + delete this.$measureNode; + }; + +}).call(Text.prototype); + +exports.Text = Text; + +}); + +ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +var isIE8; + +var Cursor = function(parentEl) { + this.element = dom.createElement("div"); + this.element.className = "ace_layer ace_cursor-layer"; + parentEl.appendChild(this.element); + + if (isIE8 === undefined) + isIE8 = !("opacity" in this.element.style); + + this.isVisible = false; + this.isBlinking = true; + this.blinkInterval = 1000; + this.smoothBlinking = false; + + this.cursors = []; + this.cursor = this.addCursor(); + dom.addCssClass(this.element, "ace_hidden-cursors"); + this.$updateCursors = (isIE8 + ? this.$updateVisibility + : this.$updateOpacity).bind(this); +}; + +(function() { + + this.$updateVisibility = function(val) { + var cursors = this.cursors; + for (var i = cursors.length; i--; ) + cursors[i].style.visibility = val ? "" : "hidden"; + }; + this.$updateOpacity = function(val) { + var cursors = this.cursors; + for (var i = cursors.length; i--; ) + cursors[i].style.opacity = val ? "" : "0"; + }; + + + this.$padding = 0; + this.setPadding = function(padding) { + this.$padding = padding; + }; + + this.setSession = function(session) { + this.session = session; + }; + + this.setBlinking = function(blinking) { + if (blinking != this.isBlinking){ + this.isBlinking = blinking; + this.restartTimer(); + } + }; + + this.setBlinkInterval = function(blinkInterval) { + if (blinkInterval != this.blinkInterval){ + this.blinkInterval = blinkInterval; + this.restartTimer(); + } + }; + + this.setSmoothBlinking = function(smoothBlinking) { + if (smoothBlinking != this.smoothBlinking && !isIE8) { + this.smoothBlinking = smoothBlinking; + dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking); + this.$updateCursors(true); + this.$updateCursors = (this.$updateOpacity).bind(this); + this.restartTimer(); + } + }; + + this.addCursor = function() { + var el = dom.createElement("div"); + el.className = "ace_cursor"; + 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; + dom.addCssClass(this.element, "ace_hidden-cursors"); + this.restartTimer(); + }; + + this.showCursor = function() { + this.isVisible = true; + dom.removeCssClass(this.element, "ace_hidden-cursors"); + this.restartTimer(); + }; + + this.restartTimer = function() { + var update = this.$updateCursors; + clearInterval(this.intervalId); + clearTimeout(this.timeoutId); + if (this.smoothBlinking) { + dom.removeCssClass(this.element, "ace_smooth-blinking"); + } + + update(true); + + if (!this.isBlinking || !this.blinkInterval || !this.isVisible) + return; + + if (this.smoothBlinking) { + setTimeout(function(){ + dom.addCssClass(this.element, "ace_smooth-blinking"); + }.bind(this)); + } + + var blink = function(){ + this.timeoutId = setTimeout(function() { + update(false); + }, 0.6 * this.blinkInterval); + }.bind(this); + + this.intervalId = setInterval(function() { + update(true); + blink(); + }, this.blinkInterval); + + blink(); + }; + + 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 = 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; + + var selections = this.session.$selectionMarkers; + var i = 0, cursorIndex = 0; + + if (selections === undefined || selections.length === 0){ + selections = [{cursor: null}]; + } + + for (var i = 0, n = selections.length; i < n; i++) { + var pixelPos = this.getPixelPosition(selections[i].cursor, true); + if ((pixelPos.top > config.height + config.offset || + pixelPos.top < 0) && i > 1) { + continue; + } + + var style = (this.cursors[cursorIndex++] || this.addCursor()).style; + + if (!this.drawCursor) { + style.left = pixelPos.left + "px"; + style.top = pixelPos.top + "px"; + style.width = config.characterWidth + "px"; + style.height = config.lineHeight + "px"; + } else { + this.drawCursor(style, pixelPos, config, selections[i], this.session); + } + } + while (this.cursors.length > cursorIndex) + this.removeCursor(); + + var overwrite = this.session.getOverwrite(); + this.$setOverwrite(overwrite); + this.$pixelPos = pixelPos; + this.restartTimer(); + }; + + this.drawCursor = null; + + this.$setOverwrite = function(overwrite) { + if (overwrite != this.overwrite) { + this.overwrite = overwrite; + if (overwrite) + dom.addCssClass(this.element, "ace_overwrite-cursors"); + else + dom.removeCssClass(this.element, "ace_overwrite-cursors"); + } + }; + + this.destroy = function() { + clearInterval(this.intervalId); + clearTimeout(this.timeoutId); + }; + +}).call(Cursor.prototype); + +exports.Cursor = Cursor; + +}); + +ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var event = acequire("./lib/event"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var MAX_SCROLL_H = 0x8000; +var ScrollBar = function(parent) { + this.element = dom.createElement("div"); + this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix; + + this.inner = dom.createElement("div"); + this.inner.className = "ace_scrollbar-inner"; + this.element.appendChild(this.inner); + + parent.appendChild(this.element); + + this.setVisible(false); + this.skipEvent = false; + + event.addListener(this.element, "scroll", this.onScroll.bind(this)); + event.addListener(this.element, "mousedown", event.preventDefault); +}; + +(function() { + oop.implement(this, EventEmitter); + + this.setVisible = function(isVisible) { + this.element.style.display = isVisible ? "" : "none"; + this.isVisible = isVisible; + this.coeff = 1; + }; +}).call(ScrollBar.prototype); +var VScrollBar = function(parent, renderer) { + ScrollBar.call(this, parent); + this.scrollTop = 0; + this.scrollHeight = 0; + renderer.$scrollbarWidth = + this.width = dom.scrollbarWidth(parent.ownerDocument); + this.inner.style.width = + this.element.style.width = (this.width || 15) + 5 + "px"; +}; + +oop.inherits(VScrollBar, ScrollBar); + +(function() { + + this.classSuffix = '-v'; + this.onScroll = function() { + if (!this.skipEvent) { + this.scrollTop = this.element.scrollTop; + if (this.coeff != 1) { + var h = this.element.clientHeight / this.scrollHeight; + this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h); + } + this._emit("scroll", {data: this.scrollTop}); + } + this.skipEvent = false; + }; + this.getWidth = function() { + return this.isVisible ? this.width : 0; + }; + this.setHeight = function(height) { + this.element.style.height = height + "px"; + }; + this.setInnerHeight = + this.setScrollHeight = function(height) { + this.scrollHeight = height; + if (height > MAX_SCROLL_H) { + this.coeff = MAX_SCROLL_H / height; + height = MAX_SCROLL_H; + } else if (this.coeff != 1) { + this.coeff = 1 + } + this.inner.style.height = height + "px"; + }; + this.setScrollTop = function(scrollTop) { + if (this.scrollTop != scrollTop) { + this.skipEvent = true; + this.scrollTop = scrollTop; + this.element.scrollTop = scrollTop * this.coeff; + } + }; + +}).call(VScrollBar.prototype); +var HScrollBar = function(parent, renderer) { + ScrollBar.call(this, parent); + this.scrollLeft = 0; + this.height = renderer.$scrollbarWidth; + this.inner.style.height = + this.element.style.height = (this.height || 15) + 5 + "px"; +}; + +oop.inherits(HScrollBar, ScrollBar); + +(function() { + + this.classSuffix = '-h'; + this.onScroll = function() { + if (!this.skipEvent) { + this.scrollLeft = this.element.scrollLeft; + this._emit("scroll", {data: this.scrollLeft}); + } + this.skipEvent = false; + }; + this.getHeight = function() { + return this.isVisible ? this.height : 0; + }; + this.setWidth = function(width) { + this.element.style.width = width + "px"; + }; + this.setInnerWidth = function(width) { + this.inner.style.width = width + "px"; + }; + this.setScrollWidth = function(width) { + this.inner.style.width = width + "px"; + }; + this.setScrollLeft = function(scrollLeft) { + if (this.scrollLeft != scrollLeft) { + this.skipEvent = true; + this.scrollLeft = this.element.scrollLeft = scrollLeft; + } + }; + +}).call(HScrollBar.prototype); + + +exports.ScrollBar = VScrollBar; // backward compatibility +exports.ScrollBarV = VScrollBar; // backward compatibility +exports.ScrollBarH = HScrollBar; // backward compatibility + +exports.VScrollBar = VScrollBar; +exports.HScrollBar = HScrollBar; +}); + +ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(acequire, exports, module) { +"use strict"; + +var event = acequire("./lib/event"); + + +var RenderLoop = function(onRender, win) { + this.onRender = onRender; + this.pending = false; + this.changes = 0; + this.window = win || window; +}; + +(function() { + + + this.schedule = function(change) { + this.changes = this.changes | change; + if (!this.pending && this.changes) { + this.pending = true; + var _self = this; + event.nextFrame(function() { + _self.pending = false; + var changes; + while (changes = _self.changes) { + _self.changes = 0; + _self.onRender(changes); + } + }, this.window); + } + }; + +}).call(RenderLoop.prototype); + +exports.RenderLoop = RenderLoop; +}); + +ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { + +var oop = acequire("../lib/oop"); +var dom = acequire("../lib/dom"); +var lang = acequire("../lib/lang"); +var useragent = acequire("../lib/useragent"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + +var CHAR_COUNT = 0; + +var FontMetrics = exports.FontMetrics = function(parentEl) { + this.el = dom.createElement("div"); + this.$setMeasureNodeStyles(this.el.style, true); + + this.$main = dom.createElement("div"); + this.$setMeasureNodeStyles(this.$main.style); + + this.$measureNode = dom.createElement("div"); + this.$setMeasureNodeStyles(this.$measureNode.style); + + + this.el.appendChild(this.$main); + this.el.appendChild(this.$measureNode); + parentEl.appendChild(this.el); + + if (!CHAR_COUNT) + this.$testFractionalRect(); + this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT); + + this.$characterSize = {width: 0, height: 0}; + this.checkForSizeChanges(); +}; + +(function() { + + oop.implement(this, EventEmitter); + + this.$characterSize = {width: 0, height: 0}; + + this.$testFractionalRect = function() { + var el = dom.createElement("div"); + this.$setMeasureNodeStyles(el.style); + el.style.width = "0.2px"; + document.documentElement.appendChild(el); + var w = el.getBoundingClientRect().width; + if (w > 0 && w < 1) + CHAR_COUNT = 50; + else + CHAR_COUNT = 100; + el.parentNode.removeChild(el); + }; + + this.$setMeasureNodeStyles = function(style, isRoot) { + style.width = style.height = "auto"; + style.left = style.top = "0px"; + style.visibility = "hidden"; + style.position = "absolute"; + style.whiteSpace = "pre"; + + if (useragent.isIE < 8) { + style["font-family"] = "inherit"; + } else { + style.font = "inherit"; + } + style.overflow = isRoot ? "hidden" : "visible"; + }; + + this.checkForSizeChanges = function() { + var size = this.$measureSizes(); + if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { + this.$measureNode.style.fontWeight = "bold"; + var boldSize = this.$measureSizes(); + this.$measureNode.style.fontWeight = ""; + this.$characterSize = size; + this.charSizes = Object.create(null); + this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height; + this._emit("changeCharacterSize", {data: size}); + } + }; + + this.$pollSizeChanges = function() { + if (this.$pollSizeChangesTimer) + return this.$pollSizeChangesTimer; + var self = this; + return this.$pollSizeChangesTimer = setInterval(function() { + self.checkForSizeChanges(); + }, 500); + }; + + this.setPolling = function(val) { + if (val) { + this.$pollSizeChanges(); + } else if (this.$pollSizeChangesTimer) { + clearInterval(this.$pollSizeChangesTimer); + this.$pollSizeChangesTimer = 0; + } + }; + + this.$measureSizes = function() { + if (CHAR_COUNT === 50) { + var rect = null; + try { + rect = this.$measureNode.getBoundingClientRect(); + } catch(e) { + rect = {width: 0, height:0 }; + } + var size = { + height: rect.height, + width: rect.width / CHAR_COUNT + }; + } else { + var size = { + height: this.$measureNode.clientHeight, + width: this.$measureNode.clientWidth / CHAR_COUNT + }; + } + if (size.width === 0 || size.height === 0) + return null; + return size; + }; + + this.$measureCharWidth = function(ch) { + this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT); + var rect = this.$main.getBoundingClientRect(); + return rect.width / CHAR_COUNT; + }; + + this.getCharacterWidth = function(ch) { + var w = this.charSizes[ch]; + if (w === undefined) { + w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width; + } + return w; + }; + + this.destroy = function() { + clearInterval(this.$pollSizeChangesTimer); + if (this.el && this.el.parentNode) + this.el.parentNode.removeChild(this.el); + }; + +}).call(FontMetrics.prototype); + +}); + +ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var config = acequire("./config"); +var useragent = acequire("./lib/useragent"); +var GutterLayer = acequire("./layer/gutter").Gutter; +var MarkerLayer = acequire("./layer/marker").Marker; +var TextLayer = acequire("./layer/text").Text; +var CursorLayer = acequire("./layer/cursor").Cursor; +var HScrollBar = acequire("./scrollbar").HScrollBar; +var VScrollBar = acequire("./scrollbar").VScrollBar; +var RenderLoop = acequire("./renderloop").RenderLoop; +var FontMetrics = acequire("./layer/font_metrics").FontMetrics; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var editorCss = ".ace_editor {\ +position: relative;\ +overflow: hidden;\ +font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\ +direction: ltr;\ +text-align: left;\ +}\ +.ace_scroller {\ +position: absolute;\ +overflow: hidden;\ +top: 0;\ +bottom: 0;\ +background-color: inherit;\ +-ms-user-select: none;\ +-moz-user-select: none;\ +-webkit-user-select: none;\ +user-select: none;\ +cursor: text;\ +}\ +.ace_content {\ +position: absolute;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +min-width: 100%;\ +}\ +.ace_dragging .ace_scroller:before{\ +position: absolute;\ +top: 0;\ +left: 0;\ +right: 0;\ +bottom: 0;\ +content: '';\ +background: rgba(250, 250, 250, 0.01);\ +z-index: 1000;\ +}\ +.ace_dragging.ace_dark .ace_scroller:before{\ +background: rgba(0, 0, 0, 0.01);\ +}\ +.ace_selecting, .ace_selecting * {\ +cursor: text !important;\ +}\ +.ace_gutter {\ +position: absolute;\ +overflow : hidden;\ +width: auto;\ +top: 0;\ +bottom: 0;\ +left: 0;\ +cursor: default;\ +z-index: 4;\ +-ms-user-select: none;\ +-moz-user-select: none;\ +-webkit-user-select: none;\ +user-select: none;\ +}\ +.ace_gutter-active-line {\ +position: absolute;\ +left: 0;\ +right: 0;\ +}\ +.ace_scroller.ace_scroll-left {\ +box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\ +}\ +.ace_gutter-cell {\ +padding-left: 19px;\ +padding-right: 6px;\ +background-repeat: no-repeat;\ +}\ +.ace_gutter-cell.ace_error {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\ +background-repeat: no-repeat;\ +background-position: 2px center;\ +}\ +.ace_gutter-cell.ace_warning {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\ +background-position: 2px center;\ +}\ +.ace_gutter-cell.ace_info {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\ +background-position: 2px center;\ +}\ +.ace_dark .ace_gutter-cell.ace_info {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\ +}\ +.ace_scrollbar {\ +position: absolute;\ +right: 0;\ +bottom: 0;\ +z-index: 6;\ +}\ +.ace_scrollbar-inner {\ +position: absolute;\ +cursor: text;\ +left: 0;\ +top: 0;\ +}\ +.ace_scrollbar-v{\ +overflow-x: hidden;\ +overflow-y: scroll;\ +top: 0;\ +}\ +.ace_scrollbar-h {\ +overflow-x: scroll;\ +overflow-y: hidden;\ +left: 0;\ +}\ +.ace_print-margin {\ +position: absolute;\ +height: 100%;\ +}\ +.ace_text-input {\ +position: absolute;\ +z-index: 0;\ +width: 0.5em;\ +height: 1em;\ +opacity: 0;\ +background: transparent;\ +-moz-appearance: none;\ +appearance: none;\ +border: none;\ +resize: none;\ +outline: none;\ +overflow: hidden;\ +font: inherit;\ +padding: 0 1px;\ +margin: 0 -1px;\ +text-indent: -1em;\ +-ms-user-select: text;\ +-moz-user-select: text;\ +-webkit-user-select: text;\ +user-select: text;\ +white-space: pre!important;\ +}\ +.ace_text-input.ace_composition {\ +background: inherit;\ +color: inherit;\ +z-index: 1000;\ +opacity: 1;\ +text-indent: 0;\ +}\ +.ace_layer {\ +z-index: 1;\ +position: absolute;\ +overflow: hidden;\ +word-wrap: normal;\ +white-space: pre;\ +height: 100%;\ +width: 100%;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +pointer-events: none;\ +}\ +.ace_gutter-layer {\ +position: relative;\ +width: auto;\ +text-align: right;\ +pointer-events: auto;\ +}\ +.ace_text-layer {\ +font: inherit !important;\ +}\ +.ace_cjk {\ +display: inline-block;\ +text-align: center;\ +}\ +.ace_cursor-layer {\ +z-index: 4;\ +}\ +.ace_cursor {\ +z-index: 4;\ +position: absolute;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +border-left: 2px solid;\ +transform: translatez(0);\ +}\ +.ace_slim-cursors .ace_cursor {\ +border-left-width: 1px;\ +}\ +.ace_overwrite-cursors .ace_cursor {\ +border-left-width: 0;\ +border-bottom: 1px solid;\ +}\ +.ace_hidden-cursors .ace_cursor {\ +opacity: 0.2;\ +}\ +.ace_smooth-blinking .ace_cursor {\ +-webkit-transition: opacity 0.18s;\ +transition: opacity 0.18s;\ +}\ +.ace_editor.ace_multiselect .ace_cursor {\ +border-left-width: 1px;\ +}\ +.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\ +position: absolute;\ +z-index: 3;\ +}\ +.ace_marker-layer .ace_selection {\ +position: absolute;\ +z-index: 5;\ +}\ +.ace_marker-layer .ace_bracket {\ +position: absolute;\ +z-index: 6;\ +}\ +.ace_marker-layer .ace_active-line {\ +position: absolute;\ +z-index: 2;\ +}\ +.ace_marker-layer .ace_selected-word {\ +position: absolute;\ +z-index: 4;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +}\ +.ace_line .ace_fold {\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +display: inline-block;\ +height: 11px;\ +margin-top: -2px;\ +vertical-align: middle;\ +background-image:\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\ +background-repeat: no-repeat, repeat-x;\ +background-position: center center, top left;\ +color: transparent;\ +border: 1px solid black;\ +border-radius: 2px;\ +cursor: pointer;\ +pointer-events: auto;\ +}\ +.ace_dark .ace_fold {\ +}\ +.ace_fold:hover{\ +background-image:\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ +url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\ +}\ +.ace_tooltip {\ +background-color: #FFF;\ +background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\ +background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\ +border: 1px solid gray;\ +border-radius: 1px;\ +box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\ +color: black;\ +max-width: 100%;\ +padding: 3px 4px;\ +position: fixed;\ +z-index: 999999;\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +cursor: default;\ +white-space: pre;\ +word-wrap: break-word;\ +line-height: normal;\ +font-style: normal;\ +font-weight: normal;\ +letter-spacing: normal;\ +pointer-events: none;\ +}\ +.ace_folding-enabled > .ace_gutter-cell {\ +padding-right: 13px;\ +}\ +.ace_fold-widget {\ +-moz-box-sizing: border-box;\ +-webkit-box-sizing: border-box;\ +box-sizing: border-box;\ +margin: 0 -12px 0 1px;\ +display: none;\ +width: 11px;\ +vertical-align: top;\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\ +background-repeat: no-repeat;\ +background-position: center;\ +border-radius: 3px;\ +border: 1px solid transparent;\ +cursor: pointer;\ +}\ +.ace_folding-enabled .ace_fold-widget {\ +display: inline-block; \ +}\ +.ace_fold-widget.ace_end {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\ +}\ +.ace_fold-widget.ace_closed {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\ +}\ +.ace_fold-widget:hover {\ +border: 1px solid rgba(0, 0, 0, 0.3);\ +background-color: rgba(255, 255, 255, 0.2);\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\ +}\ +.ace_fold-widget:active {\ +border: 1px solid rgba(0, 0, 0, 0.4);\ +background-color: rgba(0, 0, 0, 0.05);\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\ +}\ +.ace_dark .ace_fold-widget {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\ +}\ +.ace_dark .ace_fold-widget.ace_end {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\ +}\ +.ace_dark .ace_fold-widget.ace_closed {\ +background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\ +}\ +.ace_dark .ace_fold-widget:hover {\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ +background-color: rgba(255, 255, 255, 0.1);\ +}\ +.ace_dark .ace_fold-widget:active {\ +box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ +}\ +.ace_fold-widget.ace_invalid {\ +background-color: #FFB4B4;\ +border-color: #DE5555;\ +}\ +.ace_fade-fold-widgets .ace_fold-widget {\ +-webkit-transition: opacity 0.4s ease 0.05s;\ +transition: opacity 0.4s ease 0.05s;\ +opacity: 0;\ +}\ +.ace_fade-fold-widgets:hover .ace_fold-widget {\ +-webkit-transition: opacity 0.05s ease 0.05s;\ +transition: opacity 0.05s ease 0.05s;\ +opacity:1;\ +}\ +.ace_underline {\ +text-decoration: underline;\ +}\ +.ace_bold {\ +font-weight: bold;\ +}\ +.ace_nobold .ace_bold {\ +font-weight: normal;\ +}\ +.ace_italic {\ +font-style: italic;\ +}\ +.ace_error-marker {\ +background-color: rgba(255, 0, 0,0.2);\ +position: absolute;\ +z-index: 9;\ +}\ +.ace_highlight-marker {\ +background-color: rgba(255, 255, 0,0.2);\ +position: absolute;\ +z-index: 8;\ +}\ +.ace_br1 {border-top-left-radius : 3px;}\ +.ace_br2 {border-top-right-radius : 3px;}\ +.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\ +.ace_br4 {border-bottom-right-radius: 3px;}\ +.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\ +.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\ +.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\ +.ace_br8 {border-bottom-left-radius : 3px;}\ +.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\ +.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\ +.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ +"; + +dom.importCssString(editorCss, "ace_editor.css"); + +var VirtualRenderer = function(container, theme) { + var _self = this; + + this.container = container || dom.createElement("div"); + this.$keepTextAreaAtCursor = !useragent.isOldIE; + + dom.addCssClass(this.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.onGutterResize.bind(this)); + + 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.$cursorLayer = new CursorLayer(this.content); + this.$horizScroll = false; + this.$vScroll = false; + + this.scrollBar = + this.scrollBarV = new VScrollBar(this.container, this); + this.scrollBarH = new HScrollBar(this.container, this); + this.scrollBarV.addEventListener("scroll", function(e) { + if (!_self.$scrollAnimation) + _self.session.setScrollTop(e.data - _self.scrollMargin.top); + }); + this.scrollBarH.addEventListener("scroll", function(e) { + if (!_self.$scrollAnimation) + _self.session.setScrollLeft(e.data - _self.scrollMargin.left); + }); + + this.scrollTop = 0; + this.scrollLeft = 0; + + this.cursorPos = { + row : 0, + column : 0 + }; + + this.$fontMetrics = new FontMetrics(this.container); + this.$textLayer.$setFontMetrics(this.$fontMetrics); + this.$textLayer.addEventListener("changeCharacterSize", function(e) { + _self.updateCharacterSize(); + _self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height); + _self._signal("changeCharacterSize", e); + }); + + this.$size = { + width: 0, + height: 0, + scrollerHeight: 0, + scrollerWidth: 0, + $dirty: true + }; + + this.layerConfig = { + width : 1, + padding : 0, + firstRow : 0, + firstRowScreen: 0, + lastRow : 0, + lineHeight : 0, + characterWidth : 0, + minHeight : 1, + maxHeight : 1, + offset : 0, + height : 1, + gutterOffset: 1 + }; + + this.scrollMargin = { + left: 0, + right: 0, + top: 0, + bottom: 0, + v: 0, + h: 0 + }; + + this.$loop = new RenderLoop( + this.$renderChanges.bind(this), + this.container.ownerDocument.defaultView + ); + this.$loop.schedule(this.CHANGE_FULL); + + this.updateCharacterSize(); + this.setPadding(4); + config.resetOptions(this); + config._emit("renderer", this); +}; + +(function() { + + 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.updateCharacterSize = function() { + if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) { + this.$allowBoldFonts = this.$textLayer.allowBoldFonts; + this.setStyle("ace_nobold", !this.$allowBoldFonts); + } + + this.layerConfig.characterWidth = + this.characterWidth = this.$textLayer.getCharacterWidth(); + this.layerConfig.lineHeight = + this.lineHeight = this.$textLayer.getLineHeight(); + this.$updatePrintMargin(); + }; + this.setSession = function(session) { + if (this.session) + this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode); + + this.session = session; + if (session && this.scrollMargin.top && session.getScrollTop() <= 0) + session.setScrollTop(-this.scrollMargin.top); + + this.$cursorLayer.setSession(session); + this.$markerBack.setSession(session); + this.$markerFront.setSession(session); + this.$gutterLayer.setSession(session); + this.$textLayer.setSession(session); + if (!session) + return; + + this.$loop.schedule(this.CHANGE_FULL); + this.session.$setFontMetrics(this.$fontMetrics); + this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null; + + this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this); + this.onChangeNewLineMode() + this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode); + }; + this.updateLines = function(firstRow, lastRow, force) { + 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; + } + if (this.$changedLines.lastRow < this.layerConfig.firstRow) { + if (force) + this.$changedLines.lastRow = this.layerConfig.lastRow; + else + return; + } + if (this.$changedLines.firstRow > this.layerConfig.lastRow) + return; + this.$loop.schedule(this.CHANGE_LINES); + }; + + this.onChangeNewLineMode = function() { + this.$loop.schedule(this.CHANGE_TEXT); + this.$textLayer.$updateEolChar(); + }; + + this.onChangeTabSize = function() { + this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER); + this.$textLayer.onChangeTabSize(); + }; + this.updateText = function() { + this.$loop.schedule(this.CHANGE_TEXT); + }; + this.updateFull = function(force) { + if (force) + this.$renderChanges(this.CHANGE_FULL, true); + else + this.$loop.schedule(this.CHANGE_FULL); + }; + this.updateFontSize = function() { + this.$textLayer.checkForSizeChanges(); + }; + + this.$changes = 0; + this.$updateSizeAsync = function() { + if (this.$loop.pending) + this.$size.$dirty = true; + else + this.onResize(); + }; + this.onResize = function(force, gutterWidth, width, height) { + if (this.resizing > 2) + return; + else if (this.resizing > 0) + this.resizing++; + else + this.resizing = force ? 1 : 0; + var el = this.container; + if (!height) + height = el.clientHeight || el.scrollHeight; + if (!width) + width = el.clientWidth || el.scrollWidth; + var changes = this.$updateCachedSize(force, gutterWidth, width, height); + + + if (!this.$size.scrollerHeight || (!width && !height)) + return this.resizing = 0; + + if (force) + this.$gutterLayer.$padding = null; + + if (force) + this.$renderChanges(changes | this.$changes, true); + else + this.$loop.schedule(changes | this.$changes); + + if (this.resizing) + this.resizing = 0; + this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null; + }; + + this.$updateCachedSize = function(force, gutterWidth, width, height) { + height -= (this.$extraHeight || 0); + var changes = 0; + var size = this.$size; + var oldSize = { + width: size.width, + height: size.height, + scrollerHeight: size.scrollerHeight, + scrollerWidth: size.scrollerWidth + }; + if (height && (force || size.height != height)) { + size.height = height; + changes |= this.CHANGE_SIZE; + + size.scrollerHeight = size.height; + if (this.$horizScroll) + size.scrollerHeight -= this.scrollBarH.getHeight(); + this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px"; + + changes = changes | this.CHANGE_SCROLL; + } + + if (width && (force || size.width != width)) { + changes |= this.CHANGE_SIZE; + size.width = width; + + if (gutterWidth == null) + gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; + + this.gutterWidth = gutterWidth; + + this.scrollBarH.element.style.left = + this.scroller.style.left = gutterWidth + "px"; + size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth()); + + this.scrollBarH.element.style.right = + this.scroller.style.right = this.scrollBarV.getWidth() + "px"; + this.scroller.style.bottom = this.scrollBarH.getHeight() + "px"; + + if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force) + changes |= this.CHANGE_FULL; + } + + size.$dirty = !width || !height; + + if (changes) + this._signal("resize", oldSize); + + return changes; + }; + + this.onGutterResize = function() { + var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; + if (gutterWidth != this.gutterWidth) + this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height); + + if (this.session.getUseWrapMode() && this.adjustWrapLimit()) { + this.$loop.schedule(this.CHANGE_FULL); + } else if (this.$size.$dirty) { + this.$loop.schedule(this.CHANGE_FULL); + } else { + this.$computeLayerConfig(); + this.$loop.schedule(this.CHANGE_MARKER); + } + }; + this.adjustWrapLimit = function() { + var availableWidth = this.$size.scrollerWidth - this.$padding * 2; + var limit = Math.floor(availableWidth / this.characterWidth); + return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn); + }; + this.setAnimatedScroll = function(shouldAnimate){ + this.setOption("animatedScroll", shouldAnimate); + }; + this.getAnimatedScroll = function() { + return this.$animatedScroll; + }; + this.setShowInvisibles = function(showInvisibles) { + this.setOption("showInvisibles", showInvisibles); + }; + this.getShowInvisibles = function() { + return this.getOption("showInvisibles"); + }; + this.getDisplayIndentGuides = function() { + return this.getOption("displayIndentGuides"); + }; + + this.setDisplayIndentGuides = function(display) { + this.setOption("displayIndentGuides", display); + }; + this.setShowPrintMargin = function(showPrintMargin) { + this.setOption("showPrintMargin", showPrintMargin); + }; + this.getShowPrintMargin = function() { + return this.getOption("showPrintMargin"); + }; + this.setPrintMarginColumn = function(showPrintMargin) { + this.setOption("printMarginColumn", showPrintMargin); + }; + this.getPrintMarginColumn = function() { + return this.getOption("printMarginColumn"); + }; + this.getShowGutter = function(){ + return this.getOption("showGutter"); + }; + this.setShowGutter = function(show){ + return this.setOption("showGutter", show); + }; + + this.getFadeFoldWidgets = function(){ + return this.getOption("fadeFoldWidgets") + }; + + this.setFadeFoldWidgets = function(show) { + this.setOption("fadeFoldWidgets", show); + }; + + this.setHighlightGutterLine = function(shouldHighlight) { + this.setOption("highlightGutterLine", shouldHighlight); + }; + + this.getHighlightGutterLine = function() { + return this.getOption("highlightGutterLine"); + }; + + this.$updateGutterLineHighlight = function() { + var pos = this.$cursorLayer.$pixelPos; + var height = this.layerConfig.lineHeight; + if (this.session.getUseWrapMode()) { + var cursor = this.session.selection.getCursor(); + cursor.column = 0; + pos = this.$cursorLayer.getPixelPosition(cursor, true); + height *= this.session.getRowLength(cursor.row); + } + this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px"; + this.$gutterLineHighlight.style.height = height + "px"; + }; + + this.$updatePrintMargin = function() { + if (!this.$showPrintMargin && !this.$printMarginEl) + return; + + if (!this.$printMarginEl) { + var containerEl = dom.createElement("div"); + containerEl.className = "ace_layer ace_print-margin-layer"; + this.$printMarginEl = dom.createElement("div"); + this.$printMarginEl.className = "ace_print-margin"; + containerEl.appendChild(this.$printMarginEl); + this.content.insertBefore(containerEl, this.content.firstChild); + } + + var style = this.$printMarginEl.style; + style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px"; + style.visibility = this.$showPrintMargin ? "visible" : "hidden"; + + if (this.session && this.session.$wrap == -1) + this.adjustWrapLimit(); + }; + this.getContainerElement = function() { + return this.container; + }; + this.getMouseEventTarget = function() { + return this.scroller; + }; + this.getTextAreaContainer = function() { + return this.container; + }; + this.$moveTextAreaToCursor = function() { + if (!this.$keepTextAreaAtCursor) + return; + var config = this.layerConfig; + var posTop = this.$cursorLayer.$pixelPos.top; + var posLeft = this.$cursorLayer.$pixelPos.left; + posTop -= config.offset; + + var style = this.textarea.style; + var h = this.lineHeight; + if (posTop < 0 || posTop > config.height - h) { + style.top = style.left = "0"; + return; + } + + var w = this.characterWidth; + if (this.$composition) { + var val = this.textarea.value.replace(/^\x01+/, ""); + w *= (this.session.$getStringScreenWidth(val)[0]+2); + h += 2; + } + posLeft -= this.scrollLeft; + if (posLeft > this.$size.scrollerWidth - w) + posLeft = this.$size.scrollerWidth - w; + + posLeft += this.gutterWidth; + style.height = h + "px"; + style.width = w + "px"; + style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px"; + style.top = Math.min(posTop, this.$size.height - h) + "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 config = this.layerConfig; + var lastRow = config.lastRow + var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight; + if (top - this.session.getScrollTop() > config.height - config.lineHeight) + return lastRow - 1; + return lastRow; + }; + 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.setScrollMargin = function(top, bottom, left, right) { + var sm = this.scrollMargin; + sm.top = top|0; + sm.bottom = bottom|0; + sm.right = right|0; + sm.left = left|0; + sm.v = sm.top + sm.bottom; + sm.h = sm.left + sm.right; + if (sm.top && this.scrollTop <= 0 && this.session) + this.session.setScrollTop(-sm.top); + this.updateFull(); + }; + this.getHScrollBarAlwaysVisible = function() { + return this.$hScrollBarAlwaysVisible; + }; + this.setHScrollBarAlwaysVisible = function(alwaysVisible) { + this.setOption("hScrollBarAlwaysVisible", alwaysVisible); + }; + this.getVScrollBarAlwaysVisible = function() { + return this.$vScrollBarAlwaysVisible; + }; + this.setVScrollBarAlwaysVisible = function(alwaysVisible) { + this.setOption("vScrollBarAlwaysVisible", alwaysVisible); + }; + + this.$updateScrollBarV = function() { + var scrollHeight = this.layerConfig.maxHeight; + var scrollerHeight = this.$size.scrollerHeight; + if (!this.$maxLines && this.$scrollPastEnd) { + scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd; + if (this.scrollTop > scrollHeight - scrollerHeight) { + scrollHeight = this.scrollTop + scrollerHeight; + this.scrollBarV.scrollTop = null; + } + } + this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v); + this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top); + }; + this.$updateScrollBarH = function() { + this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h); + this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left); + }; + + this.$frozen = false; + this.freeze = function() { + this.$frozen = true; + }; + + this.unfreeze = function() { + this.$frozen = false; + }; + + this.$renderChanges = function(changes, force) { + if (this.$changes) { + changes |= this.$changes; + this.$changes = 0; + } + if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) { + this.$changes |= changes; + return; + } + if (this.$size.$dirty) { + this.$changes |= changes; + return this.onResize(true); + } + if (!this.lineHeight) { + this.$textLayer.checkForSizeChanges(); + } + + this._signal("beforeRender"); + var config = this.layerConfig; + if (changes & this.CHANGE_FULL || + changes & this.CHANGE_SIZE || + changes & this.CHANGE_TEXT || + changes & this.CHANGE_LINES || + changes & this.CHANGE_SCROLL || + changes & this.CHANGE_H_SCROLL + ) { + changes |= this.$computeLayerConfig(); + if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) { + var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight; + if (st > 0) { + this.scrollTop = st; + changes = changes | this.CHANGE_SCROLL; + changes |= this.$computeLayerConfig(); + } + } + config = this.layerConfig; + this.$updateScrollBarV(); + if (changes & this.CHANGE_H_SCROLL) + this.$updateScrollBarH(); + this.$gutterLayer.element.style.marginTop = (-config.offset) + "px"; + this.content.style.marginTop = (-config.offset) + "px"; + this.content.style.width = config.width + 2 * this.$padding + "px"; + this.content.style.height = config.minHeight + "px"; + } + if (changes & this.CHANGE_H_SCROLL) { + this.content.style.marginLeft = -this.scrollLeft + "px"; + this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left"; + } + if (changes & this.CHANGE_FULL) { + this.$textLayer.update(config); + if (this.$showGutter) + this.$gutterLayer.update(config); + this.$markerBack.update(config); + this.$markerFront.update(config); + this.$cursorLayer.update(config); + this.$moveTextAreaToCursor(); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + this._signal("afterRender"); + return; + } + if (changes & this.CHANGE_SCROLL) { + if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) + this.$textLayer.update(config); + else + this.$textLayer.scrollLines(config); + + if (this.$showGutter) + this.$gutterLayer.update(config); + this.$markerBack.update(config); + this.$markerFront.update(config); + this.$cursorLayer.update(config); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + this.$moveTextAreaToCursor(); + this._signal("afterRender"); + return; + } + + if (changes & this.CHANGE_TEXT) { + this.$textLayer.update(config); + if (this.$showGutter) + this.$gutterLayer.update(config); + } + else if (changes & this.CHANGE_LINES) { + if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter) + this.$gutterLayer.update(config); + } + else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) { + if (this.$showGutter) + this.$gutterLayer.update(config); + } + + if (changes & this.CHANGE_CURSOR) { + this.$cursorLayer.update(config); + this.$moveTextAreaToCursor(); + this.$highlightGutterLine && this.$updateGutterLineHighlight(); + } + + if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) { + this.$markerFront.update(config); + } + + if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) { + this.$markerBack.update(config); + } + + this._signal("afterRender"); + }; + + + this.$autosize = function() { + var height = this.session.getScreenLength() * this.lineHeight; + var maxHeight = this.$maxLines * this.lineHeight; + var desiredHeight = Math.min(maxHeight, + Math.max((this.$minLines || 1) * this.lineHeight, height) + ) + this.scrollMargin.v + (this.$extraHeight || 0); + if (this.$horizScroll) + desiredHeight += this.scrollBarH.getHeight(); + if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight) + desiredHeight = this.$maxPixelHeight; + var vScroll = height > maxHeight; + + if (desiredHeight != this.desiredHeight || + this.$size.height != this.desiredHeight || vScroll != this.$vScroll) { + if (vScroll != this.$vScroll) { + this.$vScroll = vScroll; + this.scrollBarV.setVisible(vScroll); + } + + var w = this.container.clientWidth; + this.container.style.height = desiredHeight + "px"; + this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight); + this.desiredHeight = desiredHeight; + + this._signal("autosize"); + } + }; + + this.$computeLayerConfig = function() { + var session = this.session; + var size = this.$size; + + var hideScrollbars = size.height <= 2 * this.lineHeight; + var screenLines = this.session.getScreenLength(); + var maxHeight = screenLines * this.lineHeight; + + var longestLine = this.$getLongestLine(); + + var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible || + size.scrollerWidth - longestLine - 2 * this.$padding < 0); + + var hScrollChanged = this.$horizScroll !== horizScroll; + if (hScrollChanged) { + this.$horizScroll = horizScroll; + this.scrollBarH.setVisible(horizScroll); + } + var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine + if (this.$maxLines && this.lineHeight > 1) + this.$autosize(); + + var offset = this.scrollTop % this.lineHeight; + var minHeight = size.scrollerHeight + this.lineHeight; + + var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd + ? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd + : 0; + maxHeight += scrollPastEnd; + + var sm = this.scrollMargin; + this.session.setScrollTop(Math.max(-sm.top, + Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom))); + + this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft, + longestLine + 2 * this.$padding - size.scrollerWidth + sm.right))); + + var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible || + size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top); + var vScrollChanged = vScrollBefore !== vScroll; + if (vScrollChanged) { + this.$vScroll = vScroll; + this.scrollBarV.setVisible(vScroll); + } + + var lineCount = Math.ceil(minHeight / this.lineHeight) - 1; + var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight)); + var lastRow = firstRow + lineCount; + var firstRowScreen, firstRowHeight; + var lineHeight = this.lineHeight; + firstRow = session.screenToDocumentRow(firstRow, 0); + var foldLine = session.getFoldLine(firstRow); + if (foldLine) { + firstRow = foldLine.start.row; + } + + firstRowScreen = session.documentToScreenRow(firstRow, 0); + firstRowHeight = session.getRowLength(firstRow) * lineHeight; + + lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1); + minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight + + firstRowHeight; + + offset = this.scrollTop - firstRowScreen * lineHeight; + + var changes = 0; + if (this.layerConfig.width != longestLine) + changes = this.CHANGE_H_SCROLL; + if (hScrollChanged || vScrollChanged) { + changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height); + this._signal("scrollbarVisibilityChanged"); + if (vScrollChanged) + longestLine = this.$getLongestLine(); + } + + this.layerConfig = { + width : longestLine, + padding : this.$padding, + firstRow : firstRow, + firstRowScreen: firstRowScreen, + lastRow : lastRow, + lineHeight : lineHeight, + characterWidth : this.characterWidth, + minHeight : minHeight, + maxHeight : maxHeight, + offset : offset, + gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0, + height : this.$size.scrollerHeight + }; + + return changes; + }; + + 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 (lastRow === Infinity) { + if (this.$showGutter) + this.$gutterLayer.update(layerConfig); + this.$textLayer.update(layerConfig); + return; + } + this.$textLayer.updateLines(layerConfig, firstRow, lastRow); + return true; + }; + + this.$getLongestLine = function() { + var charCount = this.session.getScreenWidth(); + if (this.showInvisibles && !this.session.$useWrapMode) + 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.removeGutterDecoration = function(row, className){ + this.$gutterLayer.removeGutterDecoration(row, className); + }; + 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) { + this.scrollCursorIntoView(anchor, offset); + this.scrollCursorIntoView(lead, offset); + }; + this.scrollCursorIntoView = function(cursor, offset, $viewMargin) { + if (this.$size.scrollerHeight === 0) + return; + + var pos = this.$cursorLayer.getPixelPosition(cursor); + + var left = pos.left; + var top = pos.top; + + var topMargin = $viewMargin && $viewMargin.top || 0; + var bottomMargin = $viewMargin && $viewMargin.bottom || 0; + + var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop; + + if (scrollTop + topMargin > top) { + if (offset && scrollTop + topMargin > top + this.lineHeight) + top -= offset * this.$size.scrollerHeight; + if (top === 0) + top = -this.scrollMargin.top; + this.session.setScrollTop(top); + } else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) { + if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight) + 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 = -this.scrollMargin.left; + this.session.setScrollLeft(left); + } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { + this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); + } else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) { + this.session.setScrollLeft(0); + } + }; + 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 h = this.$size.scrollerHeight - this.lineHeight; + var offset = pos.top - h * (alignment || 0); + + this.session.setScrollTop(offset); + return 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) + return; + var _self = this; + + if (fromValue == toValue) + return; + + if (this.$scrollAnimation) { + var oldSteps = this.$scrollAnimation.steps; + if (oldSteps.length) { + fromValue = oldSteps[0]; + if (fromValue == toValue) + return; + } + } + + var steps = _self.$calcSteps(fromValue, toValue); + this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps}; + + clearInterval(this.$timer); + + _self.session.setScrollTop(steps.shift()); + _self.session.$scrollTop = toValue; + this.$timer = setInterval(function() { + if (steps.length) { + _self.session.setScrollTop(steps.shift()); + _self.session.$scrollTop = toValue; + } else if (toValue != null) { + _self.session.$scrollTop = -1; + _self.session.setScrollTop(toValue); + toValue = null; + } else { + _self.$timer = clearInterval(_self.$timer); + _self.$scrollAnimation = null; + callback && callback(); + } + }, 10); + }; + this.scrollToY = function(scrollTop) { + if (this.scrollTop !== scrollTop) { + this.$loop.schedule(this.CHANGE_SCROLL); + this.scrollTop = scrollTop; + } + }; + this.scrollToX = function(scrollLeft) { + if (this.scrollLeft !== scrollLeft) + this.scrollLeft = scrollLeft; + this.$loop.schedule(this.CHANGE_H_SCROLL); + }; + this.scrollTo = function(x, y) { + this.session.setScrollTop(y); + this.session.setScrollLeft(y); + }; + 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() >= 1 - this.scrollMargin.top) + return true; + if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight + - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom) + return true; + if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left) + return true; + if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth + - this.layerConfig.width < -1 + this.scrollMargin.right) + return true; + }; + + 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 = (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.setTheme = function(theme, cb) { + var _self = this; + this.$themeId = theme; + _self._dispatchEvent('themeChange',{theme:theme}); + + if (!theme || typeof theme == "string") { + var moduleName = theme || this.$options.theme.initialValue; + config.loadModule(["theme", moduleName], afterLoad); + } else { + afterLoad(theme); + } + + function afterLoad(module) { + if (_self.$themeId != theme) + return cb && cb(); + if (!module || !module.cssClass) + throw new Error("couldn't load module " + theme + " or it didn't call define"); + dom.importCssString( + module.cssText, + module.cssClass, + _self.container.ownerDocument + ); + + if (_self.theme) + dom.removeCssClass(_self.container, _self.theme.cssClass); + + var padding = "padding" in module ? module.padding + : "padding" in (_self.theme || {}) ? 4 : _self.$padding; + if (_self.$padding && padding != _self.$padding) + _self.setPadding(padding); + _self.$theme = module.cssClass; + + _self.theme = module; + dom.addCssClass(_self.container, module.cssClass); + dom.setCssClass(_self.container, "ace_dark", module.isDark); + if (_self.$size) { + _self.$size.width = 0; + _self.$updateSizeAsync(); + } + + _self._dispatchEvent('themeLoaded', {theme:module}); + cb && cb(); + } + }; + this.getTheme = function() { + return this.$themeId; + }; + this.setStyle = function(style, include) { + dom.setCssClass(this.container, style, include !== false); + }; + this.unsetStyle = function(style) { + dom.removeCssClass(this.container, style); + }; + + this.setCursorStyle = function(style) { + if (this.scroller.style.cursor != style) + this.scroller.style.cursor = style; + }; + this.setMouseCursor = function(cursorStyle) { + this.scroller.style.cursor = cursorStyle; + }; + this.destroy = function() { + this.$textLayer.destroy(); + this.$cursorLayer.destroy(); + }; + +}).call(VirtualRenderer.prototype); + + +config.defineOptions(VirtualRenderer.prototype, "renderer", { + animatedScroll: {initialValue: false}, + showInvisibles: { + set: function(value) { + if (this.$textLayer.setShowInvisibles(value)) + this.$loop.schedule(this.CHANGE_TEXT); + }, + initialValue: false + }, + showPrintMargin: { + set: function() { this.$updatePrintMargin(); }, + initialValue: true + }, + printMarginColumn: { + set: function() { this.$updatePrintMargin(); }, + initialValue: 80 + }, + printMargin: { + set: function(val) { + if (typeof val == "number") + this.$printMarginColumn = val; + this.$showPrintMargin = !!val; + this.$updatePrintMargin(); + }, + get: function() { + return this.$showPrintMargin && this.$printMarginColumn; + } + }, + showGutter: { + set: function(show){ + this.$gutter.style.display = show ? "block" : "none"; + this.$loop.schedule(this.CHANGE_FULL); + this.onGutterResize(); + }, + initialValue: true + }, + fadeFoldWidgets: { + set: function(show) { + dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show); + }, + initialValue: false + }, + showFoldWidgets: { + set: function(show) {this.$gutterLayer.setShowFoldWidgets(show)}, + initialValue: true + }, + showLineNumbers: { + set: function(show) { + this.$gutterLayer.setShowLineNumbers(show); + this.$loop.schedule(this.CHANGE_GUTTER); + }, + initialValue: true + }, + displayIndentGuides: { + set: function(show) { + if (this.$textLayer.setDisplayIndentGuides(show)) + this.$loop.schedule(this.CHANGE_TEXT); + }, + initialValue: true + }, + highlightGutterLine: { + set: function(shouldHighlight) { + if (!this.$gutterLineHighlight) { + this.$gutterLineHighlight = dom.createElement("div"); + this.$gutterLineHighlight.className = "ace_gutter-active-line"; + this.$gutter.appendChild(this.$gutterLineHighlight); + return; + } + + this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none"; + if (this.$cursorLayer.$pixelPos) + this.$updateGutterLineHighlight(); + }, + initialValue: false, + value: true + }, + hScrollBarAlwaysVisible: { + set: function(val) { + if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll) + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: false + }, + vScrollBarAlwaysVisible: { + set: function(val) { + if (!this.$vScrollBarAlwaysVisible || !this.$vScroll) + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: false + }, + fontSize: { + set: function(size) { + if (typeof size == "number") + size = size + "px"; + this.container.style.fontSize = size; + this.updateFontSize(); + }, + initialValue: 12 + }, + fontFamily: { + set: function(name) { + this.container.style.fontFamily = name; + this.updateFontSize(); + } + }, + maxLines: { + set: function(val) { + this.updateFull(); + } + }, + minLines: { + set: function(val) { + this.updateFull(); + } + }, + maxPixelHeight: { + set: function(val) { + this.updateFull(); + }, + initialValue: 0 + }, + scrollPastEnd: { + set: function(val) { + val = +val || 0; + if (this.$scrollPastEnd == val) + return; + this.$scrollPastEnd = val; + this.$loop.schedule(this.CHANGE_SCROLL); + }, + initialValue: 0, + handlesSet: true + }, + fixedWidthGutter: { + set: function(val) { + this.$gutterLayer.$fixedWidth = !!val; + this.$loop.schedule(this.CHANGE_GUTTER); + } + }, + theme: { + set: function(val) { this.setTheme(val) }, + get: function() { return this.$themeId || this.theme; }, + initialValue: "./theme/textmate", + handlesSet: true + } +}); + +exports.VirtualRenderer = VirtualRenderer; +}); + +ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var net = acequire("../lib/net"); +var EventEmitter = acequire("../lib/event_emitter").EventEmitter; +var config = acequire("../config"); + +var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl) { + this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); + this.changeListener = this.changeListener.bind(this); + this.onMessage = this.onMessage.bind(this); + if (acequire.nameToUrl && !acequire.toUrl) + acequire.toUrl = acequire.nameToUrl; + + if (config.get("packaged") || !acequire.toUrl) { + workerUrl = workerUrl || config.moduleUrl(mod.id, "worker") + } else { + var normalizePath = this.$normalizePath; + workerUrl = workerUrl || normalizePath(acequire.toUrl("ace/worker/worker.js", null, "_")); + + var tlns = {}; + topLevelNamespaces.forEach(function(ns) { + tlns[ns] = normalizePath(acequire.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, "")); + }); + } + + try { + var workerSrc = mod.src; + var Blob = __webpack_require__(54); + var blob = new Blob([ workerSrc ], { type: 'application/javascript' }); + var blobUrl = (window.URL || window.webkitURL).createObjectURL(blob); + + this.$worker = new Worker(blobUrl); + + } catch(e) { + if (e instanceof window.DOMException) { + var blob = this.$workerBlob(workerUrl); + var URL = window.URL || window.webkitURL; + var blobURL = URL.createObjectURL(blob); + + this.$worker = new Worker(blobURL); + URL.revokeObjectURL(blobURL); + } else { + throw e; + } + } + this.$worker.postMessage({ + init : true, + tlns : tlns, + module : mod.id, + classname : classname + }); + + this.callbackId = 1; + this.callbacks = {}; + + this.$worker.onmessage = this.onMessage; +}; + +(function(){ + + oop.implement(this, EventEmitter); + + this.onMessage = function(e) { + var msg = e.data; + switch(msg.type) { + case "event": + this._signal(msg.name, {data: msg.data}); + break; + case "call": + var callback = this.callbacks[msg.id]; + if (callback) { + callback(msg.data); + delete this.callbacks[msg.id]; + } + break; + case "error": + this.reportError(msg.data); + break; + case "log": + window.console && console.log && console.log.apply(console, msg.data); + break; + } + }; + + this.reportError = function(err) { + window.console && console.error && console.error(err); + }; + + this.$normalizePath = function(path) { + return net.qualifyURL(path); + }; + + this.terminate = function() { + this._signal("terminate", {}); + this.deltaQueue = null; + this.$worker.terminate(); + this.$worker = null; + if (this.$doc) + this.$doc.off("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 { + this.$worker.postMessage({event: event, data: {data: data.data}}); + } + catch(ex) { + console.error(ex.stack); + } + }; + + 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(delta) { + if (!this.deltaQueue) { + this.deltaQueue = []; + setTimeout(this.$sendDeltaQueue, 0); + } + if (delta.action == "insert") + this.deltaQueue.push(delta.start, delta.lines); + else + this.deltaQueue.push(delta.start, delta.end); + }; + + this.$sendDeltaQueue = function() { + var q = this.deltaQueue; + if (!q) return; + this.deltaQueue = null; + if (q.length > 50 && q.length > this.$doc.getLength() >> 1) { + this.call("setValue", [this.$doc.getValue()]); + } else + this.emit("change", {data: q}); + }; + + this.$workerBlob = function(workerUrl) { + var script = "importScripts('" + net.qualifyURL(workerUrl) + "');"; + try { + return new Blob([script], {"type": "application/javascript"}); + } catch (e) { // Backwards-compatibility + var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; + var blobBuilder = new BlobBuilder(); + blobBuilder.append(script); + return blobBuilder.getBlob("application/javascript"); + } + }; + +}).call(WorkerClient.prototype); + + +var UIWorkerClient = function(topLevelNamespaces, mod, classname) { + this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); + this.changeListener = this.changeListener.bind(this); + this.callbackId = 1; + this.callbacks = {}; + this.messageBuffer = []; + + var main = null; + var emitSync = false; + var sender = Object.create(EventEmitter); + var _self = this; + + this.$worker = {}; + this.$worker.terminate = function() {}; + this.$worker.postMessage = function(e) { + _self.messageBuffer.push(e); + if (main) { + if (emitSync) + setTimeout(processNext); + else + processNext(); + } + }; + this.setEmitSync = function(val) { emitSync = val }; + + var processNext = function() { + var msg = _self.messageBuffer.shift(); + if (msg.command) + main[msg.command].apply(main, msg.args); + else if (msg.event) + sender._signal(msg.event, msg.data); + }; + + sender.postMessage = function(msg) { + _self.onMessage({data: msg}); + }; + sender.callback = function(data, callbackId) { + this.postMessage({type: "call", id: callbackId, data: data}); + }; + sender.emit = function(name, data) { + this.postMessage({type: "event", name: name, data: data}); + }; + + config.loadModule(["worker", mod], function(Main) { + main = new Main[classname](sender); + while (_self.messageBuffer.length) + processNext(); + }); +}; + +UIWorkerClient.prototype = WorkerClient.prototype; + +exports.UIWorkerClient = UIWorkerClient; +exports.WorkerClient = WorkerClient; + +}); + +ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("./range").Range; +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var oop = acequire("./lib/oop"); + +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; + 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; + + this.selectionBefore = session.selection.toJSON(); + if (session.selection.inMultiSelectMode) + session.selection.toSingleRange(); + + this.pos = doc.createAnchor(this.$pos.row, this.$pos.column); + var pos = this.pos; + pos.$insertRight = true; + pos.detach(); + pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false); + this.others = []; + this.$others.forEach(function(other) { + var anchor = doc.createAnchor(other.row, other.column); + anchor.$insertRight = true; + anchor.detach(); + _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); + }); + }; + this.hideOtherMarkers = function() { + if (!this.othersActive) return; + this.othersActive = false; + for (var i = 0; i < this.others.length; i++) { + this.session.removeMarker(this.others[i].markerId); + } + }; + this.onUpdate = function(delta) { + if (this.$updating) + return this.updateAnchors(delta); + + var range = delta; + if (range.start.row !== range.end.row) return; + if (range.start.row !== this.pos.row) return; + this.$updating = true; + var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column; + var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1; + var distanceFromStart = range.start.column - this.pos.column; + + this.updateAnchors(delta); + + if (inMainRange) + this.length += lengthDiff; + + if (inMainRange && !this.session.$fromUndo) { + if (delta.action === 'insert') { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + this.doc.insertMergedLines(newPos, delta.lines); + } + } else if (delta.action === 'remove') { + for (var i = this.others.length - 1; i >= 0; i--) { + var otherPos = this.others[i]; + var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; + this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff)); + } + } + } + + this.$updating = false; + this.updateMarkers(); + }; + + this.updateAnchors = function(delta) { + this.pos.onChange(delta); + for (var i = this.others.length; i--;) + this.others[i].onChange(delta); + this.updateMarkers(); + }; + + this.updateMarkers = function() { + if (this.$updating) + return; + var _self = this; + var session = this.session; + var updateMarker = function(pos, className) { + session.removeMarker(pos.markerId); + pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false); + }; + updateMarker(this.pos, this.mainClass); + for (var i = this.others.length; i--;) + updateMarker(this.others[i], this.othersClass); + }; + + this.onCursorChange = function(event) { + if (this.$updating || !this.session) return; + var pos = this.session.selection.getCursor(); + if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) { + this.showOtherMarkers(); + this._emit("cursorEnter", event); + } else { + this.hideOtherMarkers(); + this._emit("cursorLeave", event); + } + }; + this.detach = function() { + this.session.removeMarker(this.pos && this.pos.markerId); + this.hideOtherMarkers(); + this.doc.removeEventListener("change", this.$onUpdate); + this.session.selection.removeEventListener("changeCursor", this.$onCursorChange); + this.session.setUndoSelect(true); + this.session = null; + }; + this.cancel = function() { + if (this.$undoStackDepth === -1) + return; + var undoManager = this.session.getUndoManager(); + var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth; + for (var i = 0; i < undosRequired; i++) { + undoManager.undo(true); + } + if (this.selectionBefore) + this.session.selection.fromJSON(this.selectionBefore); + }; +}).call(PlaceHolder.prototype); + + +exports.PlaceHolder = PlaceHolder; +}); + +ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { + +var event = acequire("../lib/event"); +var useragent = acequire("../lib/useragent"); +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 = ev.ctrlKey; + var accel = e.getAccelKey(); + var button = e.getButton(); + + if (ctrl && useragent.isMac) + button = ev.button; + + if (e.editor.inMultiSelectMode && button == 2) { + e.editor.textInput.onContextMenu(e.domEvent); + return; + } + + if (!ctrl && !alt && !accel) { + if (button === 0 && e.editor.inMultiSelectMode) + e.editor.exitMultiSelectMode(); + return; + } + + if (button !== 0) + 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 session = editor.session; + var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); + var screenCursor = screenAnchor; + + var selectionMode; + if (editor.$mouseHandler.$enableJumpToDef) { + if (ctrl && alt || accel && alt) + selectionMode = shift ? "block" : "add"; + else if (alt && editor.$blockSelectEnabled) + selectionMode = "block"; + } else { + if (accel && !alt) { + selectionMode = "add"; + if (!isMultiSelect && shift) + return; + } else if (alt && editor.$blockSelectEnabled) { + selectionMode = "block"; + } + } + + if (selectionMode && useragent.isMac && ev.ctrlKey) { + editor.$mouseHandler.cancelContextMenu(); + } + + if (selectionMode == "add") { + if (!isMultiSelect && inSelection) + return; // dragging + + if (!isMultiSelect) { + var range = selection.toOrientedRange(); + editor.addSelectionMarker(range); + } + + var oldRange = selection.rangeList.rangeAtPoint(pos); + + + editor.$blockScrolling++; + editor.inVirtualSelectionMode = true; + + if (shift) { + oldRange = null; + range = selection.ranges[0] || range; + editor.removeSelectionMarker(range); + } + editor.once("mouseup", function() { + var tmpSel = selection.toOrientedRange(); + + if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) + selection.substractPoint(tmpSel.cursor); + else { + if (shift) { + selection.substractPoint(range.cursor); + } else if (range) { + editor.removeSelectionMarker(range); + selection.addRange(range); + } + selection.addRange(tmpSel); + } + editor.$blockScrolling--; + editor.inVirtualSelectionMode = false; + }); + + } else if (selectionMode == "block") { + e.stop(); + editor.inVirtualSelectionMode = true; + var initialRange; + var rectSel = []; + 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.lead)) + return; + screenCursor = newCursor; + + editor.$blockScrolling++; + editor.selection.moveToPosition(cursor); + editor.renderer.scrollCursorIntoView(); + + editor.removeSelectionMarkers(rectSel); + rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); + if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty()) + rectSel[0] = editor.$mouseHandler.$clickSelection.clone(); + rectSel.forEach(editor.addSelectionMarker, editor); + editor.updateSelectionMarkers(); + editor.$blockScrolling--; + }; + editor.$blockScrolling++; + if (isMultiSelect && !accel) { + selection.toSingleRange(); + } else if (!isMultiSelect && accel) { + initialRange = selection.toOrientedRange(); + editor.addSelectionMarker(initialRange); + } + + if (shift) + screenAnchor = session.documentToScreenPosition(selection.lead); + else + selection.moveToPosition(pos); + editor.$blockScrolling--; + + screenCursor = {row: -1, column: -1}; + + var onMouseSelectionEnd = function(e) { + clearInterval(timerId); + editor.removeSelectionMarkers(rectSel); + if (!rectSel.length) + rectSel = [selection.toOrientedRange()]; + editor.$blockScrolling++; + if (initialRange) { + editor.removeSelectionMarker(initialRange); + selection.toSingleRange(initialRange); + } + for (var i = 0; i < rectSel.length; i++) + selection.addRange(rectSel[i]); + editor.inVirtualSelectionMode = false; + editor.$mouseHandler.$clickSelection = null; + editor.$blockScrolling--; + }; + + var onSelectionInterval = blockSelect; + + event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); + var timerId = setInterval(function() {onSelectionInterval();}, 20); + + return e.preventDefault(); + } +} + + +exports.onMouseDown = onMouseDown; + +}); + +ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(acequire, exports, module) { +exports.defaultCommands = [{ + name: "addCursorAbove", + exec: function(editor) { editor.selectMoreLines(-1); }, + bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorBelow", + exec: function(editor) { editor.selectMoreLines(1); }, + bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorAboveSkipCurrent", + exec: function(editor) { editor.selectMoreLines(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "addCursorBelowSkipCurrent", + exec: function(editor) { editor.selectMoreLines(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectMoreBefore", + exec: function(editor) { editor.selectMore(-1); }, + bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectMoreAfter", + exec: function(editor) { editor.selectMore(1); }, + bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectNextBefore", + exec: function(editor) { editor.selectMore(-1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "selectNextAfter", + exec: function(editor) { editor.selectMore(1, true); }, + bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, + scrollIntoView: "cursor", + readOnly: true +}, { + name: "splitIntoLines", + exec: function(editor) { editor.multiSelect.splitIntoLines(); }, + bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"}, + readOnly: true +}, { + name: "alignCursors", + exec: function(editor) { editor.alignCursors(); }, + bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"}, + scrollIntoView: "cursor" +}, { + name: "findAll", + exec: function(editor) { editor.findAll(); }, + bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"}, + scrollIntoView: "cursor", + readOnly: true +}]; +exports.multiSelectCommands = [{ + name: "singleSelection", + bindKey: "esc", + exec: function(editor) { editor.exitMultiSelectMode(); }, + scrollIntoView: "cursor", + readOnly: true, + isAvailable: function(editor) {return editor && editor.inMultiSelectMode} +}]; + +var HashHandler = acequire("../keyboard/hash_handler").HashHandler; +exports.keyboardHandler = new HashHandler(exports.multiSelectCommands); + +}); + +ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(acequire, exports, module) { + +var RangeList = acequire("./range_list").RangeList; +var Range = acequire("./range").Range; +var Selection = acequire("./selection").Selection; +var onMouseDown = acequire("./mouse/multi_select_handler").onMouseDown; +var event = acequire("./lib/event"); +var lang = acequire("./lib/lang"); +var commands = acequire("./commands/multi_select_commands"); +exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands); +var Search = acequire("./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); +} +var EditSession = acequire("./edit_session").EditSession; +(function() { + this.getSelectionMarkers = function() { + return this.$selectionMarkers; + }; +}).call(EditSession.prototype); +(function() { + this.ranges = null; + this.rangeList = null; + this.addRange = function(range, $blockChangeEvents) { + if (!range) + return; + + if (!this.inMultiSelectMode && this.rangeCount === 0) { + var oldRange = this.toOrientedRange(); + this.rangeList.add(oldRange); + this.rangeList.add(range); + if (this.rangeList.ranges.length != 2) { + this.rangeList.removeAll(); + return $blockChangeEvents || this.fromOrientedRange(range); + } + this.rangeList.removeAll(); + 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._signal("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._signal("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._signal("removeRange", {ranges: removed}); + + if (this.rangeCount === 0 && this.inMultiSelectMode) { + this.inMultiSelectMode = false; + this._signal("singleSelect"); + this.session.$undoSelect = true; + this.rangeList.detach(this.session); + } + + lastRange = lastRange || this.ranges[0]; + if (lastRange && !lastRange.isEqual(this.getRange())) + this.fromOrientedRange(lastRange); + }; + this.$initRangeList = function() { + if (this.rangeList) + return; + + this.rangeList = new RangeList(); + this.ranges = []; + this.rangeCount = 0; + }; + this.getAllRanges = function() { + return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()]; + }; + + 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 isBackwards = this.isBackwards(); + var startRow = range.start.row; + var endRow = range.end.row; + if (startRow == endRow) { + if (isBackwards) + var start = range.end, end = range.start; + else + var start = range.start, end = range.end; + + this.addRange(Range.fromPoints(end, end)); + this.addRange(Range.fromPoints(start, start)); + 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); +var Editor = acequire("./editor").Editor; +(function() { + 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("ace_multiselect"); + this.keyBinding.addKeyboardHandler(commands.keyboardHandler); + this.commands.setDefaultHandler("exec", this.$onMultiSelectExec); + + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + }; + + this.$onSingleSelect = function(e) { + if (this.session.multiSelect.inVirtualMode) + return; + this.inMultiSelectMode = false; + + this.unsetStyle("ace_multiselect"); + this.keyBinding.removeKeyboardHandler(commands.keyboardHandler); + + this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + this._emit("changeSelection"); + }; + + this.$onMultiSelectExec = function(e) { + var command = e.command; + var editor = e.editor; + if (!editor.multiSelect) + return; + if (!command.multiSelectAction) { + var result = command.exec(editor, e.args || {}); + editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); + editor.multiSelect.mergeOverlappingRanges(); + } else if (command.multiSelectAction == "forEach") { + result = editor.forEachSelection(command, e.args); + } else if (command.multiSelectAction == "forEachLine") { + result = editor.forEachSelection(command, e.args, true); + } else if (command.multiSelectAction == "single") { + editor.exitMultiSelectMode(); + result = command.exec(editor, e.args || {}); + } else { + result = command.multiSelectAction(editor, e.args || {}); + } + return result; + }; + this.forEachSelection = function(cmd, args, options) { + if (this.inVirtualSelectionMode) + return; + var keepOrder = options && options.keepOrder; + var $byLines = options == true || options && options.$byLines + var session = this.session; + var selection = this.selection; + var rangeList = selection.rangeList; + var ranges = (keepOrder ? selection : rangeList).ranges; + var result; + + if (!ranges.length) + return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); + + var reg = selection._eventRegistry; + selection._eventRegistry = {}; + + var tmpSel = new Selection(session); + this.inVirtualSelectionMode = true; + for (var i = ranges.length; i--;) { + if ($byLines) { + while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row) + i--; + } + tmpSel.fromOrientedRange(ranges[i]); + tmpSel.index = i; + this.selection = session.selection = tmpSel; + var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); + if (!result && cmdResult !== undefined) + result = cmdResult; + tmpSel.toOrientedRange(ranges[i]); + } + tmpSel.detach(); + + this.selection = session.selection = selection; + this.inVirtualSelectionMode = false; + selection._eventRegistry = reg; + selection.mergeOverlappingRanges(); + + var anim = this.renderer.$scrollAnimation; + this.onCursorChange(); + this.onSelectionChange(); + if (anim && anim.from == anim.to) + this.renderer.animateScrolling(anim.from); + + return result; + }; + this.exitMultiSelectMode = function() { + if (!this.inMultiSelectMode || this.inVirtualSelectionMode) + return; + this.multiSelect.toSingleRange(); + }; + + this.getSelectedText = function() { + var text = ""; + if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { + var ranges = this.multiSelect.rangeList.ranges; + var buf = []; + for (var i = 0; i < ranges.length; i++) { + buf.push(this.session.getTextRange(ranges[i])); + } + var nl = this.session.getDocument().getNewLineCharacter(); + text = buf.join(nl); + if (text.length == (buf.length - 1) * nl.length) + text = ""; + } else if (!this.selection.isEmpty()) { + text = this.session.getTextRange(this.getSelectionRange()); + } + return text; + }; + + this.$checkMultiselectChange = function(e, anchor) { + if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { + var range = this.multiSelect.ranges[0]; + if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor) + return; + var pos = anchor == this.multiSelect.anchor + ? range.cursor == range.start ? range.end : range.start + : range.cursor; + if (pos.row != anchor.row + || this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column) + this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange()); + } + }; + this.findAll = function(needle, options, additive) { + options = options || {}; + options.needle = needle || options.needle; + if (options.needle == undefined) { + var range = this.selection.isEmpty() + ? this.selection.getWordRange() + : this.selection.getRange(); + options.needle = this.session.getTextRange(range); + } + 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); + if (range && selection.rangeList.rangeAtPoint(range.start)) + selection.addRange(range, true); + + this.$blockScrolling -= 1; + + return ranges.length; + }; + 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; + } + }; + this.selectMore = function(dir, skip, stopAtFirst) { + var session = this.session; + var sel = session.multiSelect; + + var range = sel.toOrientedRange(); + if (range.isEmpty()) { + range = session.getWordRange(range.start.row, range.start.column); + range.cursor = dir == -1 ? range.start : range.end; + this.multiSelect.addRange(range); + if (stopAtFirst) + return; + } + var needle = session.getTextRange(range); + + var newRange = find(session, needle, dir); + if (newRange) { + newRange.cursor = dir == -1 ? newRange.start : newRange.end; + this.$blockScrolling += 1; + this.session.unfold(newRange); + this.multiSelect.addRange(newRange); + this.$blockScrolling -= 1; + this.renderer.scrollCursorIntoView(null, 0.5); + } + if (skip) + this.multiSelect.substractPoint(range.cursor); + }; + this.alignCursors = function() { + var session = this.session; + var sel = session.multiSelect; + var ranges = sel.ranges; + var row = -1; + var sameRowRanges = ranges.filter(function(r) { + if (r.cursor.row == row) + return true; + row = r.cursor.row; + }); + + if (!ranges.length || sameRowRanges.length == ranges.length - 1) { + var range = this.selection.getRange(); + var fr = range.start.row, lr = range.end.row; + var guessRange = fr == lr; + if (guessRange) { + var max = this.session.getLength(); + var line; + do { + line = this.session.getLine(lr); + } while (/[=:]/.test(line) && ++lr < max); + do { + line = this.session.getLine(fr); + } while (/[=:]/.test(line) && --fr > 0); + + if (fr < 0) fr = 0; + if (lr >= max) lr = max - 1; + } + var lines = this.session.removeFullLines(fr, lr); + lines = this.$reAlignText(lines, guessRange); + this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n"); + if (!guessRange) { + range.start.column = 0; + range.end.column = lines[lines.length - 1].length; + } + this.selection.setRange(range); + } else { + sameRowRanges.forEach(function(r) { + sel.substractPoint(r.cursor); + }); + + var maxCol = 0; + var minSpace = Infinity; + var spaceOffsets = ranges.map(function(r) { + var p = r.cursor; + var line = session.getLine(p.row); + var spaceOffset = line.substr(p.column).search(/\S/g); + if (spaceOffset == -1) + spaceOffset = 0; + + if (p.column > maxCol) + maxCol = p.column; + if (spaceOffset < minSpace) + minSpace = spaceOffset; + return spaceOffset; + }); + ranges.forEach(function(r, i) { + var p = r.cursor; + var l = maxCol - p.column; + var d = spaceOffsets[i] - minSpace; + if (l > d) + session.insert(p, lang.stringRepeat(" ", l - d)); + else + session.remove(new Range(p.row, p.column, p.row, p.column - l + d)); + + r.start.column = r.end.column = maxCol; + r.start.row = r.end.row = p.row; + r.cursor = r.end; + }); + sel.fromOrientedRange(ranges[0]); + this.renderer.updateCursor(); + this.renderer.updateBackMarkers(); + } + }; + + this.$reAlignText = function(lines, forceLeft) { + var isLeftAligned = true, isRightAligned = true; + var startW, textW, endW; + + return lines.map(function(line) { + var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/); + if (!m) + return [line]; + + if (startW == null) { + startW = m[1].length; + textW = m[2].length; + endW = m[3].length; + return m; + } + + if (startW + textW + endW != m[1].length + m[2].length + m[3].length) + isRightAligned = false; + if (startW != m[1].length) + isLeftAligned = false; + + if (startW > m[1].length) + startW = m[1].length; + if (textW < m[2].length) + textW = m[2].length; + if (endW > m[3].length) + endW = m[3].length; + + return m; + }).map(forceLeft ? alignLeft : + isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign); + + function spaces(n) { + return lang.stringRepeat(" ", n); + } + + function alignLeft(m) { + return !m[2] ? m[0] : spaces(startW) + m[2] + + spaces(textW - m[2].length + endW) + + m[4].replace(/^([=:])\s+/, "$1 "); + } + function alignRight(m) { + return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2] + + spaces(endW, " ") + + m[4].replace(/^([=:])\s+/, "$1 "); + } + function unAlign(m) { + return !m[2] ? m[0] : spaces(startW) + m[2] + + spaces(endW) + + m[4].replace(/^([=:])\s+/, "$1 "); + } + }; +}).call(Editor.prototype); + + +function isSamePoint(p1, p2) { + return p1.row == p2.row && p1.column == p2.column; +} +exports.onSessionChange = function(e) { + var session = e.session; + if (session && !session.multiSelect) { + session.$selectionMarkers = []; + session.selection.$initRangeList(); + session.multiSelect = session.selection; + } + this.multiSelect = session && session.multiSelect; + + var oldSession = e.oldSession; + if (oldSession) { + oldSession.multiSelect.off("addRange", this.$onAddRange); + oldSession.multiSelect.off("removeRange", this.$onRemoveRange); + oldSession.multiSelect.off("multiSelect", this.$onMultiSelect); + oldSession.multiSelect.off("singleSelect", this.$onSingleSelect); + oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange); + oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange); + } + + if (session) { + session.multiSelect.on("addRange", this.$onAddRange); + session.multiSelect.on("removeRange", this.$onRemoveRange); + session.multiSelect.on("multiSelect", this.$onMultiSelect); + session.multiSelect.on("singleSelect", this.$onSingleSelect); + session.multiSelect.lead.on("change", this.$checkMultiselectChange); + session.multiSelect.anchor.on("change", this.$checkMultiselectChange); + } + + if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) { + if (session.selection.inMultiSelectMode) + this.$onMultiSelect(); + else + this.$onSingleSelect(); + } +}; +function MultiSelect(editor) { + if (editor.$multiselectOnSessionChange) + return; + editor.$onAddRange = editor.$onAddRange.bind(editor); + editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); + editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); + editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); + editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor); + editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor); + + editor.$multiselectOnSessionChange(editor); + editor.on("changeSession", editor.$multiselectOnSessionChange); + + editor.on("mousedown", onMouseDown); + editor.commands.addCommands(commands.defaultCommands); + + addAltCursorListeners(editor); +} + +function addAltCursorListeners(editor){ + var el = editor.textInput.getElement(); + var altCursor = false; + event.addListener(el, "keydown", function(e) { + var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey); + if (editor.$blockSelectEnabled && altDown) { + if (!altCursor) { + editor.renderer.setMouseCursor("crosshair"); + altCursor = true; + } + } else if (altCursor) { + reset(); + } + }); + + event.addListener(el, "keyup", reset); + event.addListener(el, "blur", reset); + function reset(e) { + if (altCursor) { + editor.renderer.setMouseCursor(""); + altCursor = false; + } + } +} + +exports.MultiSelect = MultiSelect; + + +acequire("./config").defineOptions(Editor.prototype, "editor", { + enableMultiselect: { + set: function(val) { + MultiSelect(this); + if (val) { + this.on("changeSession", this.$multiselectOnSessionChange); + this.on("mousedown", onMouseDown); + } else { + this.off("changeSession", this.$multiselectOnSessionChange); + this.off("mousedown", onMouseDown); + } + }, + value: true + }, + enableBlockSelect: { + set: function(val) { + this.$blockSelectEnabled = val; + }, + value: true + } +}); + + + +}); + +ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../../range").Range; + +var FoldMode = exports.FoldMode = function() {}; + +(function() { + + this.foldingStartMarker = null; + this.foldingStopMarker = null; + 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 line = session.getLine(row); + var startLevel = line.search(re); + if (startLevel == -1) + return; + + var startColumn = column || line.length; + var maxRow = session.getLength(); + var startRow = row; + var endRow = row; + + while (++row < maxRow) { + var level = session.getLine(row).search(re); + + if (level == -1) + 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) { + var start = {row: row, column: column + 1}; + var end = session.$findClosingBracket(bracket, start, typeRe); + if (!end) + return; + + var fw = session.foldWidgets[end.row]; + if (fw == null) + fw = session.getFoldWidget(end.row); + + if (fw == "start" && end.row > start.row) { + end.row --; + end.column = session.getLine(end.row).length; + } + return Range.fromPoints(start, end); + }; + + this.closingBracketBlock = function(session, bracket, row, column, typeRe) { + var end = {row: row, column: column}; + var start = session.$findOpeningBracket(bracket, end); + + if (!start) + return; + + start.column++; + end.column--; + + return Range.fromPoints(start, end); + }; +}).call(FoldMode.prototype); + +}); + +ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +exports.isDark = false; +exports.cssClass = "ace-tm"; +exports.cssText = ".ace-tm .ace_gutter {\ +background: #f0f0f0;\ +color: #333;\ +}\ +.ace-tm .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8;\ +}\ +.ace-tm .ace_fold {\ +background-color: #6B72E6;\ +}\ +.ace-tm {\ +background-color: #FFFFFF;\ +color: black;\ +}\ +.ace-tm .ace_cursor {\ +color: black;\ +}\ +.ace-tm .ace_invisible {\ +color: rgb(191, 191, 191);\ +}\ +.ace-tm .ace_storage,\ +.ace-tm .ace_keyword {\ +color: blue;\ +}\ +.ace-tm .ace_constant {\ +color: rgb(197, 6, 11);\ +}\ +.ace-tm .ace_constant.ace_buildin {\ +color: rgb(88, 72, 246);\ +}\ +.ace-tm .ace_constant.ace_language {\ +color: rgb(88, 92, 246);\ +}\ +.ace-tm .ace_constant.ace_library {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_invalid {\ +background-color: rgba(255, 0, 0, 0.1);\ +color: red;\ +}\ +.ace-tm .ace_support.ace_function {\ +color: rgb(60, 76, 114);\ +}\ +.ace-tm .ace_support.ace_constant {\ +color: rgb(6, 150, 14);\ +}\ +.ace-tm .ace_support.ace_type,\ +.ace-tm .ace_support.ace_class {\ +color: rgb(109, 121, 222);\ +}\ +.ace-tm .ace_keyword.ace_operator {\ +color: rgb(104, 118, 135);\ +}\ +.ace-tm .ace_string {\ +color: rgb(3, 106, 7);\ +}\ +.ace-tm .ace_comment {\ +color: rgb(76, 136, 107);\ +}\ +.ace-tm .ace_comment.ace_doc {\ +color: rgb(0, 102, 255);\ +}\ +.ace-tm .ace_comment.ace_doc.ace_tag {\ +color: rgb(128, 159, 191);\ +}\ +.ace-tm .ace_constant.ace_numeric {\ +color: rgb(0, 0, 205);\ +}\ +.ace-tm .ace_variable {\ +color: rgb(49, 132, 149);\ +}\ +.ace-tm .ace_xml-pe {\ +color: rgb(104, 104, 91);\ +}\ +.ace-tm .ace_entity.ace_name.ace_function {\ +color: #0000A2;\ +}\ +.ace-tm .ace_heading {\ +color: rgb(12, 7, 255);\ +}\ +.ace-tm .ace_list {\ +color:rgb(185, 6, 144);\ +}\ +.ace-tm .ace_meta.ace_tag {\ +color:rgb(0, 22, 142);\ +}\ +.ace-tm .ace_string.ace_regex {\ +color: rgb(255, 0, 0)\ +}\ +.ace-tm .ace_marker-layer .ace_selection {\ +background: rgb(181, 213, 255);\ +}\ +.ace-tm.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px white;\ +}\ +.ace-tm .ace_marker-layer .ace_step {\ +background: rgb(252, 255, 0);\ +}\ +.ace-tm .ace_marker-layer .ace_stack {\ +background: rgb(164, 229, 101);\ +}\ +.ace-tm .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgb(192, 192, 192);\ +}\ +.ace-tm .ace_marker-layer .ace_active-line {\ +background: rgba(0, 0, 0, 0.07);\ +}\ +.ace-tm .ace_gutter-active-line {\ +background-color : #dcdcdc;\ +}\ +.ace-tm .ace_marker-layer .ace_selected-word {\ +background: rgb(250, 250, 255);\ +border: 1px solid rgb(200, 200, 250);\ +}\ +.ace-tm .ace_indent-guide {\ +background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + +ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var dom = acequire("./lib/dom"); +var Range = acequire("./range").Range; + + +function LineWidgets(session) { + this.session = session; + this.session.widgetManager = this; + this.session.getRowLength = this.getRowLength; + this.session.$getWidgetScreenLength = this.$getWidgetScreenLength; + this.updateOnChange = this.updateOnChange.bind(this); + this.renderWidgets = this.renderWidgets.bind(this); + this.measureWidgets = this.measureWidgets.bind(this); + this.session._changedWidgets = []; + this.$onChangeEditor = this.$onChangeEditor.bind(this); + + this.session.on("change", this.updateOnChange); + this.session.on("changeFold", this.updateOnFold); + this.session.on("changeEditor", this.$onChangeEditor); +} + +(function() { + this.getRowLength = function(row) { + var h; + if (this.lineWidgets) + h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; + else + h = 0; + if (!this.$useWrapMode || !this.$wrapData[row]) { + return 1 + h; + } else { + return this.$wrapData[row].length + 1 + h; + } + }; + + this.$getWidgetScreenLength = function() { + var screenRows = 0; + this.lineWidgets.forEach(function(w){ + if (w && w.rowCount && !w.hidden) + screenRows += w.rowCount; + }); + return screenRows; + }; + + this.$onChangeEditor = function(e) { + this.attach(e.editor); + }; + + this.attach = function(editor) { + if (editor && editor.widgetManager && editor.widgetManager != this) + editor.widgetManager.detach(); + + if (this.editor == editor) + return; + + this.detach(); + this.editor = editor; + + if (editor) { + editor.widgetManager = this; + editor.renderer.on("beforeRender", this.measureWidgets); + editor.renderer.on("afterRender", this.renderWidgets); + } + }; + this.detach = function(e) { + var editor = this.editor; + if (!editor) + return; + + this.editor = null; + editor.widgetManager = null; + + editor.renderer.off("beforeRender", this.measureWidgets); + editor.renderer.off("afterRender", this.renderWidgets); + var lineWidgets = this.session.lineWidgets; + lineWidgets && lineWidgets.forEach(function(w) { + if (w && w.el && w.el.parentNode) { + w._inDocument = false; + w.el.parentNode.removeChild(w.el); + } + }); + }; + + this.updateOnFold = function(e, session) { + var lineWidgets = session.lineWidgets; + if (!lineWidgets || !e.action) + return; + var fold = e.data; + var start = fold.start.row; + var end = fold.end.row; + var hide = e.action == "add"; + for (var i = start + 1; i < end; i++) { + if (lineWidgets[i]) + lineWidgets[i].hidden = hide; + } + if (lineWidgets[end]) { + if (hide) { + if (!lineWidgets[start]) + lineWidgets[start] = lineWidgets[end]; + else + lineWidgets[end].hidden = hide; + } else { + if (lineWidgets[start] == lineWidgets[end]) + lineWidgets[start] = undefined; + lineWidgets[end].hidden = hide; + } + } + }; + + this.updateOnChange = function(delta) { + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) return; + + var startRow = delta.start.row; + var len = delta.end.row - startRow; + + if (len === 0) { + } else if (delta.action == 'remove') { + var removed = lineWidgets.splice(startRow + 1, len); + removed.forEach(function(w) { + w && this.removeLineWidget(w); + }, this); + this.$updateRows(); + } else { + var args = new Array(len); + args.unshift(startRow, 0); + lineWidgets.splice.apply(lineWidgets, args); + this.$updateRows(); + } + }; + + this.$updateRows = function() { + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) return; + var noWidgets = true; + lineWidgets.forEach(function(w, i) { + if (w) { + noWidgets = false; + w.row = i; + while (w.$oldWidget) { + w.$oldWidget.row = i; + w = w.$oldWidget; + } + } + }); + if (noWidgets) + this.session.lineWidgets = null; + }; + + this.addLineWidget = function(w) { + if (!this.session.lineWidgets) + this.session.lineWidgets = new Array(this.session.getLength()); + + var old = this.session.lineWidgets[w.row]; + if (old) { + w.$oldWidget = old; + if (old.el && old.el.parentNode) { + old.el.parentNode.removeChild(old.el); + old._inDocument = false; + } + } + + this.session.lineWidgets[w.row] = w; + + w.session = this.session; + + var renderer = this.editor.renderer; + if (w.html && !w.el) { + w.el = dom.createElement("div"); + w.el.innerHTML = w.html; + } + if (w.el) { + dom.addCssClass(w.el, "ace_lineWidgetContainer"); + w.el.style.position = "absolute"; + w.el.style.zIndex = 5; + renderer.container.appendChild(w.el); + w._inDocument = true; + } + + if (!w.coverGutter) { + w.el.style.zIndex = 3; + } + if (w.pixelHeight == null) { + w.pixelHeight = w.el.offsetHeight; + } + if (w.rowCount == null) { + w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight; + } + + var fold = this.session.getFoldAt(w.row, 0); + w.$fold = fold; + if (fold) { + var lineWidgets = this.session.lineWidgets; + if (w.row == fold.end.row && !lineWidgets[fold.start.row]) + lineWidgets[fold.start.row] = w; + else + w.hidden = true; + } + + this.session._emit("changeFold", {data:{start:{row: w.row}}}); + + this.$updateRows(); + this.renderWidgets(null, renderer); + this.onWidgetChanged(w); + return w; + }; + + this.removeLineWidget = function(w) { + w._inDocument = false; + w.session = null; + if (w.el && w.el.parentNode) + w.el.parentNode.removeChild(w.el); + if (w.editor && w.editor.destroy) try { + w.editor.destroy(); + } catch(e){} + if (this.session.lineWidgets) { + var w1 = this.session.lineWidgets[w.row] + if (w1 == w) { + this.session.lineWidgets[w.row] = w.$oldWidget; + if (w.$oldWidget) + this.onWidgetChanged(w.$oldWidget); + } else { + while (w1) { + if (w1.$oldWidget == w) { + w1.$oldWidget = w.$oldWidget; + break; + } + w1 = w1.$oldWidget; + } + } + } + this.session._emit("changeFold", {data:{start:{row: w.row}}}); + this.$updateRows(); + }; + + this.getWidgetsAtRow = function(row) { + var lineWidgets = this.session.lineWidgets; + var w = lineWidgets && lineWidgets[row]; + var list = []; + while (w) { + list.push(w); + w = w.$oldWidget; + } + return list; + }; + + this.onWidgetChanged = function(w) { + this.session._changedWidgets.push(w); + this.editor && this.editor.renderer.updateFull(); + }; + + this.measureWidgets = function(e, renderer) { + var changedWidgets = this.session._changedWidgets; + var config = renderer.layerConfig; + + if (!changedWidgets || !changedWidgets.length) return; + var min = Infinity; + for (var i = 0; i < changedWidgets.length; i++) { + var w = changedWidgets[i]; + if (!w || !w.el) continue; + if (w.session != this.session) continue; + if (!w._inDocument) { + if (this.session.lineWidgets[w.row] != w) + continue; + w._inDocument = true; + renderer.container.appendChild(w.el); + } + + w.h = w.el.offsetHeight; + + if (!w.fixedWidth) { + w.w = w.el.offsetWidth; + w.screenWidth = Math.ceil(w.w / config.characterWidth); + } + + var rowCount = w.h / config.lineHeight; + if (w.coverLine) { + rowCount -= this.session.getRowLineCount(w.row); + if (rowCount < 0) + rowCount = 0; + } + if (w.rowCount != rowCount) { + w.rowCount = rowCount; + if (w.row < min) + min = w.row; + } + } + if (min != Infinity) { + this.session._emit("changeFold", {data:{start:{row: min}}}); + this.session.lineWidgetWidth = null; + } + this.session._changedWidgets = []; + }; + + this.renderWidgets = function(e, renderer) { + var config = renderer.layerConfig; + var lineWidgets = this.session.lineWidgets; + if (!lineWidgets) + return; + var first = Math.min(this.firstRow, config.firstRow); + var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length); + + while (first > 0 && !lineWidgets[first]) + first--; + + this.firstRow = config.firstRow; + this.lastRow = config.lastRow; + + renderer.$cursorLayer.config = config; + for (var i = first; i <= last; i++) { + var w = lineWidgets[i]; + if (!w || !w.el) continue; + if (w.hidden) { + w.el.style.top = -100 - (w.pixelHeight || 0) + "px"; + continue; + } + if (!w._inDocument) { + w._inDocument = true; + renderer.container.appendChild(w.el); + } + var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top; + if (!w.coverLine) + top += config.lineHeight * this.session.getRowLineCount(w.row); + w.el.style.top = top - config.offset + "px"; + + var left = w.coverGutter ? 0 : renderer.gutterWidth; + if (!w.fixedWidth) + left -= renderer.scrollLeft; + w.el.style.left = left + "px"; + + if (w.fullWidth && w.screenWidth) { + w.el.style.minWidth = config.width + 2 * config.padding + "px"; + } + + if (w.fixedWidth) { + w.el.style.right = renderer.scrollBar.getWidth() + "px"; + } else { + w.el.style.right = ""; + } + } + }; + +}).call(LineWidgets.prototype); + + +exports.LineWidgets = LineWidgets; + +}); + +ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(acequire, exports, module) { +"use strict"; +var LineWidgets = acequire("../line_widgets").LineWidgets; +var dom = acequire("../lib/dom"); +var Range = acequire("../range").Range; + +function binarySearch(array, needle, comparator) { + var first = 0; + var last = array.length - 1; + + while (first <= last) { + var mid = (first + last) >> 1; + var c = comparator(needle, array[mid]); + if (c > 0) + first = mid + 1; + else if (c < 0) + last = mid - 1; + else + return mid; + } + return -(first + 1); +} + +function findAnnotations(session, row, dir) { + var annotations = session.getAnnotations().sort(Range.comparePoints); + if (!annotations.length) + return; + + var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints); + if (i < 0) + i = -i - 1; + + if (i >= annotations.length) + i = dir > 0 ? 0 : annotations.length - 1; + else if (i === 0 && dir < 0) + i = annotations.length - 1; + + var annotation = annotations[i]; + if (!annotation || !dir) + return; + + if (annotation.row === row) { + do { + annotation = annotations[i += dir]; + } while (annotation && annotation.row === row); + if (!annotation) + return annotations.slice(); + } + + + var matched = []; + row = annotation.row; + do { + matched[dir < 0 ? "unshift" : "push"](annotation); + annotation = annotations[i += dir]; + } while (annotation && annotation.row == row); + return matched.length && matched; +} + +exports.showErrorMarker = function(editor, dir) { + var session = editor.session; + if (!session.widgetManager) { + session.widgetManager = new LineWidgets(session); + session.widgetManager.attach(editor); + } + + var pos = editor.getCursorPosition(); + var row = pos.row; + var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) { + return w.type == "errorMarker"; + })[0]; + if (oldWidget) { + oldWidget.destroy(); + } else { + row -= dir; + } + var annotations = findAnnotations(session, row, dir); + var gutterAnno; + if (annotations) { + var annotation = annotations[0]; + pos.column = (annotation.pos && typeof annotation.column != "number" + ? annotation.pos.sc + : annotation.column) || 0; + pos.row = annotation.row; + gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row]; + } else if (oldWidget) { + return; + } else { + gutterAnno = { + text: ["Looks good!"], + className: "ace_ok" + }; + } + editor.session.unfold(pos.row); + editor.selection.moveToPosition(pos); + + var w = { + row: pos.row, + fixedWidth: true, + coverGutter: true, + el: dom.createElement("div"), + type: "errorMarker" + }; + var el = w.el.appendChild(dom.createElement("div")); + var arrow = w.el.appendChild(dom.createElement("div")); + arrow.className = "error_widget_arrow " + gutterAnno.className; + + var left = editor.renderer.$cursorLayer + .getPixelPosition(pos).left; + arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px"; + + w.el.className = "error_widget_wrapper"; + el.className = "error_widget " + gutterAnno.className; + el.innerHTML = gutterAnno.text.join("
"); + + el.appendChild(dom.createElement("div")); + + var kb = function(_, hashId, keyString) { + if (hashId === 0 && (keyString === "esc" || keyString === "return")) { + w.destroy(); + return {command: "null"}; + } + }; + + w.destroy = function() { + if (editor.$mouseHandler.isMousePressed) + return; + editor.keyBinding.removeKeyboardHandler(kb); + session.widgetManager.removeLineWidget(w); + editor.off("changeSelection", w.destroy); + editor.off("changeSession", w.destroy); + editor.off("mouseup", w.destroy); + editor.off("change", w.destroy); + }; + + editor.keyBinding.addKeyboardHandler(kb); + editor.on("changeSelection", w.destroy); + editor.on("changeSession", w.destroy); + editor.on("mouseup", w.destroy); + editor.on("change", w.destroy); + + editor.session.widgetManager.addLineWidget(w); + + w.el.onmousedown = editor.focus.bind(editor); + + editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight}); +}; + + +dom.importCssString("\ + .error_widget_wrapper {\ + background: inherit;\ + color: inherit;\ + border:none\ + }\ + .error_widget {\ + border-top: solid 2px;\ + border-bottom: solid 2px;\ + margin: 5px 0;\ + padding: 10px 40px;\ + white-space: pre-wrap;\ + }\ + .error_widget.ace_error, .error_widget_arrow.ace_error{\ + border-color: #ff5a5a\ + }\ + .error_widget.ace_warning, .error_widget_arrow.ace_warning{\ + border-color: #F1D817\ + }\ + .error_widget.ace_info, .error_widget_arrow.ace_info{\ + border-color: #5a5a5a\ + }\ + .error_widget.ace_ok, .error_widget_arrow.ace_ok{\ + border-color: #5aaa5a\ + }\ + .error_widget_arrow {\ + position: absolute;\ + border: solid 5px;\ + border-top-color: transparent!important;\ + border-right-color: transparent!important;\ + border-left-color: transparent!important;\ + top: -5px;\ + }\ +", ""); + +}); + +ace.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/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(acequire, exports, module) { +"use strict"; + +acequire("./lib/fixoldbrowsers"); + +var dom = acequire("./lib/dom"); +var event = acequire("./lib/event"); + +var Editor = acequire("./editor").Editor; +var EditSession = acequire("./edit_session").EditSession; +var UndoManager = acequire("./undomanager").UndoManager; +var Renderer = acequire("./virtual_renderer").VirtualRenderer; +acequire("./worker/worker_client"); +acequire("./keyboard/hash_handler"); +acequire("./placeholder"); +acequire("./multi_select"); +acequire("./mode/folding/fold_mode"); +acequire("./theme/textmate"); +acequire("./ext/error_marker"); + +exports.config = acequire("./config"); +exports.acequire = acequire; + +if (true) + exports.define = __webpack_require__(41); +exports.edit = function(el) { + if (typeof el == "string") { + var _id = el; + el = document.getElementById(_id); + if (!el) + throw new Error("ace.edit can't find div #" + _id); + } + + if (el && el.env && el.env.editor instanceof Editor) + return el.env.editor; + + var value = ""; + if (el && /input|textarea/i.test(el.tagName)) { + var oldNode = el; + value = oldNode.value; + el = dom.createElement("pre"); + oldNode.parentNode.replaceChild(el, oldNode); + } else if (el) { + value = dom.getInnerText(el); + el.innerHTML = ""; + } + + var doc = exports.createEditSession(value); + + var editor = new Editor(new Renderer(el)); + editor.setSession(doc); + + var env = { + document: doc, + editor: editor, + onResize: editor.resize.bind(editor, null) + }; + if (oldNode) env.textarea = oldNode; + event.addListener(window, "resize", env.onResize); + editor.on("destroy", function() { + event.removeListener(window, "resize", env.onResize); + env.editor.container.env = null; // prevent memory leak on old ie + }); + editor.container.env = editor.env = env; + return editor; +}; +exports.createEditSession = function(text, mode) { + var doc = new EditSession(text, mode); + doc.setUndoManager(new UndoManager()); + return doc; +} +exports.EditSession = EditSession; +exports.UndoManager = UndoManager; +exports.version = "1.2.6"; +}); + (function() { + ace.acequire(["ace/ace"], function(a) { + if (a) { + a.config.init(true); + a.define = ace.define; + } + if (!window.ace) + window.ace = a; + for (var key in a) if (a.hasOwnProperty(key)) + window.ace[key] = a[key]; + }); + })(); + +module.exports = window.ace.acequire("ace/ace"); + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {module.exports = get_blob() + +function get_blob() { + if(global.Blob) { + try { + new Blob(['asdf'], {type: 'text/plain'}) + return Blob + } catch(err) {} + } + + var Builder = global.WebKitBlobBuilder || + global.MozBlobBuilder || + global.MSBlobBuilder + + return function(parts, bag) { + var builder = new Builder + , endings = bag.endings + , type = bag.type + + if(endings) for(var i = 0, len = parts.length; i < len; ++i) { + builder.append(parts[i], endings) + } else for(var i = 0, len = parts.length; i < len; ++i) { + builder.append(parts[i]) + } + + return type ? builder.getBlob(type) : builder.getBlob() + } +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; + +var JavaScriptHighlightRules = function(options) { + var keywordMapper = this.createKeywordMapper({ + "variable.language": + "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors + "Namespace|QName|XML|XMLList|" + // E4X + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors + "SyntaxError|TypeError|URIError|" + + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions + "isNaN|parseFloat|parseInt|" + + "JSON|Math|" + // Other + "this|arguments|prototype|window|document" , // Pseudo + "keyword": + "const|yield|import|get|set|async|await|" + + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + + "__parent__|__count__|escape|unescape|with|__proto__|" + + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", + "storage.type": + "const|let|var|function", + "constant.language": + "null|Infinity|NaN|undefined", + "support.function": + "alert", + "constant.language.boolean": "true|false" + }, "identifier"); + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-7][0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + this.$rules = { + "no_regex" : [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("no_regex"), + { + token : "string", + regex : "'(?=.)", + next : "qstring" + }, { + token : "string", + regex : '"(?=.)', + next : "qqstring" + }, { + token : "constant.numeric", // hex + regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { + token : [ + "storage.type", "punctuation.operator", "support.function", + "punctuation.operator", "entity.name.function", "text","keyword.operator" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", + next: "function_arguments" + }, { + 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" + }, { + token : [ + "entity.name.function", "text", "keyword.operator", "text", "storage.type", + "text", "paren.lparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "punctuation.operator", + "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "text", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "start" + }, { + token : ["support.constant"], + regex : /that\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ + }, { + token : keywordMapper, + regex : identifierRe + }, { + token : "punctuation.operator", + regex : /[.](?![.])/, + next : "property" + }, { + token : "keyword.operator", + regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, + next : "start" + }, { + token : "punctuation.operator", + regex : /[?:,;.]/, + next : "start" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "start" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token: "comment", + regex: /^#!.*$/ + } + ], + property: [{ + token : "text", + regex : "\\s+" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", + next: "function_arguments" + }, { + token : "punctuation.operator", + regex : /[.](?![.])/ + }, { + token : "support.function", + regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|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 : "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|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : "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 : "identifier", + regex : identifierRe + }, { + regex: "", + token: "empty", + next: "no_regex" + } + ], + "start": [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("start"), + { + token: "string.regexp", + regex: "\\/", + next: "regex" + }, { + token : "text", + regex : "\\s+|^$", + next : "start" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "string.regexp", + regex: "/[sxngimy]*", + next: "no_regex" + }, { + token : "invalid", + regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ + }, { + token : "constant.language.escape", + regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ + }, { + token : "constant.language.delimiter", + regex: /\|/ + }, { + token: "constant.language.escape", + regex: /\[\^?/, + next: "regex_character_class" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp" + } + ], + "regex_character_class": [ + { + token: "regexp.charclass.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "constant.language.escape", + regex: "]", + next: "regex" + }, { + token: "constant.language.escape", + regex: "-" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp.charachterclass" + } + ], + "function_arguments": [ + { + token: "variable.parameter", + regex: identifierRe + }, { + token: "punctuation.operator", + regex: "[, ]+" + }, { + token: "punctuation.operator", + regex: "$" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qqstring" + }, { + token : "string", + regex : '"|$', + next : "no_regex" + }, { + defaultToken: "string" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qstring" + }, { + token : "string", + regex : "'|$", + next : "no_regex" + }, { + defaultToken: "string" + } + ] + }; + + + if (!options || !options.noES6) { + this.$rules.no_regex.unshift({ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + } + else if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) + return "paren.quasi.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.quasi.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : escapedRe + }, { + token : "paren.quasi.start", + regex : /\${/, + push : "start" + }, { + token : "string.quasi.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string.quasi" + }] + }); + + if (!options || options.jsx != false) + JSX.call(this); + } + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("no_regex") ]); + + this.normalizeRules(); +}; + +oop.inherits(JavaScriptHighlightRules, TextHighlightRules); + +function JSX() { + var tagRegex = identifierRe.replace("\\d", "\\d\\-"); + var jsxTag = { + onMatch : function(val, state, stack) { + var offset = val.charAt(1) == "/" ? 2 : 1; + if (offset == 1) { + if (state != this.nextState) + stack.unshift(this.next, this.nextState, 0); + else + stack.unshift(this.next); + stack[2]++; + } else if (offset == 2) { + if (state == this.nextState) { + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.shift(); + stack.shift(); + } + } + } + return [{ + type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", + value: val.slice(0, offset) + }, { + type: "meta.tag.tag-name.xml", + value: val.substr(offset) + }]; + }, + regex : "", + onMatch : function(value, currentState, stack) { + if (currentState == stack[0]) + stack.shift(); + if (value.length == 2) { + if (stack[0] == this.nextState) + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.splice(0, 2); + } + } + this.next = stack[0] || "start"; + return [{type: this.token, value: value}]; + }, + nextState: "jsx" + }, + jsxJsRule, + comments("jsxAttributes"), + { + token : "entity.other.attribute-name.xml", + regex : tagRegex + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + token : "text.tag-whitespace.xml", + regex : "\\s+" + }, { + token : "string.attribute-value.xml", + regex : "'", + stateName : "jsx_attr_q", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + stateName : "jsx_attr_qq", + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, + jsxTag + ]; + this.$rules.reference = [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }]; +} + +function comments(next) { + return [ + { + token : "comment", // multi line comment + regex : /\/\*/, + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "\\*\\/", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + }, { + token : "comment", + regex : "\\/\\/", + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "$|^", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + } + ]; +} +exports.JavaScriptHighlightRules = JavaScriptHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../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) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, 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, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = JavaScriptHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().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 == "no_regex") { + var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start" || endState == "no_regex") { + 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"], __webpack_require__(42), "JavaScriptWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(results) { + session.setAnnotations(results.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/javascript"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; + +var DocCommentHighlightRules = function() { + this.$rules = { + "start" : [ { + token : "comment.doc.tag", + regex : "@[\\w\\d_]+" // TODO: fix email addresses + }, + DocCommentHighlightRules.getTagRule(), + { + defaultToken : "comment.doc", + caseInsensitive: true + }] + }; +}; + +oop.inherits(DocCommentHighlightRules, TextHighlightRules); + +DocCommentHighlightRules.getTagRule = function(start) { + return { + token : "comment.doc.tag.storage.type", + regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" + }; +} + +DocCommentHighlightRules.getStartRule = function(start) { + return { + token : "comment.doc", // doc comment + regex : "\\/\\*(?=\\*)", + next : start + }; +}; + +DocCommentHighlightRules.getEndRule = function (start) { + return { + token : "comment.doc", // closing comment + regex : "\\*\\/", + next : start + }; +}; + + +exports.DocCommentHighlightRules = DocCommentHighlightRules; + +}); + +ace.define("ace/mode/netscript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; +var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; +var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; + +var NetscriptHighlightRules = function(options) { + var keywordMapper = this.createKeywordMapper({ + "variable.language": + "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors + "Namespace|QName|XML|XMLList|" + // E4X + "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors + "SyntaxError|TypeError|URIError|" + + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions + "isNaN|parseFloat|parseInt|" + + "hack|sleep|grow|weaken|print|tprint|scan|nuke|brutessh|ftpcrack|" + //Netscript functions + "relaysmtp|httpworm|sqlinject|run|exec|kill|killall|scp|ls|hasRootAccess|" + + "getIp|getHackingMultipliers|getBitNodeMultipliers|getStats|isBusy|" + + "getHostname|getHackingLevel|getServerMoneyAvailable|getServerMaxMoney|" + + "getServerGrowth|getServerSecurityLevel|getServerBaseSecurityLevel|" + + "getServerMinSecurityLevel|" + + "getServerRequiredHackingLevel|getServerNumPortsRequired|getServerRam|" + + "serverExists|fileExists|isRunning|getNextHacknetNodeCost|" + + "purchaseHacknetNode|deleteServer|getPurchasedServers|" + + "purchaseServer|round|write|read|scriptRunning|scriptKill|getScriptRam|" + + "getHackTime|getGrowTime|getWeakenTime|getScriptIncome|getScriptExpGain|" + + "getTimeSinceLastAug|" + + "universityCourse|" + + "gymWorkout|travelToCity|purchaseTor|purchaseProgram|upgradeHomeRam|" + + "getUpgradeHomeRamCost|workForCompany|applyToCompany|getCompanyRep|" + + "checkFactionInvitations|joinFaction|workForFaction|getFactionRep|" + + "createProgram|commitCrime|getCrimeChance|getOwnedAugmentations|" + + "getAugmentationsFromFaction|" + + "getAugmentationCost|purchaseAugmentation|" + + "installAugmentations|hacknetnodes|upgradeLevel|upgradeRam|upgradeCore|" + + "getLevelUpgradeCost|getRamUpgradeCost|getCoreUpgradeCost|" + + "getStockPrice|getStockPosition|buyStock|sellStock|" + + "JSON|Math|" + // Other + "this|arguments|prototype|window|document" , // Pseudo + "keyword": + "const|yield|import|get|set|async|await|" + + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + + "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + + "__parent__|__count__|escape|unescape|with|__proto__|" + + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", + "storage.type": + "const|let|var|function", + "constant.language": + "null|Infinity|NaN|undefined", + "support.function": + "alert", + "constant.language.boolean": "true|false" + }, "identifier"); + var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; + + var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex + "u[0-9a-fA-F]{4}|" + // unicode + "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode + "[0-2][0-7]{0,2}|" + // oct + "3[0-7][0-7]?|" + // oct + "[4-7][0-7]?|" + //oct + ".)"; + + this.$rules = { + "no_regex" : [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("no_regex"), + { + token : "string", + regex : "'(?=.)", + next : "qstring" + }, { + token : "string", + regex : '"(?=.)', + next : "qqstring" + }, { + token : "constant.numeric", // hex + regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ + }, { + token : "constant.numeric", // float + regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ + }, { + token : [ + "storage.type", "punctuation.operator", "support.function", + "punctuation.operator", "entity.name.function", "text","keyword.operator" + ], + regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", + next: "function_arguments" + }, { + 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" + }, { + token : [ + "entity.name.function", "text", "keyword.operator", "text", "storage.type", + "text", "paren.lparen" + ], + regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "entity.name.function", "text", "punctuation.operator", + "text", "storage.type", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : [ + "text", "text", "storage.type", "text", "paren.lparen" + ], + regex : "(:)(\\s*)(function)(\\s*)(\\()", + next: "function_arguments" + }, { + token : "keyword", + regex : "(?:" + kwBeforeRe + ")\\b", + next : "start" + }, { + token : ["support.constant"], + regex : /that\b/ + }, { + token : ["storage.type", "punctuation.operator", "support.function.firebug"], + regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ + }, { + token : keywordMapper, + regex : identifierRe + }, { + token : "punctuation.operator", + regex : /[.](?![.])/, + next : "property" + }, { + token : "keyword.operator", + regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, + next : "start" + }, { + token : "punctuation.operator", + regex : /[?:,;.]/, + next : "start" + }, { + token : "paren.lparen", + regex : /[\[({]/, + next : "start" + }, { + token : "paren.rparen", + regex : /[\])}]/ + }, { + token: "comment", + regex: /^#!.*$/ + } + ], + property: [{ + token : "text", + regex : "\\s+" + }, { + token : [ + "storage.type", "punctuation.operator", "entity.name.function", "text", + "keyword.operator", "text", + "storage.type", "text", "entity.name.function", "text", "paren.lparen" + ], + regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", + next: "function_arguments" + }, { + token : "punctuation.operator", + regex : /[.](?![.])/ + }, { + token : "support.function", + regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|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 : "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|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ + }, { + token : "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 : "identifier", + regex : identifierRe + }, { + regex: "", + token: "empty", + next: "no_regex" + } + ], + "start": [ + DocCommentHighlightRules.getStartRule("doc-start"), + comments("start"), + { + token: "string.regexp", + regex: "\\/", + next: "regex" + }, { + token : "text", + regex : "\\s+|^$", + next : "start" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "regex": [ + { + token: "regexp.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "string.regexp", + regex: "/[sxngimy]*", + next: "no_regex" + }, { + token : "invalid", + regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ + }, { + token : "constant.language.escape", + regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ + }, { + token : "constant.language.delimiter", + regex: /\|/ + }, { + token: "constant.language.escape", + regex: /\[\^?/, + next: "regex_character_class" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp" + } + ], + "regex_character_class": [ + { + token: "regexp.charclass.keyword.operator", + regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" + }, { + token: "constant.language.escape", + regex: "]", + next: "regex" + }, { + token: "constant.language.escape", + regex: "-" + }, { + token: "empty", + regex: "$", + next: "no_regex" + }, { + defaultToken: "string.regexp.charachterclass" + } + ], + "function_arguments": [ + { + token: "variable.parameter", + regex: identifierRe + }, { + token: "punctuation.operator", + regex: "[, ]+" + }, { + token: "punctuation.operator", + regex: "$" + }, { + token: "empty", + regex: "", + next: "no_regex" + } + ], + "qqstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qqstring" + }, { + token : "string", + regex : '"|$', + next : "no_regex" + }, { + defaultToken: "string" + } + ], + "qstring" : [ + { + token : "constant.language.escape", + regex : escapedRe + }, { + token : "string", + regex : "\\\\$", + next : "qstring" + }, { + token : "string", + regex : "'|$", + next : "no_regex" + }, { + defaultToken: "string" + } + ] + }; + + + if (!options || !options.noES6) { + this.$rules.no_regex.unshift({ + regex: "[{}]", onMatch: function(val, state, stack) { + this.next = val == "{" ? this.nextState : ""; + if (val == "{" && stack.length) { + stack.unshift("start", state); + } + else if (val == "}" && stack.length) { + stack.shift(); + this.next = stack.shift(); + if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) + return "paren.quasi.end"; + } + return val == "{" ? "paren.lparen" : "paren.rparen"; + }, + nextState: "start" + }, { + token : "string.quasi.start", + regex : /`/, + push : [{ + token : "constant.language.escape", + regex : escapedRe + }, { + token : "paren.quasi.start", + regex : /\${/, + push : "start" + }, { + token : "string.quasi.end", + regex : /`/, + next : "pop" + }, { + defaultToken: "string.quasi" + }] + }); + + if (!options || options.jsx != false) + JSX.call(this); + } + + this.embedRules(DocCommentHighlightRules, "doc-", + [ DocCommentHighlightRules.getEndRule("no_regex") ]); + + this.normalizeRules(); +}; + +oop.inherits(NetscriptHighlightRules, TextHighlightRules); + +function JSX() { + var tagRegex = identifierRe.replace("\\d", "\\d\\-"); + var jsxTag = { + onMatch : function(val, state, stack) { + var offset = val.charAt(1) == "/" ? 2 : 1; + if (offset == 1) { + if (state != this.nextState) + stack.unshift(this.next, this.nextState, 0); + else + stack.unshift(this.next); + stack[2]++; + } else if (offset == 2) { + if (state == this.nextState) { + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.shift(); + stack.shift(); + } + } + } + return [{ + type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", + value: val.slice(0, offset) + }, { + type: "meta.tag.tag-name.xml", + value: val.substr(offset) + }]; + }, + regex : "", + onMatch : function(value, currentState, stack) { + if (currentState == stack[0]) + stack.shift(); + if (value.length == 2) { + if (stack[0] == this.nextState) + stack[1]--; + if (!stack[1] || stack[1] < 0) { + stack.splice(0, 2); + } + } + this.next = stack[0] || "start"; + return [{type: this.token, value: value}]; + }, + nextState: "jsx" + }, + jsxJsRule, + comments("jsxAttributes"), + { + token : "entity.other.attribute-name.xml", + regex : tagRegex + }, { + token : "keyword.operator.attribute-equals.xml", + regex : "=" + }, { + token : "text.tag-whitespace.xml", + regex : "\\s+" + }, { + token : "string.attribute-value.xml", + regex : "'", + stateName : "jsx_attr_q", + push : [ + {token : "string.attribute-value.xml", regex: "'", next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, { + token : "string.attribute-value.xml", + regex : '"', + stateName : "jsx_attr_qq", + push : [ + {token : "string.attribute-value.xml", regex: '"', next: "pop"}, + {include : "reference"}, + {defaultToken : "string.attribute-value.xml"} + ] + }, + jsxTag + ]; + this.$rules.reference = [{ + token : "constant.language.escape.reference.xml", + regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" + }]; +} + +function comments(next) { + return [ + { + token : "comment", // multi line comment + regex : /\/\*/, + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "\\*\\/", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + }, { + token : "comment", + regex : "\\/\\/", + next: [ + DocCommentHighlightRules.getTagRule(), + {token : "comment", regex : "$|^", next : next || "pop"}, + {defaultToken : "comment", caseInsensitive: true} + ] + } + ]; +} +exports.NetscriptHighlightRules = NetscriptHighlightRules; +}); + +ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { +"use strict"; + +var Range = acequire("../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) { + return line.match(/^\s*/)[0]; + }; + +}).call(MatchingBraceOutdent.prototype); + +exports.MatchingBraceOutdent = MatchingBraceOutdent; +}); + +ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../../lib/oop"); +var Range = acequire("../../range").Range; +var BaseFoldMode = acequire("./fold_mode").FoldMode; + +var FoldMode = exports.FoldMode = function(commentRegex) { + if (commentRegex) { + this.foldingStartMarker = new RegExp( + this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) + ); + this.foldingStopMarker = new RegExp( + this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) + ); + } +}; +oop.inherits(FoldMode, BaseFoldMode); + +(function() { + + this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; + this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; + this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; + this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; + this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; + this._getFoldWidgetBase = this.getFoldWidget; + this.getFoldWidget = function(session, foldStyle, row) { + var line = session.getLine(row); + + if (this.singleLineBlockCommentRe.test(line)) { + if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) + return ""; + } + + var fw = this._getFoldWidgetBase(session, foldStyle, row); + + if (!fw && this.startRegionRe.test(line)) + return "start"; // lineCommentRegionStart + + return fw; + }; + + this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { + var line = session.getLine(row); + + if (this.startRegionRe.test(line)) + return this.getCommentRegionBlock(session, line, 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, 1); + + if (range && !range.isMultiLine()) { + if (forceMultiline) { + range = this.getSectionRange(session, row); + } else if (foldStyle != "all") + range = null; + } + + return range; + } + + if (foldStyle === "markbegin") + return; + + var match = line.match(this.foldingStopMarker); + if (match) { + var i = match.index + match[0].length; + + if (match[1]) + return this.closingBracketBlock(session, match[1], row, i); + + return session.getCommentFoldRange(row, i, -1); + } + }; + + this.getSectionRange = function(session, row) { + var line = session.getLine(row); + var startIndent = line.search(/\S/); + var startRow = row; + var startColumn = line.length; + row = row + 1; + var endRow = row; + var maxRow = session.getLength(); + while (++row < maxRow) { + line = session.getLine(row); + var indent = line.search(/\S/); + if (indent === -1) + continue; + if (startIndent > indent) + break; + var subRange = this.getFoldWidgetRange(session, "all", row); + + if (subRange) { + if (subRange.start.row <= startRow) { + break; + } else if (subRange.isMultiLine()) { + row = subRange.end.row; + } else if (startIndent == indent) { + break; + } + } + endRow = row; + } + + return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); + }; + this.getCommentRegionBlock = function(session, line, row) { + var startColumn = line.search(/\s*$/); + var maxRow = session.getLength(); + var startRow = row; + + var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; + var depth = 1; + while (++row < maxRow) { + line = session.getLine(row); + var m = re.exec(line); + if (!m) continue; + if (m[1]) depth--; + else depth++; + + if (!depth) break; + } + + var endRow = row; + if (endRow > startRow) { + return new Range(startRow, startColumn, endRow, line.length); + } + }; + +}).call(FoldMode.prototype); + +}); + +ace.define("ace/mode/netscript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/netscript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("../lib/oop"); +var TextMode = acequire("./text").Mode; +var NetscriptHighlightRules = acequire("./netscript_highlight_rules").NetscriptHighlightRules; +var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; +var WorkerClient = acequire("../worker/worker_client").WorkerClient; +var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; +var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; + +var Mode = function() { + this.HighlightRules = NetscriptHighlightRules; + + this.$outdent = new MatchingBraceOutdent(); + this.$behaviour = new CstyleBehaviour(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "//"; + this.blockComment = {start: "/*", end: "*/"}; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.getTokenizer().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 == "no_regex") { + var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); + if (match) { + indent += tab; + } + } else if (state == "doc-start") { + if (endState == "start" || endState == "no_regex") { + 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"], __webpack_require__(42), "JavaScriptWorker"); + worker.attachToDocument(session.getDocument()); + + worker.on("annotate", function(results) { + session.setAnnotations(results.data); + }); + + worker.on("terminate", function() { + session.clearAnnotations(); + }); + + return worker; + }; + + this.$id = "ace/mode/netscript"; +}).call(Mode.prototype); + +exports.Mode = Mode; +}); + + +/***/ }), +/* 57 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/chaos",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-chaos"; +exports.cssText = ".ace-chaos .ace_gutter {\ +background: #141414;\ +color: #595959;\ +border-right: 1px solid #282828;\ +}\ +.ace-chaos .ace_gutter-cell.ace_warning {\ +background-image: none;\ +background: #FC0;\ +border-left: none;\ +padding-left: 0;\ +color: #000;\ +}\ +.ace-chaos .ace_gutter-cell.ace_error {\ +background-position: -6px center;\ +background-image: none;\ +background: #F10;\ +border-left: none;\ +padding-left: 0;\ +color: #000;\ +}\ +.ace-chaos .ace_print-margin {\ +border-left: 1px solid #555;\ +right: 0;\ +background: #1D1D1D;\ +}\ +.ace-chaos {\ +background-color: #161616;\ +color: #E6E1DC;\ +}\ +.ace-chaos .ace_cursor {\ +border-left: 2px solid #FFFFFF;\ +}\ +.ace-chaos .ace_cursor.ace_overwrite {\ +border-left: 0px;\ +border-bottom: 1px solid #FFFFFF;\ +}\ +.ace-chaos .ace_marker-layer .ace_selection {\ +background: #494836;\ +}\ +.ace-chaos .ace_marker-layer .ace_step {\ +background: rgb(198, 219, 174);\ +}\ +.ace-chaos .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #FCE94F;\ +}\ +.ace-chaos .ace_marker-layer .ace_active-line {\ +background: #333;\ +}\ +.ace-chaos .ace_gutter-active-line {\ +background-color: #222;\ +}\ +.ace-chaos .ace_invisible {\ +color: #404040;\ +}\ +.ace-chaos .ace_keyword {\ +color:#00698F;\ +}\ +.ace-chaos .ace_keyword.ace_operator {\ +color:#FF308F;\ +}\ +.ace-chaos .ace_constant {\ +color:#1EDAFB;\ +}\ +.ace-chaos .ace_constant.ace_language {\ +color:#FDC251;\ +}\ +.ace-chaos .ace_constant.ace_library {\ +color:#8DFF0A;\ +}\ +.ace-chaos .ace_constant.ace_numeric {\ +color:#58C554;\ +}\ +.ace-chaos .ace_invalid {\ +color:#FFFFFF;\ +background-color:#990000;\ +}\ +.ace-chaos .ace_invalid.ace_deprecated {\ +color:#FFFFFF;\ +background-color:#990000;\ +}\ +.ace-chaos .ace_support {\ +color: #999;\ +}\ +.ace-chaos .ace_support.ace_function {\ +color:#00AEEF;\ +}\ +.ace-chaos .ace_function {\ +color:#00AEEF;\ +}\ +.ace-chaos .ace_string {\ +color:#58C554;\ +}\ +.ace-chaos .ace_comment {\ +color:#555;\ +font-style:italic;\ +padding-bottom: 0px;\ +}\ +.ace-chaos .ace_variable {\ +color:#997744;\ +}\ +.ace-chaos .ace_meta.ace_tag {\ +color:#BE53E6;\ +}\ +.ace-chaos .ace_entity.ace_other.ace_attribute-name {\ +color:#FFFF89;\ +}\ +.ace-chaos .ace_markup.ace_underline {\ +text-decoration: underline;\ +}\ +.ace-chaos .ace_fold-widget {\ +text-align: center;\ +}\ +.ace-chaos .ace_fold-widget:hover {\ +color: #777;\ +}\ +.ace-chaos .ace_fold-widget.ace_start,\ +.ace-chaos .ace_fold-widget.ace_end,\ +.ace-chaos .ace_fold-widget.ace_closed{\ +background: none;\ +border: none;\ +box-shadow: none;\ +}\ +.ace-chaos .ace_fold-widget.ace_start:after {\ +content: '▾'\ +}\ +.ace-chaos .ace_fold-widget.ace_end:after {\ +content: '▴'\ +}\ +.ace-chaos .ace_fold-widget.ace_closed:after {\ +content: '‣'\ +}\ +.ace-chaos .ace_indent-guide {\ +border-right:1px dotted #333;\ +margin-right:-1px;\ +}\ +.ace-chaos .ace_fold { \ +background: #222; \ +border-radius: 3px; \ +color: #7AF; \ +border: none; \ +}\ +.ace-chaos .ace_fold:hover {\ +background: #CCC; \ +color: #000;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); + +}); + + +/***/ }), +/* 58 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/chrome",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-chrome"; +exports.cssText = ".ace-chrome .ace_gutter {\ +background: #ebebeb;\ +color: #333;\ +overflow : hidden;\ +}\ +.ace-chrome .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8;\ +}\ +.ace-chrome {\ +background-color: #FFFFFF;\ +color: black;\ +}\ +.ace-chrome .ace_cursor {\ +color: black;\ +}\ +.ace-chrome .ace_invisible {\ +color: rgb(191, 191, 191);\ +}\ +.ace-chrome .ace_constant.ace_buildin {\ +color: rgb(88, 72, 246);\ +}\ +.ace-chrome .ace_constant.ace_language {\ +color: rgb(88, 92, 246);\ +}\ +.ace-chrome .ace_constant.ace_library {\ +color: rgb(6, 150, 14);\ +}\ +.ace-chrome .ace_invalid {\ +background-color: rgb(153, 0, 0);\ +color: white;\ +}\ +.ace-chrome .ace_fold {\ +}\ +.ace-chrome .ace_support.ace_function {\ +color: rgb(60, 76, 114);\ +}\ +.ace-chrome .ace_support.ace_constant {\ +color: rgb(6, 150, 14);\ +}\ +.ace-chrome .ace_support.ace_type,\ +.ace-chrome .ace_support.ace_class\ +.ace-chrome .ace_support.ace_other {\ +color: rgb(109, 121, 222);\ +}\ +.ace-chrome .ace_variable.ace_parameter {\ +font-style:italic;\ +color:#FD971F;\ +}\ +.ace-chrome .ace_keyword.ace_operator {\ +color: rgb(104, 118, 135);\ +}\ +.ace-chrome .ace_comment {\ +color: #236e24;\ +}\ +.ace-chrome .ace_comment.ace_doc {\ +color: #236e24;\ +}\ +.ace-chrome .ace_comment.ace_doc.ace_tag {\ +color: #236e24;\ +}\ +.ace-chrome .ace_constant.ace_numeric {\ +color: rgb(0, 0, 205);\ +}\ +.ace-chrome .ace_variable {\ +color: rgb(49, 132, 149);\ +}\ +.ace-chrome .ace_xml-pe {\ +color: rgb(104, 104, 91);\ +}\ +.ace-chrome .ace_entity.ace_name.ace_function {\ +color: #0000A2;\ +}\ +.ace-chrome .ace_heading {\ +color: rgb(12, 7, 255);\ +}\ +.ace-chrome .ace_list {\ +color:rgb(185, 6, 144);\ +}\ +.ace-chrome .ace_marker-layer .ace_selection {\ +background: rgb(181, 213, 255);\ +}\ +.ace-chrome .ace_marker-layer .ace_step {\ +background: rgb(252, 255, 0);\ +}\ +.ace-chrome .ace_marker-layer .ace_stack {\ +background: rgb(164, 229, 101);\ +}\ +.ace-chrome .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgb(192, 192, 192);\ +}\ +.ace-chrome .ace_marker-layer .ace_active-line {\ +background: rgba(0, 0, 0, 0.07);\ +}\ +.ace-chrome .ace_gutter-active-line {\ +background-color : #dcdcdc;\ +}\ +.ace-chrome .ace_marker-layer .ace_selected-word {\ +background: rgb(250, 250, 255);\ +border: 1px solid rgb(200, 200, 250);\ +}\ +.ace-chrome .ace_storage,\ +.ace-chrome .ace_keyword,\ +.ace-chrome .ace_meta.ace_tag {\ +color: rgb(147, 15, 128);\ +}\ +.ace-chrome .ace_string.ace_regex {\ +color: rgb(255, 0, 0)\ +}\ +.ace-chrome .ace_string {\ +color: #1A1AA6;\ +}\ +.ace-chrome .ace_entity.ace_other.ace_attribute-name {\ +color: #994409;\ +}\ +.ace-chrome .ace_indent-guide {\ +background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + + +/***/ }), +/* 59 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/monokai",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-monokai"; +exports.cssText = ".ace-monokai .ace_gutter {\ +background: #2F3129;\ +color: #8F908A\ +}\ +.ace-monokai .ace_print-margin {\ +width: 1px;\ +background: #555651\ +}\ +.ace-monokai {\ +background-color: #272822;\ +color: #F8F8F2\ +}\ +.ace-monokai .ace_cursor {\ +color: #F8F8F0\ +}\ +.ace-monokai .ace_marker-layer .ace_selection {\ +background: #49483E\ +}\ +.ace-monokai.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #272822;\ +}\ +.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: #202020\ +}\ +.ace-monokai .ace_gutter-active-line {\ +background-color: #272727\ +}\ +.ace-monokai .ace_marker-layer .ace_selected-word {\ +border: 1px solid #49483E\ +}\ +.ace-monokai .ace_invisible {\ +color: #52524d\ +}\ +.ace-monokai .ace_entity.ace_name.ace_tag,\ +.ace-monokai .ace_keyword,\ +.ace-monokai .ace_meta.ace_tag,\ +.ace-monokai .ace_storage {\ +color: #F92672\ +}\ +.ace-monokai .ace_punctuation,\ +.ace-monokai .ace_punctuation.ace_tag {\ +color: #fff\ +}\ +.ace-monokai .ace_constant.ace_character,\ +.ace-monokai .ace_constant.ace_language,\ +.ace-monokai .ace_constant.ace_numeric,\ +.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,\ +.ace-monokai .ace_support.ace_function {\ +color: #66D9EF\ +}\ +.ace-monokai .ace_fold {\ +background-color: #A6E22E;\ +border-color: #F8F8F2\ +}\ +.ace-monokai .ace_storage.ace_type,\ +.ace-monokai .ace_support.ace_class,\ +.ace-monokai .ace_support.ace_type {\ +font-style: italic;\ +color: #66D9EF\ +}\ +.ace-monokai .ace_entity.ace_name.ace_function,\ +.ace-monokai .ace_entity.ace_other,\ +.ace-monokai .ace_entity.ace_other.ace_attribute-name,\ +.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_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + + +/***/ }), +/* 60 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/solarized_dark",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-solarized-dark"; +exports.cssText = ".ace-solarized-dark .ace_gutter {\ +background: #01313f;\ +color: #d0edf7\ +}\ +.ace-solarized-dark .ace_print-margin {\ +width: 1px;\ +background: #33555E\ +}\ +.ace-solarized-dark {\ +background-color: #002B36;\ +color: #93A1A1\ +}\ +.ace-solarized-dark .ace_entity.ace_other.ace_attribute-name,\ +.ace-solarized-dark .ace_storage {\ +color: #93A1A1\ +}\ +.ace-solarized-dark .ace_cursor,\ +.ace-solarized-dark .ace_string.ace_regexp {\ +color: #D30102\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_active-line,\ +.ace-solarized-dark .ace_marker-layer .ace_selection {\ +background: rgba(255, 255, 255, 0.1)\ +}\ +.ace-solarized-dark.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #002B36;\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_step {\ +background: rgb(102, 82, 0)\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-dark .ace_gutter-active-line {\ +background-color: #0d3440\ +}\ +.ace-solarized-dark .ace_marker-layer .ace_selected-word {\ +border: 1px solid #073642\ +}\ +.ace-solarized-dark .ace_invisible {\ +color: rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-dark .ace_keyword,\ +.ace-solarized-dark .ace_meta,\ +.ace-solarized-dark .ace_support.ace_class,\ +.ace-solarized-dark .ace_support.ace_type {\ +color: #859900\ +}\ +.ace-solarized-dark .ace_constant.ace_character,\ +.ace-solarized-dark .ace_constant.ace_other {\ +color: #CB4B16\ +}\ +.ace-solarized-dark .ace_constant.ace_language {\ +color: #B58900\ +}\ +.ace-solarized-dark .ace_constant.ace_numeric {\ +color: #D33682\ +}\ +.ace-solarized-dark .ace_fold {\ +background-color: #268BD2;\ +border-color: #93A1A1\ +}\ +.ace-solarized-dark .ace_entity.ace_name.ace_function,\ +.ace-solarized-dark .ace_entity.ace_name.ace_tag,\ +.ace-solarized-dark .ace_support.ace_function,\ +.ace-solarized-dark .ace_variable,\ +.ace-solarized-dark .ace_variable.ace_language {\ +color: #268BD2\ +}\ +.ace-solarized-dark .ace_string {\ +color: #2AA198\ +}\ +.ace-solarized-dark .ace_comment {\ +font-style: italic;\ +color: #657B83\ +}\ +.ace-solarized-dark .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNg0Db1ZVCxc/sPAAd4AlUHlLenAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + + +/***/ }), +/* 61 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/solarized_light",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-solarized-light"; +exports.cssText = ".ace-solarized-light .ace_gutter {\ +background: #fbf1d3;\ +color: #333\ +}\ +.ace-solarized-light .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8\ +}\ +.ace-solarized-light {\ +background-color: #FDF6E3;\ +color: #586E75\ +}\ +.ace-solarized-light .ace_cursor {\ +color: #000000\ +}\ +.ace-solarized-light .ace_marker-layer .ace_selection {\ +background: rgba(7, 54, 67, 0.09)\ +}\ +.ace-solarized-light.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #FDF6E3;\ +}\ +.ace-solarized-light .ace_marker-layer .ace_step {\ +background: rgb(255, 255, 0)\ +}\ +.ace-solarized-light .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-light .ace_marker-layer .ace_active-line {\ +background: #EEE8D5\ +}\ +.ace-solarized-light .ace_gutter-active-line {\ +background-color : #EDE5C1\ +}\ +.ace-solarized-light .ace_marker-layer .ace_selected-word {\ +border: 1px solid #073642\ +}\ +.ace-solarized-light .ace_invisible {\ +color: rgba(147, 161, 161, 0.50)\ +}\ +.ace-solarized-light .ace_keyword,\ +.ace-solarized-light .ace_meta,\ +.ace-solarized-light .ace_support.ace_class,\ +.ace-solarized-light .ace_support.ace_type {\ +color: #859900\ +}\ +.ace-solarized-light .ace_constant.ace_character,\ +.ace-solarized-light .ace_constant.ace_other {\ +color: #CB4B16\ +}\ +.ace-solarized-light .ace_constant.ace_language {\ +color: #B58900\ +}\ +.ace-solarized-light .ace_constant.ace_numeric {\ +color: #D33682\ +}\ +.ace-solarized-light .ace_fold {\ +background-color: #268BD2;\ +border-color: #586E75\ +}\ +.ace-solarized-light .ace_entity.ace_name.ace_function,\ +.ace-solarized-light .ace_entity.ace_name.ace_tag,\ +.ace-solarized-light .ace_support.ace_function,\ +.ace-solarized-light .ace_variable,\ +.ace-solarized-light .ace_variable.ace_language {\ +color: #268BD2\ +}\ +.ace-solarized-light .ace_storage {\ +color: #073642\ +}\ +.ace-solarized-light .ace_string {\ +color: #2AA198\ +}\ +.ace-solarized-light .ace_string.ace_regexp {\ +color: #D30102\ +}\ +.ace-solarized-light .ace_comment,\ +.ace-solarized-light .ace_entity.ace_other.ace_attribute-name {\ +color: #93A1A1\ +}\ +.ace-solarized-light .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYHjy8NJ/AAjgA5fzQUmBAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + + +/***/ }), +/* 62 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/terminal",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-terminal-theme"; +exports.cssText = ".ace-terminal-theme .ace_gutter {\ +background: #1a0005;\ +color: steelblue\ +}\ +.ace-terminal-theme .ace_print-margin {\ +width: 1px;\ +background: #1a1a1a\ +}\ +.ace-terminal-theme {\ +background-color: black;\ +color: #DEDEDE\ +}\ +.ace-terminal-theme .ace_cursor {\ +color: #9F9F9F\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_selection {\ +background: #424242\ +}\ +.ace-terminal-theme.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px black;\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_step {\ +background: rgb(0, 0, 0)\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_bracket {\ +background: #090;\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_bracket-start {\ +background: #090;\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_bracket-unmatched {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #900\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_active-line {\ +background: #2A2A2A\ +}\ +.ace-terminal-theme .ace_gutter-active-line {\ +background-color: #2A112A\ +}\ +.ace-terminal-theme .ace_marker-layer .ace_selected-word {\ +border: 1px solid #424242\ +}\ +.ace-terminal-theme .ace_invisible {\ +color: #343434\ +}\ +.ace-terminal-theme .ace_keyword,\ +.ace-terminal-theme .ace_meta,\ +.ace-terminal-theme .ace_storage,\ +.ace-terminal-theme .ace_storage.ace_type,\ +.ace-terminal-theme .ace_support.ace_type {\ +color: tomato\ +}\ +.ace-terminal-theme .ace_keyword.ace_operator {\ +color: deeppink\ +}\ +.ace-terminal-theme .ace_constant.ace_character,\ +.ace-terminal-theme .ace_constant.ace_language,\ +.ace-terminal-theme .ace_constant.ace_numeric,\ +.ace-terminal-theme .ace_keyword.ace_other.ace_unit,\ +.ace-terminal-theme .ace_support.ace_constant,\ +.ace-terminal-theme .ace_variable.ace_parameter {\ +color: #E78C45\ +}\ +.ace-terminal-theme .ace_constant.ace_other {\ +color: gold\ +}\ +.ace-terminal-theme .ace_invalid {\ +color: yellow;\ +background-color: red\ +}\ +.ace-terminal-theme .ace_invalid.ace_deprecated {\ +color: #CED2CF;\ +background-color: #B798BF\ +}\ +.ace-terminal-theme .ace_fold {\ +background-color: #7AA6DA;\ +border-color: #DEDEDE\ +}\ +.ace-terminal-theme .ace_entity.ace_name.ace_function,\ +.ace-terminal-theme .ace_support.ace_function,\ +.ace-terminal-theme .ace_variable {\ +color: #7AA6DA\ +}\ +.ace-terminal-theme .ace_support.ace_class,\ +.ace-terminal-theme .ace_support.ace_type {\ +color: #E7C547\ +}\ +.ace-terminal-theme .ace_heading,\ +.ace-terminal-theme .ace_string {\ +color: #B9CA4A\ +}\ +.ace-terminal-theme .ace_entity.ace_name.ace_tag,\ +.ace-terminal-theme .ace_entity.ace_other.ace_attribute-name,\ +.ace-terminal-theme .ace_meta.ace_tag,\ +.ace-terminal-theme .ace_string.ace_regexp,\ +.ace-terminal-theme .ace_variable {\ +color: #D54E53\ +}\ +.ace-terminal-theme .ace_comment {\ +color: orangered\ +}\ +.ace-terminal-theme .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYLBWV/8PAAK4AYnhiq+xAAAAAElFTkSuQmCC) right repeat-y;\ +}\ +"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + + +/***/ }), +/* 63 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/twilight",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = true; +exports.cssClass = "ace-twilight"; +exports.cssText = ".ace-twilight .ace_gutter {\ +background: #232323;\ +color: #E2E2E2\ +}\ +.ace-twilight .ace_print-margin {\ +width: 1px;\ +background: #232323\ +}\ +.ace-twilight {\ +background-color: #141414;\ +color: #F8F8F8\ +}\ +.ace-twilight .ace_cursor {\ +color: #A7A7A7\ +}\ +.ace-twilight .ace_marker-layer .ace_selection {\ +background: rgba(221, 240, 255, 0.20)\ +}\ +.ace-twilight.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #141414;\ +}\ +.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: rgba(255, 255, 255, 0.031)\ +}\ +.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_character,\ +.ace-twilight .ace_constant.ace_character.ace_escape,\ +.ace-twilight .ace_constant.ace_other,\ +.ace-twilight .ace_heading,\ +.ace-twilight .ace_markup.ace_heading,\ +.ace-twilight .ace_support.ace_constant {\ +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_fold {\ +background-color: #AC885B;\ +border-color: #F8F8F8\ +}\ +.ace-twilight .ace_support.ace_function {\ +color: #DAD085\ +}\ +.ace-twilight .ace_list,\ +.ace-twilight .ace_markup.ace_list,\ +.ace-twilight .ace_storage {\ +color: #F9EE98\ +}\ +.ace-twilight .ace_entity.ace_name.ace_function,\ +.ace-twilight .ace_meta.ace_tag,\ +.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_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWMQERFpYLC1tf0PAAgOAnPnhxyiAAAAAElFTkSuQmCC) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + + +/***/ }), +/* 64 */ +/***/ (function(module, exports) { + +ace.define("ace/theme/xcode",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { + +exports.isDark = false; +exports.cssClass = "ace-xcode"; +exports.cssText = "\ +.ace-xcode .ace_gutter {\ +background: #e8e8e8;\ +color: #333\ +}\ +.ace-xcode .ace_print-margin {\ +width: 1px;\ +background: #e8e8e8\ +}\ +.ace-xcode {\ +background-color: #FFFFFF;\ +color: #000000\ +}\ +.ace-xcode .ace_cursor {\ +color: #000000\ +}\ +.ace-xcode .ace_marker-layer .ace_selection {\ +background: #B5D5FF\ +}\ +.ace-xcode.ace_multiselect .ace_selection.ace_start {\ +box-shadow: 0 0 3px 0px #FFFFFF;\ +}\ +.ace-xcode .ace_marker-layer .ace_step {\ +background: rgb(198, 219, 174)\ +}\ +.ace-xcode .ace_marker-layer .ace_bracket {\ +margin: -1px 0 0 -1px;\ +border: 1px solid #BFBFBF\ +}\ +.ace-xcode .ace_marker-layer .ace_active-line {\ +background: rgba(0, 0, 0, 0.071)\ +}\ +.ace-xcode .ace_gutter-active-line {\ +background-color: rgba(0, 0, 0, 0.071)\ +}\ +.ace-xcode .ace_marker-layer .ace_selected-word {\ +border: 1px solid #B5D5FF\ +}\ +.ace-xcode .ace_constant.ace_language,\ +.ace-xcode .ace_keyword,\ +.ace-xcode .ace_meta,\ +.ace-xcode .ace_variable.ace_language {\ +color: #C800A4\ +}\ +.ace-xcode .ace_invisible {\ +color: #BFBFBF\ +}\ +.ace-xcode .ace_constant.ace_character,\ +.ace-xcode .ace_constant.ace_other {\ +color: #275A5E\ +}\ +.ace-xcode .ace_constant.ace_numeric {\ +color: #3A00DC\ +}\ +.ace-xcode .ace_entity.ace_other.ace_attribute-name,\ +.ace-xcode .ace_support.ace_constant,\ +.ace-xcode .ace_support.ace_function {\ +color: #450084\ +}\ +.ace-xcode .ace_fold {\ +background-color: #C800A4;\ +border-color: #000000\ +}\ +.ace-xcode .ace_entity.ace_name.ace_tag,\ +.ace-xcode .ace_support.ace_class,\ +.ace-xcode .ace_support.ace_type {\ +color: #790EAD\ +}\ +.ace-xcode .ace_storage {\ +color: #C900A4\ +}\ +.ace-xcode .ace_string {\ +color: #DF0002\ +}\ +.ace-xcode .ace_comment {\ +color: #008E00\ +}\ +.ace-xcode .ace_indent-guide {\ +background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==) right repeat-y\ +}"; + +var dom = acequire("../lib/dom"); +dom.importCssString(exports.cssText, exports.cssClass); +}); + + +/***/ }), +/* 65 */ +/***/ (function(module, exports) { + +ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"], function(acequire, exports, module) { + 'use strict'; + + function log() { + var d = ""; + function format(p) { + if (typeof p != "object") + return p + ""; + if ("line" in p) { + return p.line + ":" + p.ch; + } + if ("anchor" in p) { + return format(p.anchor) + "->" + format(p.head); + } + if (Array.isArray(p)) + return "[" + p.map(function(x) { + return format(x); + }) + "]"; + return JSON.stringify(p); + } + for (var i = 0; i < arguments.length; i++) { + var p = arguments[i]; + var f = format(p); + d += f + " "; + } + console.log(d); + } + var Range = acequire("../range").Range; + var EventEmitter = acequire("../lib/event_emitter").EventEmitter; + var dom = acequire("../lib/dom"); + var oop = acequire("../lib/oop"); + var KEYS = acequire("../lib/keys"); + var event = acequire("../lib/event"); + var Search = acequire("../search").Search; + var useragent = acequire("../lib/useragent"); + var SearchHighlight = acequire("../search_highlight").SearchHighlight; + var multiSelectCommands = acequire("../commands/multi_select_commands"); + var TextModeTokenRe = acequire("../mode/text").Mode.prototype.tokenRe; + acequire("../multi_select"); + + var CodeMirror = function(ace) { + this.ace = ace; + this.state = {}; + this.marks = {}; + this.$uid = 0; + this.onChange = this.onChange.bind(this); + this.onSelectionChange = this.onSelectionChange.bind(this); + this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this); + this.ace.on('change', this.onChange); + this.ace.on('changeSelection', this.onSelectionChange); + this.ace.on('beforeEndOperation', this.onBeforeEndOperation); + }; + CodeMirror.Pos = function(line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; + }; + CodeMirror.defineOption = function(name, val, setter) {}; + CodeMirror.commands = { + redo: function(cm) { cm.ace.redo(); }, + undo: function(cm) { cm.ace.undo(); }, + newlineAndIndent: function(cm) { cm.ace.insert("\n"); } + }; + CodeMirror.keyMap = {}; + CodeMirror.addClass = CodeMirror.rmClass = + CodeMirror.e_stop = function() {}; + CodeMirror.keyName = function(e) { + if (e.key) return e.key; + var key = (KEYS[e.keyCode] || ""); + if (key.length == 1) key = key.toUpperCase(); + key = event.getModifierString(e).replace(/(^|-)\w/g, function(m) { + return m.toUpperCase(); + }) + key; + return key; + }; + CodeMirror.keyMap['default'] = function(key) { + return function(cm) { + var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()]; + return cmd && cm.ace.execCommand(cmd) !== false; + }; + }; + CodeMirror.lookupKey = function lookupKey(key, map, handle) { + if (typeof map == "string") + map = CodeMirror.keyMap[map]; + var found = typeof map == "function" ? map(key) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (!Array.isArray(map.fallthrough)) + return lookupKey(key, map.fallthrough, handle); + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle); + if (result) return result; + } + } + }; + + CodeMirror.signal = function(o, name, e) { return o._signal(name, e) }; + CodeMirror.on = event.addListener; + CodeMirror.off = event.removeListener; + CodeMirror.isWordChar = function(ch) { + if (ch < "\x7f") return /^\w$/.test(ch); + TextModeTokenRe.lastIndex = 0; + return TextModeTokenRe.test(ch); + }; + +(function() { + oop.implement(CodeMirror.prototype, EventEmitter); + + this.destroy = function() { + this.ace.off('change', this.onChange); + this.ace.off('changeSelection', this.onSelectionChange); + this.ace.off('beforeEndOperation', this.onBeforeEndOperation); + this.removeOverlay(); + }; + this.virtualSelectionMode = function() { + return this.ace.inVirtualSelectionMode && this.ace.selection.index; + }; + this.onChange = function(delta) { + var change = { text: delta.action[0] == 'i' ? delta.lines : [] }; + var curOp = this.curOp = this.curOp || {}; + if (!curOp.changeHandlers) + curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice(); + if (this.virtualSelectionMode()) return; + if (!curOp.lastChange) { + curOp.lastChange = curOp.change = change; + } else { + curOp.lastChange.next = curOp.lastChange = change; + } + this.$updateMarkers(delta); + }; + this.onSelectionChange = function() { + var curOp = this.curOp = this.curOp || {}; + if (!curOp.cursorActivityHandlers) + curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice(); + this.curOp.cursorActivity = true; + if (this.ace.inMultiSelectMode) { + this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler); + } + }; + this.operation = function(fn, force) { + if (!force && this.curOp || force && this.curOp && this.curOp.force) { + return fn(); + } + if (force || !this.ace.curOp) { + if (this.curOp) + this.onBeforeEndOperation(); + } + if (!this.ace.curOp) { + var prevOp = this.ace.prevOp; + this.ace.startOperation({ + command: { name: "vim", scrollIntoView: "cursor" } + }); + } + var curOp = this.curOp = this.curOp || {}; + this.curOp.force = force; + var result = fn(); + if (this.ace.curOp && this.ace.curOp.command.name == "vim") { + this.ace.endOperation(); + if (!curOp.cursorActivity && !curOp.lastChange && prevOp) + this.ace.prevOp = prevOp; + } + if (force || !this.ace.curOp) { + if (this.curOp) + this.onBeforeEndOperation(); + } + return result; + }; + this.onBeforeEndOperation = function() { + var op = this.curOp; + if (op) { + if (op.change) { this.signal("change", op.change, op); } + if (op && op.cursorActivity) { this.signal("cursorActivity", null, op); } + this.curOp = null; + } + }; + + this.signal = function(eventName, e, handlers) { + var listeners = handlers ? handlers[eventName + "Handlers"] + : (this._eventRegistry || {})[eventName]; + if (!listeners) + return; + listeners = listeners.slice(); + for (var i=0; i 0) { + point.row += rowShift; + point.column += point.row == end.row ? colShift : 0; + continue; + } + if (!isInsert && cmp2 <= 0) { + point.row = start.row; + point.column = start.column; + if (cmp2 === 0) + point.bias = 1; + } + } + }; + var Marker = function(cm, id, row, column) { + this.cm = cm; + this.id = id; + this.row = row; + this.column = column; + cm.marks[this.id] = this; + }; + Marker.prototype.clear = function() { delete this.cm.marks[this.id] }; + Marker.prototype.find = function() { return toCmPos(this) }; + this.setBookmark = function(cursor, options) { + var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch); + if (!options || !options.insertLeft) + bm.$insertRight = true; + this.marks[bm.id] = bm; + return bm; + }; + this.moveH = function(increment, unit) { + if (unit == 'char') { + var sel = this.ace.selection; + sel.clearSelection(); + sel.moveCursorBy(0, increment); + } + }; + this.findPosV = function(start, amount, unit, goalColumn) { + if (unit == 'page') { + var renderer = this.ace.renderer; + var config = renderer.layerConfig; + amount = amount * Math.floor(config.height / config.lineHeight); + unit = 'line'; + } + if (unit == 'line') { + var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch); + if (goalColumn != null) + screenPos.column = goalColumn; + screenPos.row += amount; + screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1); + var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column); + return toCmPos(pos); + } else { + debugger; + } + }; + this.charCoords = function(pos, mode) { + if (mode == 'div' || !mode) { + var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); + return {left: sc.column, top: sc.row}; + }if (mode == 'local') { + var renderer = this.ace.renderer; + var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); + var lh = renderer.layerConfig.lineHeight; + var cw = renderer.layerConfig.characterWidth; + var top = lh * sc.row; + return {left: sc.column * cw, top: top, bottom: top + lh}; + } + }; + this.coordsChar = function(pos, mode) { + var renderer = this.ace.renderer; + if (mode == 'local') { + var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight)); + var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth)); + var ch = renderer.session.screenToDocumentPosition(row, col); + return toCmPos(ch); + } else if (mode == 'div') { + throw "not implemented"; + } + }; + this.getSearchCursor = function(query, pos, caseFold) { + var caseSensitive = false; + var isRegexp = false; + if (query instanceof RegExp && !query.global) { + caseSensitive = !query.ignoreCase; + query = query.source; + isRegexp = true; + } + var search = new Search(); + if (pos.ch == undefined) pos.ch = Number.MAX_VALUE; + var acePos = {row: pos.line, column: pos.ch}; + var cm = this; + var last = null; + return { + findNext: function() { return this.find(false) }, + findPrevious: function() {return this.find(true) }, + find: function(back) { + search.setOptions({ + needle: query, + caseSensitive: caseSensitive, + wrap: false, + backwards: back, + regExp: isRegexp, + start: last || acePos + }); + var range = search.find(cm.ace.session); + if (range && range.isEmpty()) { + if (cm.getLine(range.start.row).length == range.start.column) { + search.$options.start = range; + range = search.find(cm.ace.session); + } + } + last = range; + return last; + }, + from: function() { return last && toCmPos(last.start) }, + to: function() { return last && toCmPos(last.end) }, + replace: function(text) { + if (last) { + last.end = cm.ace.session.doc.replace(last, text); + } + } + }; + }; + this.scrollTo = function(x, y) { + var renderer = this.ace.renderer; + var config = renderer.layerConfig; + var maxHeight = config.maxHeight; + maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd; + if (y != null) this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight))); + if (x != null) this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width))); + }; + this.scrollInfo = function() { return 0; }; + this.scrollIntoView = function(pos, margin) { + if (pos) { + var renderer = this.ace.renderer; + var viewMargin = { "top": 0, "bottom": margin }; + renderer.scrollCursorIntoView(toAcePos(pos), + (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin); + } + }; + this.getLine = function(row) { return this.ace.session.getLine(row) }; + this.getRange = function(s, e) { + return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch)); + }; + this.replaceRange = function(text, s, e) { + if (!e) e = s; + return this.ace.session.replace(new Range(s.line, s.ch, e.line, e.ch), text); + }; + this.replaceSelections = function(p) { + var sel = this.ace.selection; + if (this.ace.inVirtualSelectionMode) { + this.ace.session.replace(sel.getRange(), p[0] || ""); + return; + } + sel.inVirtualSelectionMode = true; + var ranges = sel.rangeList.ranges; + if (!ranges.length) ranges = [this.ace.multiSelect.getRange()]; + for (var i = ranges.length; i--;) + this.ace.session.replace(ranges[i], p[i] || ""); + sel.inVirtualSelectionMode = false; + }; + this.getSelection = function() { + return this.ace.getSelectedText(); + }; + this.getSelections = function() { + return this.listSelections().map(function(x) { + return this.getRange(x.anchor, x.head); + }, this); + }; + this.getInputField = function() { + return this.ace.textInput.getElement(); + }; + this.getWrapperElement = function() { + return this.ace.containter; + }; + var optMap = { + indentWithTabs: "useSoftTabs", + indentUnit: "tabSize", + tabSize: "tabSize", + firstLineNumber: "firstLineNumber", + readOnly: "readOnly" + }; + this.setOption = function(name, val) { + this.state[name] = val; + switch (name) { + case 'indentWithTabs': + name = optMap[name]; + val = !val; + break; + default: + name = optMap[name]; + } + if (name) + this.ace.setOption(name, val); + }; + this.getOption = function(name, val) { + var aceOpt = optMap[name]; + if (aceOpt) + val = this.ace.getOption(aceOpt); + switch (name) { + case 'indentWithTabs': + name = optMap[name]; + return !val; + } + return aceOpt ? val : this.state[name]; + }; + this.toggleOverwrite = function(on) { + this.state.overwrite = on; + return this.ace.setOverwrite(on); + }; + this.addOverlay = function(o) { + if (!this.$searchHighlight || !this.$searchHighlight.session) { + var highlight = new SearchHighlight(null, "ace_highlight-marker", "text"); + var marker = this.ace.session.addDynamicMarker(highlight); + highlight.id = marker.id; + highlight.session = this.ace.session; + highlight.destroy = function(o) { + highlight.session.off("change", highlight.updateOnChange); + highlight.session.off("changeEditor", highlight.destroy); + highlight.session.removeMarker(highlight.id); + highlight.session = null; + }; + highlight.updateOnChange = function(delta) { + var row = delta.start.row; + if (row == delta.end.row) highlight.cache[row] = undefined; + else highlight.cache.splice(row, highlight.cache.length); + }; + highlight.session.on("changeEditor", highlight.destroy); + highlight.session.on("change", highlight.updateOnChange); + } + var re = new RegExp(o.query.source, "gmi"); + this.$searchHighlight = o.highlight = highlight; + this.$searchHighlight.setRegexp(re); + this.ace.renderer.updateBackMarkers(); + }; + this.removeOverlay = function(o) { + if (this.$searchHighlight && this.$searchHighlight.session) { + this.$searchHighlight.destroy(); + } + }; + this.getScrollInfo = function() { + var renderer = this.ace.renderer; + var config = renderer.layerConfig; + return { + left: renderer.scrollLeft, + top: renderer.scrollTop, + height: config.maxHeight, + width: config.width, + clientHeight: config.height, + clientWidth: config.width + }; + }; + this.getValue = function() { + return this.ace.getValue(); + }; + this.setValue = function(v) { + return this.ace.setValue(v); + }; + this.getTokenTypeAt = function(pos) { + var token = this.ace.session.getTokenAt(pos.line, pos.ch); + return token && /comment|string/.test(token.type) ? "string" : ""; + }; + this.findMatchingBracket = function(pos) { + var m = this.ace.session.findMatchingBracket(toAcePos(pos)); + return {to: m && toCmPos(m)}; + }; + this.indentLine = function(line, method) { + if (method === true) + this.ace.session.indentRows(line, line, "\t"); + else if (method === false) + this.ace.session.outdentRows(new Range(line, 0, line, 0)); + }; + this.indexFromPos = function(pos) { + return this.ace.session.doc.positionToIndex(toAcePos(pos)); + }; + this.posFromIndex = function(index) { + return toCmPos(this.ace.session.doc.indexToPosition(index)); + }; + this.focus = function(index) { + return this.ace.focus(); + }; + this.blur = function(index) { + return this.ace.blur(); + }; + this.defaultTextHeight = function(index) { + return this.ace.renderer.layerConfig.lineHeight; + }; + this.scanForBracket = function(pos, dir, _, options) { + var re = options.bracketRegex.source; + if (dir == 1) { + var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), /paren|text/); + } else { + var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), {row: pos.line, column: pos.ch + 1}, /paren|text/); + } + return m && {pos: toCmPos(m)}; + }; + this.refresh = function() { + return this.ace.resize(true); + }; + this.getMode = function() { + return { name : this.getOption("mode") }; + } +}).call(CodeMirror.prototype); + function toAcePos(cmPos) { + return {row: cmPos.line, column: cmPos.ch}; + } + function toCmPos(acePos) { + return new Pos(acePos.row, acePos.column); + } + + var StringStream = CodeMirror.StringStream = function(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == this.lineStart;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() { + throw "not implemented"; + }, + indentation: function() { + throw "not implemented"; + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);}, + hideFirstChars: function(n, inner) { + this.lineStart += n; + try { return inner(); } + finally { this.lineStart -= n; } + } + }; +CodeMirror.defineExtension = function(name, fn) { + CodeMirror.prototype[name] = fn; +}; +dom.importCssString(".normal-mode .ace_cursor{\ + border: 1px solid red;\ + background-color: red;\ + opacity: 0.5;\ +}\ +.normal-mode .ace_hidden-cursors .ace_cursor{\ + background-color: transparent;\ +}\ +.ace_dialog {\ + position: absolute;\ + left: 0; right: 0;\ + background: white;\ + z-index: 15;\ + padding: .1em .8em;\ + overflow: hidden;\ + color: #333;\ +}\ +.ace_dialog-top {\ + border-bottom: 1px solid #eee;\ + top: 0;\ +}\ +.ace_dialog-bottom {\ + border-top: 1px solid #eee;\ + bottom: 0;\ +}\ +.ace_dialog input {\ + border: none;\ + outline: none;\ + background: transparent;\ + width: 20em;\ + color: inherit;\ + font-family: monospace;\ +}", "vimMode"); +(function() { + function dialogDiv(cm, template, bottom) { + var wrap = cm.ace.container; + var dialog; + dialog = wrap.appendChild(document.createElement("div")); + if (bottom) + dialog.className = "ace_dialog ace_dialog-bottom"; + else + dialog.className = "ace_dialog ace_dialog-top"; + + if (typeof template == "string") { + dialog.innerHTML = template; + } else { // Assuming it's a detached DOM element. + dialog.appendChild(template); + } + return dialog; + } + + function closeNotification(cm, newVal) { + if (cm.state.currentNotificationClose) + cm.state.currentNotificationClose(); + cm.state.currentNotificationClose = newVal; + } + + CodeMirror.defineExtension("openDialog", function(template, callback, options) { + if (this.virtualSelectionMode()) return; + if (!options) options = {}; + + closeNotification(this, null); + + var dialog = dialogDiv(this, template, options.bottom); + var closed = false, me = this; + function close(newVal) { + if (typeof newVal == 'string') { + inp.value = newVal; + } else { + if (closed) return; + closed = true; + dialog.parentNode.removeChild(dialog); + me.focus(); + + if (options.onClose) options.onClose(dialog); + } + } + + var inp = dialog.getElementsByTagName("input")[0], button; + if (inp) { + if (options.value) { + inp.value = options.value; + if (options.select !== false) inp.select(); + } + + if (options.onInput) + CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);}); + if (options.onKeyUp) + CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);}); + + CodeMirror.on(inp, "keydown", function(e) { + if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; } + if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) { + inp.blur(); + CodeMirror.e_stop(e); + close(); + } + if (e.keyCode == 13) callback(inp.value); + }); + + if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close); + + inp.focus(); + } else if (button = dialog.getElementsByTagName("button")[0]) { + CodeMirror.on(button, "click", function() { + close(); + me.focus(); + }); + + if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); + + button.focus(); + } + return close; + }); + + CodeMirror.defineExtension("openNotification", function(template, options) { + if (this.virtualSelectionMode()) return; + closeNotification(this, close); + var dialog = dialogDiv(this, template, options && options.bottom); + var closed = false, doneTimer; + var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000; + + function close() { + if (closed) return; + closed = true; + clearTimeout(doneTimer); + dialog.parentNode.removeChild(dialog); + } + + CodeMirror.on(dialog, 'click', function(e) { + CodeMirror.e_preventDefault(e); + close(); + }); + + if (duration) + doneTimer = setTimeout(close, duration); + + return close; + }); +})(); + + + var defaultKeymap = [ + { keys: '', type: 'keyToKey', toKeys: 'h' }, + { keys: '', type: 'keyToKey', toKeys: 'l' }, + { keys: '', type: 'keyToKey', toKeys: 'k' }, + { keys: '', type: 'keyToKey', toKeys: 'j' }, + { keys: '', type: 'keyToKey', toKeys: 'l' }, + { keys: '', type: 'keyToKey', toKeys: 'h', context: 'normal'}, + { keys: '', type: 'keyToKey', toKeys: 'W' }, + { keys: '', type: 'keyToKey', toKeys: 'B', context: 'normal' }, + { keys: '', type: 'keyToKey', toKeys: 'w' }, + { keys: '', type: 'keyToKey', toKeys: 'b', context: 'normal' }, + { keys: '', type: 'keyToKey', toKeys: 'j' }, + { keys: '', type: 'keyToKey', toKeys: 'k' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, + { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, + { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' }, + { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'}, + { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' }, + { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' }, + { keys: '', type: 'keyToKey', toKeys: '0' }, + { keys: '', type: 'keyToKey', toKeys: '$' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: '' }, + { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' }, + { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }}, + { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }}, + { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }}, + { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }}, + { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }}, + { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }}, + { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }}, + { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }}, + { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }}, + { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }}, + { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }}, + { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }}, + { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }}, + { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }}, + { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }}, + { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }}, + { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }}, + { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }}, + { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }}, + { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }}, + { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }}, + { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }}, + { keys: '0', type: 'motion', motion: 'moveToStartOfLine' }, + { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }}, + { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }}, + { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }}, + { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }}, + { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }}, + { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }}, + { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }}, + { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }}, + { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }}, + { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }}, + { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }}, + { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}}, + { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, + { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } }, + { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } }, + { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } }, + { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } }, + { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}}, + { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}}, + { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}}, + { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}}, + { keys: '|', type: 'motion', motion: 'moveToColumn'}, + { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'}, + { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'}, + { keys: 'd', type: 'operator', operator: 'delete' }, + { keys: 'y', type: 'operator', operator: 'yank' }, + { keys: 'c', type: 'operator', operator: 'change' }, + { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }}, + { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }}, + { keys: 'g~', type: 'operator', operator: 'changeCase' }, + { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true }, + { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true }, + { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }}, + { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }}, + { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }}, + { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }}, + { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'}, + { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'}, + { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' }, + { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }}, + { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }}, + { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }}, + { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }}, + { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' }, + { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' }, + { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' }, + { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' }, + { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' }, + { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' }, + { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' }, + { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' }, + { keys: 'v', type: 'action', action: 'toggleVisualMode' }, + { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }}, + { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, + { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, + { keys: 'gv', type: 'action', action: 'reselectLastSelection' }, + { keys: 'J', type: 'action', action: 'joinLines', isEdit: true }, + { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }}, + { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }}, + { keys: 'r', type: 'action', action: 'replace', isEdit: true }, + { keys: '@', type: 'action', action: 'replayMacro' }, + { keys: 'q', type: 'action', action: 'enterMacroRecordMode' }, + { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }}, + { keys: 'u', type: 'action', action: 'undo', context: 'normal' }, + { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true }, + { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true }, + { keys: '', type: 'action', action: 'redo' }, + { keys: 'm', type: 'action', action: 'setMark' }, + { keys: '"', type: 'action', action: 'setRegister' }, + { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }}, + { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }}, + { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }}, + { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: '.', type: 'action', action: 'repeatLastEdit' }, + { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}}, + { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}}, + { keys: 'a', type: 'motion', motion: 'textObjectManipulation' }, + { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }}, + { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }}, + { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }}, + { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, + { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, + { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }}, + { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }}, + { keys: ':', type: 'ex' } + ]; + var defaultExCommandMap = [ + { name: 'colorscheme', shortName: 'colo' }, + { name: 'map' }, + { name: 'imap', shortName: 'im' }, + { name: 'nmap', shortName: 'nm' }, + { name: 'vmap', shortName: 'vm' }, + { name: 'unmap' }, + { name: 'write', shortName: 'w' }, + { name: 'quit', shortName: 'q' }, + { name: 'xwritequit', shortName: 'x'}, + { name: 'wqwritequit', shortName: 'wq'}, + { name: 'undo', shortName: 'u' }, + { name: 'redo', shortName: 'red' }, + { name: 'set', shortName: 'se' }, + { name: 'set', shortName: 'se' }, + { name: 'setlocal', shortName: 'setl' }, + { name: 'setglobal', shortName: 'setg' }, + { name: 'sort', shortName: 'sor' }, + { name: 'substitute', shortName: 's', possiblyAsync: true }, + { name: 'nohlsearch', shortName: 'noh' }, + { name: 'delmarks', shortName: 'delm' }, + { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true }, + { name: 'global', shortName: 'g' } + ]; + + var Pos = CodeMirror.Pos; + + var Vim = function() { return vimApi; } //{ + function enterVimMode(cm) { + cm.setOption('disableInput', true); + cm.setOption('showCursorWhenSelecting', false); + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + cm.on('cursorActivity', onCursorActivity); + maybeInitVimState(cm); + CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm)); + } + + function leaveVimMode(cm) { + cm.setOption('disableInput', false); + cm.off('cursorActivity', onCursorActivity); + CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm)); + cm.state.vim = null; + } + + function detachVimMap(cm, next) { + if (this == CodeMirror.keyMap.vim) + CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor"); + + if (!next || next.attach != attachVimMap) + leaveVimMode(cm, false); + } + function attachVimMap(cm, prev) { + if (this == CodeMirror.keyMap.vim) + CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor"); + + if (!prev || prev.attach != attachVimMap) + enterVimMode(cm); + } + CodeMirror.defineOption('vimMode', false, function(cm, val, prev) { + if (val && cm.getOption("keyMap") != "vim") + cm.setOption("keyMap", "vim"); + else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap"))) + cm.setOption("keyMap", "default"); + }); + + function cmKey(key, cm) { + if (!cm) { return undefined; } + var vimKey = cmKeyToVimKey(key); + if (!vimKey) { + return false; + } + var cmd = CodeMirror.Vim.findKey(cm, vimKey); + if (typeof cmd == 'function') { + CodeMirror.signal(cm, 'vim-keypress', vimKey); + } + return cmd; + } + + var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'}; + var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del'}; + function cmKeyToVimKey(key) { + if (key.charAt(0) == '\'') { + return key.charAt(1); + } + var pieces = key.split(/-(?!$)/); + var lastPiece = pieces[pieces.length - 1]; + if (pieces.length == 1 && pieces[0].length == 1) { + return false; + } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) { + return false; + } + var hasCharacter = false; + for (var i = 0; i < pieces.length; i++) { + var piece = pieces[i]; + if (piece in modifiers) { pieces[i] = modifiers[piece]; } + else { hasCharacter = true; } + if (piece in specialKeys) { pieces[i] = specialKeys[piece]; } + } + if (!hasCharacter) { + return false; + } + if (isUpperCase(lastPiece)) { + pieces[pieces.length - 1] = lastPiece.toLowerCase(); + } + return '<' + pieces.join('-') + '>'; + } + + function getOnPasteFn(cm) { + var vim = cm.state.vim; + if (!vim.onPasteFn) { + vim.onPasteFn = function() { + if (!vim.insertMode) { + cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); + actions.enterInsertMode(cm, {}, vim); + } + }; + } + return vim.onPasteFn; + } + + var numberRegex = /[\d]/; + var wordCharTest = [CodeMirror.isWordChar, function(ch) { + return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch); + }], bigWordCharTest = [function(ch) { + return /\S/.test(ch); + }]; + function makeKeyRange(start, size) { + var keys = []; + for (var i = start; i < start + size; i++) { + keys.push(String.fromCharCode(i)); + } + return keys; + } + var upperCaseAlphabet = makeKeyRange(65, 26); + var lowerCaseAlphabet = makeKeyRange(97, 26); + var numbers = makeKeyRange(48, 10); + var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']); + var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']); + + function isLine(cm, line) { + return line >= cm.firstLine() && line <= cm.lastLine(); + } + function isLowerCase(k) { + return (/^[a-z]$/).test(k); + } + function isMatchableSymbol(k) { + return '()[]{}'.indexOf(k) != -1; + } + function isNumber(k) { + return numberRegex.test(k); + } + function isUpperCase(k) { + return (/^[A-Z]$/).test(k); + } + function isWhiteSpaceString(k) { + return (/^\s*$/).test(k); + } + function inArray(val, arr) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] == val) { + return true; + } + } + return false; + } + + var options = {}; + function defineOption(name, defaultValue, type, aliases, callback) { + if (defaultValue === undefined && !callback) { + throw Error('defaultValue is acequired unless callback is provided'); + } + if (!type) { type = 'string'; } + options[name] = { + type: type, + defaultValue: defaultValue, + callback: callback + }; + if (aliases) { + for (var i = 0; i < aliases.length; i++) { + options[aliases[i]] = options[name]; + } + } + if (defaultValue) { + setOption(name, defaultValue); + } + } + + function setOption(name, value, cm, cfg) { + var option = options[name]; + cfg = cfg || {}; + var scope = cfg.scope; + if (!option) { + throw Error('Unknown option: ' + name); + } + if (option.type == 'boolean') { + if (value && value !== true) { + throw Error('Invalid argument: ' + name + '=' + value); + } else if (value !== false) { + value = true; + } + } + if (option.callback) { + if (scope !== 'local') { + option.callback(value, undefined); + } + if (scope !== 'global' && cm) { + option.callback(value, cm); + } + } else { + if (scope !== 'local') { + option.value = option.type == 'boolean' ? !!value : value; + } + if (scope !== 'global' && cm) { + cm.state.vim.options[name] = {value: value}; + } + } + } + + function getOption(name, cm, cfg) { + var option = options[name]; + cfg = cfg || {}; + var scope = cfg.scope; + if (!option) { + throw Error('Unknown option: ' + name); + } + if (option.callback) { + var local = cm && option.callback(undefined, cm); + if (scope !== 'global' && local !== undefined) { + return local; + } + if (scope !== 'local') { + return option.callback(); + } + return; + } else { + var local = (scope !== 'global') && (cm && cm.state.vim.options[name]); + return (local || (scope !== 'local') && option || {}).value; + } + } + + defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) { + if (cm === undefined) { + return; + } + if (name === undefined) { + var mode = cm.getOption('mode'); + return mode == 'null' ? '' : mode; + } else { + var mode = name == '' ? 'null' : name; + cm.setOption('mode', mode); + } + }); + + var createCircularJumpList = function() { + var size = 100; + var pointer = -1; + var head = 0; + var tail = 0; + var buffer = new Array(size); + function add(cm, oldCur, newCur) { + var current = pointer % size; + var curMark = buffer[current]; + function useNextSlot(cursor) { + var next = ++pointer % size; + var trashMark = buffer[next]; + if (trashMark) { + trashMark.clear(); + } + buffer[next] = cm.setBookmark(cursor); + } + if (curMark) { + var markPos = curMark.find(); + if (markPos && !cursorEqual(markPos, oldCur)) { + useNextSlot(oldCur); + } + } else { + useNextSlot(oldCur); + } + useNextSlot(newCur); + head = pointer; + tail = pointer - size + 1; + if (tail < 0) { + tail = 0; + } + } + function move(cm, offset) { + pointer += offset; + if (pointer > head) { + pointer = head; + } else if (pointer < tail) { + pointer = tail; + } + var mark = buffer[(size + pointer) % size]; + if (mark && !mark.find()) { + var inc = offset > 0 ? 1 : -1; + var newCur; + var oldCur = cm.getCursor(); + do { + pointer += inc; + mark = buffer[(size + pointer) % size]; + if (mark && + (newCur = mark.find()) && + !cursorEqual(oldCur, newCur)) { + break; + } + } while (pointer < head && pointer > tail); + } + return mark; + } + return { + cachedCursor: undefined, //used for # and * jumps + add: add, + move: move + }; + }; + var createInsertModeChanges = function(c) { + if (c) { + return { + changes: c.changes, + expectCursorActivityForChange: c.expectCursorActivityForChange + }; + } + return { + changes: [], + expectCursorActivityForChange: false + }; + }; + + function MacroModeState() { + this.latestRegister = undefined; + this.isPlaying = false; + this.isRecording = false; + this.replaySearchQueries = []; + this.onRecordingDone = undefined; + this.lastInsertModeChanges = createInsertModeChanges(); + } + MacroModeState.prototype = { + exitMacroRecordMode: function() { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.onRecordingDone) { + macroModeState.onRecordingDone(); // close dialog + } + macroModeState.onRecordingDone = undefined; + macroModeState.isRecording = false; + }, + enterMacroRecordMode: function(cm, registerName) { + var register = + vimGlobalState.registerController.getRegister(registerName); + if (register) { + register.clear(); + this.latestRegister = registerName; + if (cm.openDialog) { + this.onRecordingDone = cm.openDialog( + '(recording)['+registerName+']', null, {bottom:true}); + } + this.isRecording = true; + } + } + }; + + function maybeInitVimState(cm) { + if (!cm.state.vim) { + cm.state.vim = { + inputState: new InputState(), + lastEditInputState: undefined, + lastEditActionCommand: undefined, + lastHPos: -1, + lastHSPos: -1, + lastMotion: null, + marks: {}, + fakeCursor: null, + insertMode: false, + insertModeRepeat: undefined, + visualMode: false, + visualLine: false, + visualBlock: false, + lastSelection: null, + lastPastedText: null, + sel: {}, + options: {} + }; + } + return cm.state.vim; + } + var vimGlobalState; + function resetVimGlobalState() { + vimGlobalState = { + searchQuery: null, + searchIsReversed: false, + lastSubstituteReplacePart: undefined, + jumpList: createCircularJumpList(), + macroModeState: new MacroModeState, + lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''}, + registerController: new RegisterController({}), + searchHistoryController: new HistoryController({}), + exCommandHistoryController : new HistoryController({}) + }; + for (var optionName in options) { + var option = options[optionName]; + option.value = option.defaultValue; + } + } + + var lastInsertModeKeyTimer; + var vimApi= { + buildKeyMap: function() { + }, + getRegisterController: function() { + return vimGlobalState.registerController; + }, + resetVimGlobalState_: resetVimGlobalState, + getVimGlobalState_: function() { + return vimGlobalState; + }, + maybeInitVimState_: maybeInitVimState, + + suppressErrorLogging: false, + + InsertModeKey: InsertModeKey, + map: function(lhs, rhs, ctx) { + exCommandDispatcher.map(lhs, rhs, ctx); + }, + unmap: function(lhs, ctx) { + exCommandDispatcher.unmap(lhs, ctx); + }, + setOption: setOption, + getOption: getOption, + defineOption: defineOption, + defineEx: function(name, prefix, func){ + if (!prefix) { + prefix = name; + } else if (name.indexOf(prefix) !== 0) { + throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered'); + } + exCommands[name]=func; + exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; + }, + handleKey: function (cm, key, origin) { + var command = this.findKey(cm, key, origin); + if (typeof command === 'function') { + return command(); + } + }, + findKey: function(cm, key, origin) { + var vim = maybeInitVimState(cm); + function handleMacroRecording() { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isRecording) { + if (key == 'q') { + macroModeState.exitMacroRecordMode(); + clearInputState(cm); + return true; + } + if (origin != 'mapping') { + logKey(macroModeState, key); + } + } + } + function handleEsc() { + if (key == '') { + clearInputState(cm); + if (vim.visualMode) { + exitVisualMode(cm); + } else if (vim.insertMode) { + exitInsertMode(cm); + } + return true; + } + } + function doKeyToKey(keys) { + var match; + while (keys) { + match = (/<\w+-.+?>|<\w+>|./).exec(keys); + key = match[0]; + keys = keys.substring(match.index + key.length); + CodeMirror.Vim.handleKey(cm, key, 'mapping'); + } + } + + function handleKeyInsertMode() { + if (handleEsc()) { return true; } + var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; + var keysAreChars = key.length == 1; + var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); + while (keys.length > 1 && match.type != 'full') { + var keys = vim.inputState.keyBuffer = keys.slice(1); + var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); + if (thisMatch.type != 'none') { match = thisMatch; } + } + if (match.type == 'none') { clearInputState(cm); return false; } + else if (match.type == 'partial') { + if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } + lastInsertModeKeyTimer = window.setTimeout( + function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } }, + getOption('insertModeEscKeysTimeout')); + return !keysAreChars; + } + + if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } + if (keysAreChars) { + var selections = cm.listSelections(); + for (var i = 0; i < selections.length; i++) { + var here = selections[i].head; + cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input'); + } + vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop(); + } + clearInputState(cm); + return match.command; + } + + function handleKeyNonInsertMode() { + if (handleMacroRecording() || handleEsc()) { return true; } + + var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; + if (/^[1-9]\d*$/.test(keys)) { return true; } + + var keysMatcher = /^(\d*)(.*)$/.exec(keys); + if (!keysMatcher) { clearInputState(cm); return false; } + var context = vim.visualMode ? 'visual' : + 'normal'; + var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context); + if (match.type == 'none') { clearInputState(cm); return false; } + else if (match.type == 'partial') { return true; } + + vim.inputState.keyBuffer = ''; + var keysMatcher = /^(\d*)(.*)$/.exec(keys); + if (keysMatcher[1] && keysMatcher[1] != '0') { + vim.inputState.pushRepeatDigit(keysMatcher[1]); + } + return match.command; + } + + var command; + if (vim.insertMode) { command = handleKeyInsertMode(); } + else { command = handleKeyNonInsertMode(); } + if (command === false) { + return undefined; + } else if (command === true) { + return function() { return true; }; + } else { + return function() { + if ((command.operator || command.isEdit) && cm.getOption('readOnly')) + return; // ace_patch + return cm.operation(function() { + cm.curOp.isVimOp = true; + try { + if (command.type == 'keyToKey') { + doKeyToKey(command.toKeys); + } else { + commandDispatcher.processCommand(cm, vim, command); + } + } catch (e) { + cm.state.vim = undefined; + maybeInitVimState(cm); + if (!CodeMirror.Vim.suppressErrorLogging) { + console['log'](e); + } + throw e; + } + return true; + }); + }; + } + }, + handleEx: function(cm, input) { + exCommandDispatcher.processCommand(cm, input); + }, + + defineMotion: defineMotion, + defineAction: defineAction, + defineOperator: defineOperator, + mapCommand: mapCommand, + _mapCommand: _mapCommand, + + defineRegister: defineRegister, + + exitVisualMode: exitVisualMode, + exitInsertMode: exitInsertMode + }; + function InputState() { + this.prefixRepeat = []; + this.motionRepeat = []; + + this.operator = null; + this.operatorArgs = null; + this.motion = null; + this.motionArgs = null; + this.keyBuffer = []; // For matching multi-key commands. + this.registerName = null; // Defaults to the unnamed register. + } + InputState.prototype.pushRepeatDigit = function(n) { + if (!this.operator) { + this.prefixRepeat = this.prefixRepeat.concat(n); + } else { + this.motionRepeat = this.motionRepeat.concat(n); + } + }; + InputState.prototype.getRepeat = function() { + var repeat = 0; + if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) { + repeat = 1; + if (this.prefixRepeat.length > 0) { + repeat *= parseInt(this.prefixRepeat.join(''), 10); + } + if (this.motionRepeat.length > 0) { + repeat *= parseInt(this.motionRepeat.join(''), 10); + } + } + return repeat; + }; + + function clearInputState(cm, reason) { + cm.state.vim.inputState = new InputState(); + CodeMirror.signal(cm, 'vim-command-done', reason); + } + function Register(text, linewise, blockwise) { + this.clear(); + this.keyBuffer = [text || '']; + this.insertModeChanges = []; + this.searchQueries = []; + this.linewise = !!linewise; + this.blockwise = !!blockwise; + } + Register.prototype = { + setText: function(text, linewise, blockwise) { + this.keyBuffer = [text || '']; + this.linewise = !!linewise; + this.blockwise = !!blockwise; + }, + pushText: function(text, linewise) { + if (linewise) { + if (!this.linewise) { + this.keyBuffer.push('\n'); + } + this.linewise = true; + } + this.keyBuffer.push(text); + }, + pushInsertModeChanges: function(changes) { + this.insertModeChanges.push(createInsertModeChanges(changes)); + }, + pushSearchQuery: function(query) { + this.searchQueries.push(query); + }, + clear: function() { + this.keyBuffer = []; + this.insertModeChanges = []; + this.searchQueries = []; + this.linewise = false; + }, + toString: function() { + return this.keyBuffer.join(''); + } + }; + function defineRegister(name, register) { + var registers = vimGlobalState.registerController.registers[name]; + if (!name || name.length != 1) { + throw Error('Register name must be 1 character'); + } + registers[name] = register; + validRegisters.push(name); + } + function RegisterController(registers) { + this.registers = registers; + this.unnamedRegister = registers['"'] = new Register(); + registers['.'] = new Register(); + registers[':'] = new Register(); + registers['/'] = new Register(); + } + RegisterController.prototype = { + pushText: function(registerName, operator, text, linewise, blockwise) { + if (linewise && text.charAt(0) == '\n') { + text = text.slice(1) + '\n'; + } + if (linewise && text.charAt(text.length - 1) !== '\n'){ + text += '\n'; + } + var register = this.isValidRegister(registerName) ? + this.getRegister(registerName) : null; + if (!register) { + switch (operator) { + case 'yank': + this.registers['0'] = new Register(text, linewise, blockwise); + break; + case 'delete': + case 'change': + if (text.indexOf('\n') == -1) { + this.registers['-'] = new Register(text, linewise); + } else { + this.shiftNumericRegisters_(); + this.registers['1'] = new Register(text, linewise); + } + break; + } + this.unnamedRegister.setText(text, linewise, blockwise); + return; + } + var append = isUpperCase(registerName); + if (append) { + register.pushText(text, linewise); + } else { + register.setText(text, linewise, blockwise); + } + this.unnamedRegister.setText(register.toString(), linewise); + }, + getRegister: function(name) { + if (!this.isValidRegister(name)) { + return this.unnamedRegister; + } + name = name.toLowerCase(); + if (!this.registers[name]) { + this.registers[name] = new Register(); + } + return this.registers[name]; + }, + isValidRegister: function(name) { + return name && inArray(name, validRegisters); + }, + shiftNumericRegisters_: function() { + for (var i = 9; i >= 2; i--) { + this.registers[i] = this.getRegister('' + (i - 1)); + } + } + }; + function HistoryController() { + this.historyBuffer = []; + this.iterator; + this.initialPrefix = null; + } + HistoryController.prototype = { + nextMatch: function (input, up) { + var historyBuffer = this.historyBuffer; + var dir = up ? -1 : 1; + if (this.initialPrefix === null) this.initialPrefix = input; + for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) { + var element = historyBuffer[i]; + for (var j = 0; j <= element.length; j++) { + if (this.initialPrefix == element.substring(0, j)) { + this.iterator = i; + return element; + } + } + } + if (i >= historyBuffer.length) { + this.iterator = historyBuffer.length; + return this.initialPrefix; + } + if (i < 0 ) return input; + }, + pushInput: function(input) { + var index = this.historyBuffer.indexOf(input); + if (index > -1) this.historyBuffer.splice(index, 1); + if (input.length) this.historyBuffer.push(input); + }, + reset: function() { + this.initialPrefix = null; + this.iterator = this.historyBuffer.length; + } + }; + var commandDispatcher = { + matchCommand: function(keys, keyMap, inputState, context) { + var matches = commandMatches(keys, keyMap, context, inputState); + if (!matches.full && !matches.partial) { + return {type: 'none'}; + } else if (!matches.full && matches.partial) { + return {type: 'partial'}; + } + + var bestMatch; + for (var i = 0; i < matches.full.length; i++) { + var match = matches.full[i]; + if (!bestMatch) { + bestMatch = match; + } + } + if (bestMatch.keys.slice(-11) == '') { + inputState.selectedCharacter = lastChar(keys); + } + return {type: 'full', command: bestMatch}; + }, + processCommand: function(cm, vim, command) { + vim.inputState.repeatOverride = command.repeatOverride; + switch (command.type) { + case 'motion': + this.processMotion(cm, vim, command); + break; + case 'operator': + this.processOperator(cm, vim, command); + break; + case 'operatorMotion': + this.processOperatorMotion(cm, vim, command); + break; + case 'action': + this.processAction(cm, vim, command); + break; + case 'search': + this.processSearch(cm, vim, command); + break; + case 'ex': + case 'keyToEx': + this.processEx(cm, vim, command); + break; + default: + break; + } + }, + processMotion: function(cm, vim, command) { + vim.inputState.motion = command.motion; + vim.inputState.motionArgs = copyArgs(command.motionArgs); + this.evalInput(cm, vim); + }, + processOperator: function(cm, vim, command) { + var inputState = vim.inputState; + if (inputState.operator) { + if (inputState.operator == command.operator) { + inputState.motion = 'expandToLine'; + inputState.motionArgs = { linewise: true }; + this.evalInput(cm, vim); + return; + } else { + clearInputState(cm); + } + } + inputState.operator = command.operator; + inputState.operatorArgs = copyArgs(command.operatorArgs); + if (vim.visualMode) { + this.evalInput(cm, vim); + } + }, + processOperatorMotion: function(cm, vim, command) { + var visualMode = vim.visualMode; + var operatorMotionArgs = copyArgs(command.operatorMotionArgs); + if (operatorMotionArgs) { + if (visualMode && operatorMotionArgs.visualLine) { + vim.visualLine = true; + } + } + this.processOperator(cm, vim, command); + if (!visualMode) { + this.processMotion(cm, vim, command); + } + }, + processAction: function(cm, vim, command) { + var inputState = vim.inputState; + var repeat = inputState.getRepeat(); + var repeatIsExplicit = !!repeat; + var actionArgs = copyArgs(command.actionArgs) || {}; + if (inputState.selectedCharacter) { + actionArgs.selectedCharacter = inputState.selectedCharacter; + } + if (command.operator) { + this.processOperator(cm, vim, command); + } + if (command.motion) { + this.processMotion(cm, vim, command); + } + if (command.motion || command.operator) { + this.evalInput(cm, vim); + } + actionArgs.repeat = repeat || 1; + actionArgs.repeatIsExplicit = repeatIsExplicit; + actionArgs.registerName = inputState.registerName; + clearInputState(cm); + vim.lastMotion = null; + if (command.isEdit) { + this.recordLastEdit(vim, inputState, command); + } + actions[command.action](cm, actionArgs, vim); + }, + processSearch: function(cm, vim, command) { + if (!cm.getSearchCursor) { + return; + } + var forward = command.searchArgs.forward; + var wholeWordOnly = command.searchArgs.wholeWordOnly; + getSearchState(cm).setReversed(!forward); + var promptPrefix = (forward) ? '/' : '?'; + var originalQuery = getSearchState(cm).getQuery(); + var originalScrollPos = cm.getScrollInfo(); + function handleQuery(query, ignoreCase, smartCase) { + vimGlobalState.searchHistoryController.pushInput(query); + vimGlobalState.searchHistoryController.reset(); + try { + updateSearchQuery(cm, query, ignoreCase, smartCase); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + query); + clearInputState(cm); + return; + } + commandDispatcher.processMotion(cm, vim, { + type: 'motion', + motion: 'findNext', + motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist } + }); + } + function onPromptClose(query) { + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + handleQuery(query, true /** ignoreCase */, true /** smartCase */); + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isRecording) { + logSearchQuery(macroModeState, query); + } + } + function onPromptKeyUp(e, query, close) { + var keyName = CodeMirror.keyName(e), up; + if (keyName == 'Up' || keyName == 'Down') { + up = keyName == 'Up' ? true : false; + query = vimGlobalState.searchHistoryController.nextMatch(query, up) || ''; + close(query); + } else { + if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') + vimGlobalState.searchHistoryController.reset(); + } + var parsedQuery; + try { + parsedQuery = updateSearchQuery(cm, query, + true /** ignoreCase */, true /** smartCase */); + } catch (e) { + } + if (parsedQuery) { + cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30); + } else { + clearSearchHighlight(cm); + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + } + } + function onPromptKeyDown(e, query, close) { + var keyName = CodeMirror.keyName(e); + if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || + (keyName == 'Backspace' && query == '')) { + vimGlobalState.searchHistoryController.pushInput(query); + vimGlobalState.searchHistoryController.reset(); + updateSearchQuery(cm, originalQuery); + clearSearchHighlight(cm); + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + CodeMirror.e_stop(e); + clearInputState(cm); + close(); + cm.focus(); + } else if (keyName == 'Ctrl-U') { + CodeMirror.e_stop(e); + close(''); + } + } + switch (command.searchArgs.querySrc) { + case 'prompt': + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { + var query = macroModeState.replaySearchQueries.shift(); + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + } else { + showPrompt(cm, { + onClose: onPromptClose, + prefix: promptPrefix, + desc: searchPromptDesc, + onKeyUp: onPromptKeyUp, + onKeyDown: onPromptKeyDown + }); + } + break; + case 'wordUnderCursor': + var word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + true /** noSymbol */); + var isKeyword = true; + if (!word) { + word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + false /** noSymbol */); + isKeyword = false; + } + if (!word) { + return; + } + var query = cm.getLine(word.start.line).substring(word.start.ch, + word.end.ch); + if (isKeyword && wholeWordOnly) { + query = '\\b' + query + '\\b'; + } else { + query = escapeRegex(query); + } + vimGlobalState.jumpList.cachedCursor = cm.getCursor(); + cm.setCursor(word.start); + + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + break; + } + }, + processEx: function(cm, vim, command) { + function onPromptClose(input) { + vimGlobalState.exCommandHistoryController.pushInput(input); + vimGlobalState.exCommandHistoryController.reset(); + exCommandDispatcher.processCommand(cm, input); + } + function onPromptKeyDown(e, input, close) { + var keyName = CodeMirror.keyName(e), up; + if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || + (keyName == 'Backspace' && input == '')) { + vimGlobalState.exCommandHistoryController.pushInput(input); + vimGlobalState.exCommandHistoryController.reset(); + CodeMirror.e_stop(e); + clearInputState(cm); + close(); + cm.focus(); + } + if (keyName == 'Up' || keyName == 'Down') { + up = keyName == 'Up' ? true : false; + input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || ''; + close(input); + } else if (keyName == 'Ctrl-U') { + CodeMirror.e_stop(e); + close(''); + } else { + if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') + vimGlobalState.exCommandHistoryController.reset(); + } + } + if (command.type == 'keyToEx') { + exCommandDispatcher.processCommand(cm, command.exArgs.input); + } else { + if (vim.visualMode) { + showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>', + onKeyDown: onPromptKeyDown}); + } else { + showPrompt(cm, { onClose: onPromptClose, prefix: ':', + onKeyDown: onPromptKeyDown}); + } + } + }, + evalInput: function(cm, vim) { + var inputState = vim.inputState; + var motion = inputState.motion; + var motionArgs = inputState.motionArgs || {}; + var operator = inputState.operator; + var operatorArgs = inputState.operatorArgs || {}; + var registerName = inputState.registerName; + var sel = vim.sel; + var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head')); + var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor')); + var oldHead = copyCursor(origHead); + var oldAnchor = copyCursor(origAnchor); + var newHead, newAnchor; + var repeat; + if (operator) { + this.recordLastEdit(vim, inputState); + } + if (inputState.repeatOverride !== undefined) { + repeat = inputState.repeatOverride; + } else { + repeat = inputState.getRepeat(); + } + if (repeat > 0 && motionArgs.explicitRepeat) { + motionArgs.repeatIsExplicit = true; + } else if (motionArgs.noRepeat || + (!motionArgs.explicitRepeat && repeat === 0)) { + repeat = 1; + motionArgs.repeatIsExplicit = false; + } + if (inputState.selectedCharacter) { + motionArgs.selectedCharacter = operatorArgs.selectedCharacter = + inputState.selectedCharacter; + } + motionArgs.repeat = repeat; + clearInputState(cm); + if (motion) { + var motionResult = motions[motion](cm, origHead, motionArgs, vim); + vim.lastMotion = motions[motion]; + if (!motionResult) { + return; + } + if (motionArgs.toJumplist) { + if (!operator && cm.ace.curOp != null) + cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch + var jumpList = vimGlobalState.jumpList; + var cachedCursor = jumpList.cachedCursor; + if (cachedCursor) { + recordJumpPosition(cm, cachedCursor, motionResult); + delete jumpList.cachedCursor; + } else { + recordJumpPosition(cm, origHead, motionResult); + } + } + if (motionResult instanceof Array) { + newAnchor = motionResult[0]; + newHead = motionResult[1]; + } else { + newHead = motionResult; + } + if (!newHead) { + newHead = copyCursor(origHead); + } + if (vim.visualMode) { + if (!(vim.visualBlock && newHead.ch === Infinity)) { + newHead = clipCursorToContent(cm, newHead, vim.visualBlock); + } + if (newAnchor) { + newAnchor = clipCursorToContent(cm, newAnchor, true); + } + newAnchor = newAnchor || oldAnchor; + sel.anchor = newAnchor; + sel.head = newHead; + updateCmSelection(cm); + updateMark(cm, vim, '<', + cursorIsBefore(newAnchor, newHead) ? newAnchor + : newHead); + updateMark(cm, vim, '>', + cursorIsBefore(newAnchor, newHead) ? newHead + : newAnchor); + } else if (!operator) { + newHead = clipCursorToContent(cm, newHead); + cm.setCursor(newHead.line, newHead.ch); + } + } + if (operator) { + if (operatorArgs.lastSel) { + newAnchor = oldAnchor; + var lastSel = operatorArgs.lastSel; + var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line); + var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch); + if (lastSel.visualLine) { + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); + } else if (lastSel.visualBlock) { + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset); + } else if (lastSel.head.line == lastSel.anchor.line) { + newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset); + } else { + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); + } + vim.visualMode = true; + vim.visualLine = lastSel.visualLine; + vim.visualBlock = lastSel.visualBlock; + sel = vim.sel = { + anchor: newAnchor, + head: newHead + }; + updateCmSelection(cm); + } else if (vim.visualMode) { + operatorArgs.lastSel = { + anchor: copyCursor(sel.anchor), + head: copyCursor(sel.head), + visualBlock: vim.visualBlock, + visualLine: vim.visualLine + }; + } + var curStart, curEnd, linewise, mode; + var cmSel; + if (vim.visualMode) { + curStart = cursorMin(sel.head, sel.anchor); + curEnd = cursorMax(sel.head, sel.anchor); + linewise = vim.visualLine || operatorArgs.linewise; + mode = vim.visualBlock ? 'block' : + linewise ? 'line' : + 'char'; + cmSel = makeCmSelection(cm, { + anchor: curStart, + head: curEnd + }, mode); + if (linewise) { + var ranges = cmSel.ranges; + if (mode == 'block') { + for (var i = 0; i < ranges.length; i++) { + ranges[i].head.ch = lineLength(cm, ranges[i].head.line); + } + } else if (mode == 'line') { + ranges[0].head = Pos(ranges[0].head.line + 1, 0); + } + } + } else { + curStart = copyCursor(newAnchor || oldAnchor); + curEnd = copyCursor(newHead || oldHead); + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curStart; + curStart = curEnd; + curEnd = tmp; + } + linewise = motionArgs.linewise || operatorArgs.linewise; + if (linewise) { + expandSelectionToLine(cm, curStart, curEnd); + } else if (motionArgs.forward) { + clipToLine(cm, curStart, curEnd); + } + mode = 'char'; + var exclusive = !motionArgs.inclusive || linewise; + cmSel = makeCmSelection(cm, { + anchor: curStart, + head: curEnd + }, mode, exclusive); + } + cm.setSelections(cmSel.ranges, cmSel.primary); + vim.lastMotion = null; + operatorArgs.repeat = repeat; // For indent in visual mode. + operatorArgs.registerName = registerName; + operatorArgs.linewise = linewise; + var operatorMoveTo = operators[operator]( + cm, operatorArgs, cmSel.ranges, oldAnchor, newHead); + if (vim.visualMode) { + exitVisualMode(cm, operatorMoveTo != null); + } + if (operatorMoveTo) { + cm.setCursor(operatorMoveTo); + } + } + }, + recordLastEdit: function(vim, inputState, actionCommand) { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { return; } + vim.lastEditInputState = inputState; + vim.lastEditActionCommand = actionCommand; + macroModeState.lastInsertModeChanges.changes = []; + macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false; + } + }; + var motions = { + moveToTopLine: function(cm, _head, motionArgs) { + var line = getUserVisibleLines(cm).top + motionArgs.repeat -1; + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + moveToMiddleLine: function(cm) { + var range = getUserVisibleLines(cm); + var line = Math.floor((range.top + range.bottom) * 0.5); + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + moveToBottomLine: function(cm, _head, motionArgs) { + var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1; + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + expandToLine: function(_cm, head, motionArgs) { + var cur = head; + return Pos(cur.line + motionArgs.repeat - 1, Infinity); + }, + findNext: function(cm, _head, motionArgs) { + var state = getSearchState(cm); + var query = state.getQuery(); + if (!query) { + return; + } + var prev = !motionArgs.forward; + prev = (state.isReversed()) ? !prev : prev; + highlightSearchMatches(cm, query); + return findNext(cm, prev/** prev */, query, motionArgs.repeat); + }, + goToMark: function(cm, _head, motionArgs, vim) { + var mark = vim.marks[motionArgs.selectedCharacter]; + if (mark) { + var pos = mark.find(); + return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos; + } + return null; + }, + moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) { + if (vim.visualBlock && motionArgs.sameLine) { + var sel = vim.sel; + return [ + clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)), + clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch)) + ]; + } else { + return ([vim.sel.head, vim.sel.anchor]); + } + }, + jumpToMark: function(cm, head, motionArgs, vim) { + var best = head; + for (var i = 0; i < motionArgs.repeat; i++) { + var cursor = best; + for (var key in vim.marks) { + if (!isLowerCase(key)) { + continue; + } + var mark = vim.marks[key].find(); + var isWrongDirection = (motionArgs.forward) ? + cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark); + + if (isWrongDirection) { + continue; + } + if (motionArgs.linewise && (mark.line == cursor.line)) { + continue; + } + + var equal = cursorEqual(cursor, best); + var between = (motionArgs.forward) ? + cursorIsBetween(cursor, mark, best) : + cursorIsBetween(best, mark, cursor); + + if (equal || between) { + best = mark; + } + } + } + + if (motionArgs.linewise) { + best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))); + } + return best; + }, + moveByCharacters: function(_cm, head, motionArgs) { + var cur = head; + var repeat = motionArgs.repeat; + var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; + return Pos(cur.line, ch); + }, + moveByLines: function(cm, head, motionArgs, vim) { + var cur = head; + var endCh = cur.ch; + switch (vim.lastMotion) { + case this.moveByLines: + case this.moveByDisplayLines: + case this.moveByScroll: + case this.moveToColumn: + case this.moveToEol: + endCh = vim.lastHPos; + break; + default: + vim.lastHPos = endCh; + } + var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0); + var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; + var first = cm.firstLine(); + var last = cm.lastLine(); + if ((line < first && cur.line == first) || + (line > last && cur.line == last)) { + return; + } + var fold = cm.ace.session.getFoldLine(line); + if (fold) { + if (motionArgs.forward) { + if (line > fold.start.row) + line = fold.end.row + 1; + } else { + line = fold.start.row; + } + } + if (motionArgs.toFirstChar){ + endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)); + vim.lastHPos = endCh; + } + vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left; + return Pos(line, endCh); + }, + moveByDisplayLines: function(cm, head, motionArgs, vim) { + var cur = head; + switch (vim.lastMotion) { + case this.moveByDisplayLines: + case this.moveByScroll: + case this.moveByLines: + case this.moveToColumn: + case this.moveToEol: + break; + default: + vim.lastHSPos = cm.charCoords(cur,'div').left; + } + var repeat = motionArgs.repeat; + var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos); + if (res.hitSide) { + if (motionArgs.forward) { + var lastCharCoords = cm.charCoords(res, 'div'); + var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos }; + var res = cm.coordsChar(goalCoords, 'div'); + } else { + var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div'); + resCoords.left = vim.lastHSPos; + res = cm.coordsChar(resCoords, 'div'); + } + } + vim.lastHPos = res.ch; + return res; + }, + moveByPage: function(cm, head, motionArgs) { + var curStart = head; + var repeat = motionArgs.repeat; + return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page'); + }, + moveByParagraph: function(cm, head, motionArgs) { + var dir = motionArgs.forward ? 1 : -1; + return findParagraph(cm, head, motionArgs.repeat, dir); + }, + moveByScroll: function(cm, head, motionArgs, vim) { + var scrollbox = cm.getScrollInfo(); + var curEnd = null; + var repeat = motionArgs.repeat; + if (!repeat) { + repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight()); + } + var orig = cm.charCoords(head, 'local'); + motionArgs.repeat = repeat; + var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim); + if (!curEnd) { + return null; + } + var dest = cm.charCoords(curEnd, 'local'); + cm.scrollTo(null, scrollbox.top + dest.top - orig.top); + return curEnd; + }, + moveByWords: function(cm, head, motionArgs) { + return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward, + !!motionArgs.wordEnd, !!motionArgs.bigWord); + }, + moveTillCharacter: function(cm, _head, motionArgs) { + var repeat = motionArgs.repeat; + var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter); + var increment = motionArgs.forward ? -1 : 1; + recordLastCharacterSearch(increment, motionArgs); + if (!curEnd) return null; + curEnd.ch += increment; + return curEnd; + }, + moveToCharacter: function(cm, head, motionArgs) { + var repeat = motionArgs.repeat; + recordLastCharacterSearch(0, motionArgs); + return moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter) || head; + }, + moveToSymbol: function(cm, head, motionArgs) { + var repeat = motionArgs.repeat; + return findSymbol(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter) || head; + }, + moveToColumn: function(cm, head, motionArgs, vim) { + var repeat = motionArgs.repeat; + vim.lastHPos = repeat - 1; + vim.lastHSPos = cm.charCoords(head,'div').left; + return moveToColumn(cm, repeat); + }, + moveToEol: function(cm, head, motionArgs, vim) { + var cur = head; + vim.lastHPos = Infinity; + var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity); + var end=cm.clipPos(retval); + end.ch--; + vim.lastHSPos = cm.charCoords(end,'div').left; + return retval; + }, + moveToFirstNonWhiteSpaceCharacter: function(cm, head) { + var cursor = head; + return Pos(cursor.line, + findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line))); + }, + moveToMatchedSymbol: function(cm, head) { + var cursor = head; + var line = cursor.line; + var ch = cursor.ch; + var lineText = cm.getLine(line); + var symbol; + do { + symbol = lineText.charAt(ch++); + if (symbol && isMatchableSymbol(symbol)) { + var style = cm.getTokenTypeAt(Pos(line, ch)); + if (style !== "string" && style !== "comment") { + break; + } + } + } while (symbol); + if (symbol) { + var matched = cm.findMatchingBracket(Pos(line, ch)); + return matched.to; + } else { + return cursor; + } + }, + moveToStartOfLine: function(_cm, head) { + return Pos(head.line, 0); + }, + moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) { + var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine(); + if (motionArgs.repeatIsExplicit) { + lineNum = motionArgs.repeat - cm.getOption('firstLineNumber'); + } + return Pos(lineNum, + findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum))); + }, + textObjectManipulation: function(cm, head, motionArgs, vim) { + var mirroredPairs = {'(': ')', ')': '(', + '{': '}', '}': '{', + '[': ']', ']': '['}; + var selfPaired = {'\'': true, '"': true}; + + var character = motionArgs.selectedCharacter; + if (character == 'b') { + character = '('; + } else if (character == 'B') { + character = '{'; + } + var inclusive = !motionArgs.textObjectInner; + + var tmp; + if (mirroredPairs[character]) { + tmp = selectCompanionObject(cm, head, character, inclusive); + } else if (selfPaired[character]) { + tmp = findBeginningAndEnd(cm, head, character, inclusive); + } else if (character === 'W') { + tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, + true /** bigWord */); + } else if (character === 'w') { + tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, + false /** bigWord */); + } else if (character === 'p') { + tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive); + motionArgs.linewise = true; + if (vim.visualMode) { + if (!vim.visualLine) { vim.visualLine = true; } + } else { + var operatorArgs = vim.inputState.operatorArgs; + if (operatorArgs) { operatorArgs.linewise = true; } + tmp.end.line--; + } + } else { + return null; + } + + if (!cm.state.vim.visualMode) { + return [tmp.start, tmp.end]; + } else { + return expandSelection(cm, tmp.start, tmp.end); + } + }, + + repeatLastCharacterSearch: function(cm, head, motionArgs) { + var lastSearch = vimGlobalState.lastChararacterSearch; + var repeat = motionArgs.repeat; + var forward = motionArgs.forward === lastSearch.forward; + var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1); + cm.moveH(-increment, 'char'); + motionArgs.inclusive = forward ? true : false; + var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter); + if (!curEnd) { + cm.moveH(increment, 'char'); + return head; + } + curEnd.ch += increment; + return curEnd; + } + }; + + function defineMotion(name, fn) { + motions[name] = fn; + } + + function fillArray(val, times) { + var arr = []; + for (var i = 0; i < times; i++) { + arr.push(val); + } + return arr; + } + var operators = { + change: function(cm, args, ranges) { + var finalHead, text; + var vim = cm.state.vim; + vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock; + if (!vim.visualMode) { + var anchor = ranges[0].anchor, + head = ranges[0].head; + text = cm.getRange(anchor, head); + var lastState = vim.lastEditInputState || {}; + if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) { + var match = (/\s+$/).exec(text); + if (match && lastState.motionArgs && lastState.motionArgs.forward) { + head = offsetCursor(head, 0, - match[0].length); + text = text.slice(0, - match[0].length); + } + } + var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE); + var wasLastLine = cm.firstLine() == cm.lastLine(); + if (head.line > cm.lastLine() && args.linewise && !wasLastLine) { + cm.replaceRange('', prevLineEnd, head); + } else { + cm.replaceRange('', anchor, head); + } + if (args.linewise) { + if (!wasLastLine) { + cm.setCursor(prevLineEnd); + CodeMirror.commands.newlineAndIndent(cm); + } + anchor.ch = Number.MAX_VALUE; + } + finalHead = anchor; + } else { + text = cm.getSelection(); + var replacement = fillArray('', ranges.length); + cm.replaceSelections(replacement); + finalHead = cursorMin(ranges[0].head, ranges[0].anchor); + } + vimGlobalState.registerController.pushText( + args.registerName, 'change', text, + args.linewise, ranges.length > 1); + actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim); + }, + 'delete': function(cm, args, ranges) { + var finalHead, text; + var vim = cm.state.vim; + if (!vim.visualBlock) { + var anchor = ranges[0].anchor, + head = ranges[0].head; + if (args.linewise && + head.line != cm.firstLine() && + anchor.line == cm.lastLine() && + anchor.line == head.line - 1) { + if (anchor.line == cm.firstLine()) { + anchor.ch = 0; + } else { + anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1)); + } + } + text = cm.getRange(anchor, head); + cm.replaceRange('', anchor, head); + finalHead = anchor; + if (args.linewise) { + finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor); + } + } else { + text = cm.getSelection(); + var replacement = fillArray('', ranges.length); + cm.replaceSelections(replacement); + finalHead = ranges[0].anchor; + } + vimGlobalState.registerController.pushText( + args.registerName, 'delete', text, + args.linewise, vim.visualBlock); + return clipCursorToContent(cm, finalHead); + }, + indent: function(cm, args, ranges) { + var vim = cm.state.vim; + var startLine = ranges[0].anchor.line; + var endLine = vim.visualBlock ? + ranges[ranges.length - 1].anchor.line : + ranges[0].head.line; + var repeat = (vim.visualMode) ? args.repeat : 1; + if (args.linewise) { + endLine--; + } + for (var i = startLine; i <= endLine; i++) { + for (var j = 0; j < repeat; j++) { + cm.indentLine(i, args.indentRight); + } + } + return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor); + }, + changeCase: function(cm, args, ranges, oldAnchor, newHead) { + var selections = cm.getSelections(); + var swapped = []; + var toLower = args.toLower; + for (var j = 0; j < selections.length; j++) { + var toSwap = selections[j]; + var text = ''; + if (toLower === true) { + text = toSwap.toLowerCase(); + } else if (toLower === false) { + text = toSwap.toUpperCase(); + } else { + for (var i = 0; i < toSwap.length; i++) { + var character = toSwap.charAt(i); + text += isUpperCase(character) ? character.toLowerCase() : + character.toUpperCase(); + } + } + swapped.push(text); + } + cm.replaceSelections(swapped); + if (args.shouldMoveCursor){ + return newHead; + } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) { + return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor); + } else if (args.linewise){ + return oldAnchor; + } else { + return cursorMin(ranges[0].anchor, ranges[0].head); + } + }, + yank: function(cm, args, ranges, oldAnchor) { + var vim = cm.state.vim; + var text = cm.getSelection(); + var endPos = vim.visualMode + ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor) + : oldAnchor; + vimGlobalState.registerController.pushText( + args.registerName, 'yank', + text, args.linewise, vim.visualBlock); + return endPos; + } + }; + + function defineOperator(name, fn) { + operators[name] = fn; + } + + var actions = { + jumpListWalk: function(cm, actionArgs, vim) { + if (vim.visualMode) { + return; + } + var repeat = actionArgs.repeat; + var forward = actionArgs.forward; + var jumpList = vimGlobalState.jumpList; + + var mark = jumpList.move(cm, forward ? repeat : -repeat); + var markPos = mark ? mark.find() : undefined; + markPos = markPos ? markPos : cm.getCursor(); + cm.setCursor(markPos); + cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch + }, + scroll: function(cm, actionArgs, vim) { + if (vim.visualMode) { + return; + } + var repeat = actionArgs.repeat || 1; + var lineHeight = cm.defaultTextHeight(); + var top = cm.getScrollInfo().top; + var delta = lineHeight * repeat; + var newPos = actionArgs.forward ? top + delta : top - delta; + var cursor = copyCursor(cm.getCursor()); + var cursorCoords = cm.charCoords(cursor, 'local'); + if (actionArgs.forward) { + if (newPos > cursorCoords.top) { + cursor.line += (newPos - cursorCoords.top) / lineHeight; + cursor.line = Math.ceil(cursor.line); + cm.setCursor(cursor); + cursorCoords = cm.charCoords(cursor, 'local'); + cm.scrollTo(null, cursorCoords.top); + } else { + cm.scrollTo(null, newPos); + } + } else { + var newBottom = newPos + cm.getScrollInfo().clientHeight; + if (newBottom < cursorCoords.bottom) { + cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight; + cursor.line = Math.floor(cursor.line); + cm.setCursor(cursor); + cursorCoords = cm.charCoords(cursor, 'local'); + cm.scrollTo( + null, cursorCoords.bottom - cm.getScrollInfo().clientHeight); + } else { + cm.scrollTo(null, newPos); + } + } + }, + scrollToCursor: function(cm, actionArgs) { + var lineNum = cm.getCursor().line; + var charCoords = cm.charCoords(Pos(lineNum, 0), 'local'); + var height = cm.getScrollInfo().clientHeight; + var y = charCoords.top; + var lineHeight = charCoords.bottom - y; + switch (actionArgs.position) { + case 'center': y = y - (height / 2) + lineHeight; + break; + case 'bottom': y = y - height + lineHeight*1.4; + break; + case 'top': y = y + lineHeight*0.4; + break; + } + cm.scrollTo(null, y); + }, + replayMacro: function(cm, actionArgs, vim) { + var registerName = actionArgs.selectedCharacter; + var repeat = actionArgs.repeat; + var macroModeState = vimGlobalState.macroModeState; + if (registerName == '@') { + registerName = macroModeState.latestRegister; + } + while(repeat--){ + executeMacroRegister(cm, vim, macroModeState, registerName); + } + }, + enterMacroRecordMode: function(cm, actionArgs) { + var macroModeState = vimGlobalState.macroModeState; + var registerName = actionArgs.selectedCharacter; + macroModeState.enterMacroRecordMode(cm, registerName); + }, + enterInsertMode: function(cm, actionArgs, vim) { + if (cm.getOption('readOnly')) { return; } + vim.insertMode = true; + vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1; + var insertAt = (actionArgs) ? actionArgs.insertAt : null; + var sel = vim.sel; + var head = actionArgs.head || cm.getCursor('head'); + var height = cm.listSelections().length; + if (insertAt == 'eol') { + head = Pos(head.line, lineLength(cm, head.line)); + } else if (insertAt == 'charAfter') { + head = offsetCursor(head, 0, 1); + } else if (insertAt == 'firstNonBlank') { + head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head); + } else if (insertAt == 'startOfSelectedArea') { + if (!vim.visualBlock) { + if (sel.head.line < sel.anchor.line) { + head = sel.head; + } else { + head = Pos(sel.anchor.line, 0); + } + } else { + head = Pos( + Math.min(sel.head.line, sel.anchor.line), + Math.min(sel.head.ch, sel.anchor.ch)); + height = Math.abs(sel.head.line - sel.anchor.line) + 1; + } + } else if (insertAt == 'endOfSelectedArea') { + if (!vim.visualBlock) { + if (sel.head.line >= sel.anchor.line) { + head = offsetCursor(sel.head, 0, 1); + } else { + head = Pos(sel.anchor.line, 0); + } + } else { + head = Pos( + Math.min(sel.head.line, sel.anchor.line), + Math.max(sel.head.ch + 1, sel.anchor.ch)); + height = Math.abs(sel.head.line - sel.anchor.line) + 1; + } + } else if (insertAt == 'inplace') { + if (vim.visualMode){ + return; + } + } + cm.setOption('keyMap', 'vim-insert'); + cm.setOption('disableInput', false); + if (actionArgs && actionArgs.replace) { + cm.toggleOverwrite(true); + cm.setOption('keyMap', 'vim-replace'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); + } else { + cm.setOption('keyMap', 'vim-insert'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); + } + if (!vimGlobalState.macroModeState.isPlaying) { + cm.on('change', onChange); + CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); + } + if (vim.visualMode) { + exitVisualMode(cm); + } + selectForInsert(cm, head, height); + }, + toggleVisualMode: function(cm, actionArgs, vim) { + var repeat = actionArgs.repeat; + var anchor = cm.getCursor(); + var head; + if (!vim.visualMode) { + vim.visualMode = true; + vim.visualLine = !!actionArgs.linewise; + vim.visualBlock = !!actionArgs.blockwise; + head = clipCursorToContent( + cm, Pos(anchor.line, anchor.ch + repeat - 1), + true /** includeLineBreak */); + vim.sel = { + anchor: anchor, + head: head + }; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); + updateCmSelection(cm); + updateMark(cm, vim, '<', cursorMin(anchor, head)); + updateMark(cm, vim, '>', cursorMax(anchor, head)); + } else if (vim.visualLine ^ actionArgs.linewise || + vim.visualBlock ^ actionArgs.blockwise) { + vim.visualLine = !!actionArgs.linewise; + vim.visualBlock = !!actionArgs.blockwise; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); + updateCmSelection(cm); + } else { + exitVisualMode(cm); + } + }, + reselectLastSelection: function(cm, _actionArgs, vim) { + var lastSelection = vim.lastSelection; + if (vim.visualMode) { + updateLastSelection(cm, vim); + } + if (lastSelection) { + var anchor = lastSelection.anchorMark.find(); + var head = lastSelection.headMark.find(); + if (!anchor || !head) { + return; + } + vim.sel = { + anchor: anchor, + head: head + }; + vim.visualMode = true; + vim.visualLine = lastSelection.visualLine; + vim.visualBlock = lastSelection.visualBlock; + updateCmSelection(cm); + updateMark(cm, vim, '<', cursorMin(anchor, head)); + updateMark(cm, vim, '>', cursorMax(anchor, head)); + CodeMirror.signal(cm, 'vim-mode-change', { + mode: 'visual', + subMode: vim.visualLine ? 'linewise' : + vim.visualBlock ? 'blockwise' : ''}); + } + }, + joinLines: function(cm, actionArgs, vim) { + var curStart, curEnd; + if (vim.visualMode) { + curStart = cm.getCursor('anchor'); + curEnd = cm.getCursor('head'); + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curEnd; + curEnd = curStart; + curStart = tmp; + } + curEnd.ch = lineLength(cm, curEnd.line) - 1; + } else { + var repeat = Math.max(actionArgs.repeat, 2); + curStart = cm.getCursor(); + curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1, + Infinity)); + } + var finalCh = 0; + for (var i = curStart.line; i < curEnd.line; i++) { + finalCh = lineLength(cm, curStart.line); + var tmp = Pos(curStart.line + 1, + lineLength(cm, curStart.line + 1)); + var text = cm.getRange(curStart, tmp); + text = text.replace(/\n\s*/g, ' '); + cm.replaceRange(text, curStart, tmp); + } + var curFinalPos = Pos(curStart.line, finalCh); + if (vim.visualMode) { + exitVisualMode(cm, false); + } + cm.setCursor(curFinalPos); + }, + newLineAndEnterInsertMode: function(cm, actionArgs, vim) { + vim.insertMode = true; + var insertAt = copyCursor(cm.getCursor()); + if (insertAt.line === cm.firstLine() && !actionArgs.after) { + cm.replaceRange('\n', Pos(cm.firstLine(), 0)); + cm.setCursor(cm.firstLine(), 0); + } else { + insertAt.line = (actionArgs.after) ? insertAt.line : + insertAt.line - 1; + insertAt.ch = lineLength(cm, insertAt.line); + cm.setCursor(insertAt); + var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + newlineFn(cm); + } + this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim); + }, + paste: function(cm, actionArgs, vim) { + var cur = copyCursor(cm.getCursor()); + var register = vimGlobalState.registerController.getRegister( + actionArgs.registerName); + var text = register.toString(); + if (!text) { + return; + } + if (actionArgs.matchIndent) { + var tabSize = cm.getOption("tabSize"); + var whitespaceLength = function(str) { + var tabs = (str.split("\t").length - 1); + var spaces = (str.split(" ").length - 1); + return tabs * tabSize + spaces * 1; + }; + var currentLine = cm.getLine(cm.getCursor().line); + var indent = whitespaceLength(currentLine.match(/^\s*/)[0]); + var chompedText = text.replace(/\n$/, ''); + var wasChomped = text !== chompedText; + var firstIndent = whitespaceLength(text.match(/^\s*/)[0]); + var text = chompedText.replace(/^\s*/gm, function(wspace) { + var newIndent = indent + (whitespaceLength(wspace) - firstIndent); + if (newIndent < 0) { + return ""; + } + else if (cm.getOption("indentWithTabs")) { + var quotient = Math.floor(newIndent / tabSize); + return Array(quotient + 1).join('\t'); + } + else { + return Array(newIndent + 1).join(' '); + } + }); + text += wasChomped ? "\n" : ""; + } + if (actionArgs.repeat > 1) { + var text = Array(actionArgs.repeat + 1).join(text); + } + var linewise = register.linewise; + var blockwise = register.blockwise; + if (linewise && !blockwise) { + if(vim.visualMode) { + text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n'; + } else if (actionArgs.after) { + text = '\n' + text.slice(0, text.length - 1); + cur.ch = lineLength(cm, cur.line); + } else { + cur.ch = 0; + } + } else { + if (blockwise) { + text = text.split('\n'); + for (var i = 0; i < text.length; i++) { + text[i] = (text[i] == '') ? ' ' : text[i]; + } + } + cur.ch += actionArgs.after ? 1 : 0; + } + var curPosFinal; + var idx; + if (vim.visualMode) { + vim.lastPastedText = text; + var lastSelectionCurEnd; + var selectedArea = getSelectedAreaRange(cm, vim); + var selectionStart = selectedArea[0]; + var selectionEnd = selectedArea[1]; + var selectedText = cm.getSelection(); + var selections = cm.listSelections(); + var emptyStrings = new Array(selections.length).join('1').split('1'); + if (vim.lastSelection) { + lastSelectionCurEnd = vim.lastSelection.headMark.find(); + } + vimGlobalState.registerController.unnamedRegister.setText(selectedText); + if (blockwise) { + cm.replaceSelections(emptyStrings); + selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch); + cm.setCursor(selectionStart); + selectBlock(cm, selectionEnd); + cm.replaceSelections(text); + curPosFinal = selectionStart; + } else if (vim.visualBlock) { + cm.replaceSelections(emptyStrings); + cm.setCursor(selectionStart); + cm.replaceRange(text, selectionStart, selectionStart); + curPosFinal = selectionStart; + } else { + cm.replaceRange(text, selectionStart, selectionEnd); + curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1); + } + if(lastSelectionCurEnd) { + vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd); + } + if (linewise) { + curPosFinal.ch=0; + } + } else { + if (blockwise) { + cm.setCursor(cur); + for (var i = 0; i < text.length; i++) { + var line = cur.line+i; + if (line > cm.lastLine()) { + cm.replaceRange('\n', Pos(line, 0)); + } + var lastCh = lineLength(cm, line); + if (lastCh < cur.ch) { + extendLineToColumn(cm, line, cur.ch); + } + } + cm.setCursor(cur); + selectBlock(cm, Pos(cur.line + text.length-1, cur.ch)); + cm.replaceSelections(text); + curPosFinal = cur; + } else { + cm.replaceRange(text, cur); + if (linewise && actionArgs.after) { + curPosFinal = Pos( + cur.line + 1, + findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1))); + } else if (linewise && !actionArgs.after) { + curPosFinal = Pos( + cur.line, + findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line))); + } else if (!linewise && actionArgs.after) { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length - 1); + } else { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length); + } + } + } + if (vim.visualMode) { + exitVisualMode(cm, false); + } + cm.setCursor(curPosFinal); + }, + undo: function(cm, actionArgs) { + cm.operation(function() { + repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); + cm.setCursor(cm.getCursor('anchor')); + }); + }, + redo: function(cm, actionArgs) { + repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); + }, + setRegister: function(_cm, actionArgs, vim) { + vim.inputState.registerName = actionArgs.selectedCharacter; + }, + setMark: function(cm, actionArgs, vim) { + var markName = actionArgs.selectedCharacter; + updateMark(cm, vim, markName, cm.getCursor()); + }, + replace: function(cm, actionArgs, vim) { + var replaceWith = actionArgs.selectedCharacter; + var curStart = cm.getCursor(); + var replaceTo; + var curEnd; + var selections = cm.listSelections(); + if (vim.visualMode) { + curStart = cm.getCursor('start'); + curEnd = cm.getCursor('end'); + } else { + var line = cm.getLine(curStart.line); + replaceTo = curStart.ch + actionArgs.repeat; + if (replaceTo > line.length) { + replaceTo=line.length; + } + curEnd = Pos(curStart.line, replaceTo); + } + if (replaceWith=='\n') { + if (!vim.visualMode) cm.replaceRange('', curStart, curEnd); + (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm); + } else { + var replaceWithStr = cm.getRange(curStart, curEnd); + replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith); + if (vim.visualBlock) { + var spaces = new Array(cm.getOption("tabSize")+1).join(' '); + replaceWithStr = cm.getSelection(); + replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n'); + cm.replaceSelections(replaceWithStr); + } else { + cm.replaceRange(replaceWithStr, curStart, curEnd); + } + if (vim.visualMode) { + curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ? + selections[0].anchor : selections[0].head; + cm.setCursor(curStart); + exitVisualMode(cm, false); + } else { + cm.setCursor(offsetCursor(curEnd, 0, -1)); + } + } + }, + incrementNumberToken: function(cm, actionArgs) { + var cur = cm.getCursor(); + var lineStr = cm.getLine(cur.line); + var re = /-?\d+/g; + var match; + var start; + var end; + var numberStr; + var token; + while ((match = re.exec(lineStr)) !== null) { + token = match[0]; + start = match.index; + end = start + token.length; + if (cur.ch < end)break; + } + if (!actionArgs.backtrack && (end <= cur.ch))return; + if (token) { + var increment = actionArgs.increase ? 1 : -1; + var number = parseInt(token) + (increment * actionArgs.repeat); + var from = Pos(cur.line, start); + var to = Pos(cur.line, end); + numberStr = number.toString(); + cm.replaceRange(numberStr, from, to); + } else { + return; + } + cm.setCursor(Pos(cur.line, start + numberStr.length - 1)); + }, + repeatLastEdit: function(cm, actionArgs, vim) { + var lastEditInputState = vim.lastEditInputState; + if (!lastEditInputState) { return; } + var repeat = actionArgs.repeat; + if (repeat && actionArgs.repeatIsExplicit) { + vim.lastEditInputState.repeatOverride = repeat; + } else { + repeat = vim.lastEditInputState.repeatOverride || repeat; + } + repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */); + }, + exitInsertMode: exitInsertMode + }; + + function defineAction(name, fn) { + actions[name] = fn; + } + function clipCursorToContent(cm, cur, includeLineBreak) { + var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() ); + var maxCh = lineLength(cm, line) - 1; + maxCh = (includeLineBreak) ? maxCh + 1 : maxCh; + var ch = Math.min(Math.max(0, cur.ch), maxCh); + return Pos(line, ch); + } + function copyArgs(args) { + var ret = {}; + for (var prop in args) { + if (args.hasOwnProperty(prop)) { + ret[prop] = args[prop]; + } + } + return ret; + } + function offsetCursor(cur, offsetLine, offsetCh) { + if (typeof offsetLine === 'object') { + offsetCh = offsetLine.ch; + offsetLine = offsetLine.line; + } + return Pos(cur.line + offsetLine, cur.ch + offsetCh); + } + function getOffset(anchor, head) { + return { + line: head.line - anchor.line, + ch: head.line - anchor.line + }; + } + function commandMatches(keys, keyMap, context, inputState) { + var match, partial = [], full = []; + for (var i = 0; i < keyMap.length; i++) { + var command = keyMap[i]; + if (context == 'insert' && command.context != 'insert' || + command.context && command.context != context || + inputState.operator && command.type == 'action' || + !(match = commandMatch(keys, command.keys))) { continue; } + if (match == 'partial') { partial.push(command); } + if (match == 'full') { full.push(command); } + } + return { + partial: partial.length && partial, + full: full.length && full + }; + } + function commandMatch(pressed, mapped) { + if (mapped.slice(-11) == '') { + var prefixLen = mapped.length - 11; + var pressedPrefix = pressed.slice(0, prefixLen); + var mappedPrefix = mapped.slice(0, prefixLen); + return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' : + mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false; + } else { + return pressed == mapped ? 'full' : + mapped.indexOf(pressed) == 0 ? 'partial' : false; + } + } + function lastChar(keys) { + var match = /^.*(<[\w\-]+>)$/.exec(keys); + var selectedCharacter = match ? match[1] : keys.slice(-1); + if (selectedCharacter.length > 1){ + switch(selectedCharacter){ + case '': + selectedCharacter='\n'; + break; + case '': + selectedCharacter=' '; + break; + default: + break; + } + } + return selectedCharacter; + } + function repeatFn(cm, fn, repeat) { + return function() { + for (var i = 0; i < repeat; i++) { + fn(cm); + } + }; + } + function copyCursor(cur) { + return Pos(cur.line, cur.ch); + } + function cursorEqual(cur1, cur2) { + return cur1.ch == cur2.ch && cur1.line == cur2.line; + } + function cursorIsBefore(cur1, cur2) { + if (cur1.line < cur2.line) { + return true; + } + if (cur1.line == cur2.line && cur1.ch < cur2.ch) { + return true; + } + return false; + } + function cursorMin(cur1, cur2) { + if (arguments.length > 2) { + cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1)); + } + return cursorIsBefore(cur1, cur2) ? cur1 : cur2; + } + function cursorMax(cur1, cur2) { + if (arguments.length > 2) { + cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1)); + } + return cursorIsBefore(cur1, cur2) ? cur2 : cur1; + } + function cursorIsBetween(cur1, cur2, cur3) { + var cur1before2 = cursorIsBefore(cur1, cur2); + var cur2before3 = cursorIsBefore(cur2, cur3); + return cur1before2 && cur2before3; + } + function lineLength(cm, lineNum) { + return cm.getLine(lineNum).length; + } + function trim(s) { + if (s.trim) { + return s.trim(); + } + return s.replace(/^\s+|\s+$/g, ''); + } + function escapeRegex(s) { + return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1'); + } + function extendLineToColumn(cm, lineNum, column) { + var endCh = lineLength(cm, lineNum); + var spaces = new Array(column-endCh+1).join(' '); + cm.setCursor(Pos(lineNum, endCh)); + cm.replaceRange(spaces, cm.getCursor()); + } + function selectBlock(cm, selectionEnd) { + var selections = [], ranges = cm.listSelections(); + var head = copyCursor(cm.clipPos(selectionEnd)); + var isClipped = !cursorEqual(selectionEnd, head); + var curHead = cm.getCursor('head'); + var primIndex = getIndex(ranges, curHead); + var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor); + var max = ranges.length - 1; + var index = max - primIndex > primIndex ? max : 0; + var base = ranges[index].anchor; + + var firstLine = Math.min(base.line, head.line); + var lastLine = Math.max(base.line, head.line); + var baseCh = base.ch, headCh = head.ch; + + var dir = ranges[index].head.ch - baseCh; + var newDir = headCh - baseCh; + if (dir > 0 && newDir <= 0) { + baseCh++; + if (!isClipped) { headCh--; } + } else if (dir < 0 && newDir >= 0) { + baseCh--; + if (!wasClipped) { headCh++; } + } else if (dir < 0 && newDir == -1) { + baseCh--; + headCh++; + } + for (var line = firstLine; line <= lastLine; line++) { + var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)}; + selections.push(range); + } + primIndex = head.line == lastLine ? selections.length - 1 : 0; + cm.setSelections(selections); + selectionEnd.ch = headCh; + base.ch = baseCh; + return base; + } + function selectForInsert(cm, head, height) { + var sel = []; + for (var i = 0; i < height; i++) { + var lineHead = offsetCursor(head, i, 0); + sel.push({anchor: lineHead, head: lineHead}); + } + cm.setSelections(sel, 0); + } + function getIndex(ranges, cursor, end) { + for (var i = 0; i < ranges.length; i++) { + var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor); + var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor); + if (atAnchor || atHead) { + return i; + } + } + return -1; + } + function getSelectedAreaRange(cm, vim) { + var lastSelection = vim.lastSelection; + var getCurrentSelectedAreaRange = function() { + var selections = cm.listSelections(); + var start = selections[0]; + var end = selections[selections.length-1]; + var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head; + var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor; + return [selectionStart, selectionEnd]; + }; + var getLastSelectedAreaRange = function() { + var selectionStart = cm.getCursor(); + var selectionEnd = cm.getCursor(); + var block = lastSelection.visualBlock; + if (block) { + var width = block.width; + var height = block.height; + selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width); + var selections = []; + for (var i = selectionStart.line; i < selectionEnd.line; i++) { + var anchor = Pos(i, selectionStart.ch); + var head = Pos(i, selectionEnd.ch); + var range = {anchor: anchor, head: head}; + selections.push(range); + } + cm.setSelections(selections); + } else { + var start = lastSelection.anchorMark.find(); + var end = lastSelection.headMark.find(); + var line = end.line - start.line; + var ch = end.ch - start.ch; + selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch}; + if (lastSelection.visualLine) { + selectionStart = Pos(selectionStart.line, 0); + selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line)); + } + cm.setSelection(selectionStart, selectionEnd); + } + return [selectionStart, selectionEnd]; + }; + if (!vim.visualMode) { + return getLastSelectedAreaRange(); + } else { + return getCurrentSelectedAreaRange(); + } + } + function updateLastSelection(cm, vim) { + var anchor = vim.sel.anchor; + var head = vim.sel.head; + if (vim.lastPastedText) { + head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length); + vim.lastPastedText = null; + } + vim.lastSelection = {'anchorMark': cm.setBookmark(anchor), + 'headMark': cm.setBookmark(head), + 'anchor': copyCursor(anchor), + 'head': copyCursor(head), + 'visualMode': vim.visualMode, + 'visualLine': vim.visualLine, + 'visualBlock': vim.visualBlock}; + } + function expandSelection(cm, start, end) { + var sel = cm.state.vim.sel; + var head = sel.head; + var anchor = sel.anchor; + var tmp; + if (cursorIsBefore(end, start)) { + tmp = end; + end = start; + start = tmp; + } + if (cursorIsBefore(head, anchor)) { + head = cursorMin(start, head); + anchor = cursorMax(anchor, end); + } else { + anchor = cursorMin(start, anchor); + head = cursorMax(head, end); + head = offsetCursor(head, 0, -1); + if (head.ch == -1 && head.line != cm.firstLine()) { + head = Pos(head.line - 1, lineLength(cm, head.line - 1)); + } + } + return [anchor, head]; + } + function updateCmSelection(cm, sel, mode) { + var vim = cm.state.vim; + sel = sel || vim.sel; + var mode = mode || + vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char'; + var cmSel = makeCmSelection(cm, sel, mode); + cm.setSelections(cmSel.ranges, cmSel.primary); + updateFakeCursor(cm); + } + function makeCmSelection(cm, sel, mode, exclusive) { + var head = copyCursor(sel.head); + var anchor = copyCursor(sel.anchor); + if (mode == 'char') { + var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; + var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; + head = offsetCursor(sel.head, 0, headOffset); + anchor = offsetCursor(sel.anchor, 0, anchorOffset); + return { + ranges: [{anchor: anchor, head: head}], + primary: 0 + }; + } else if (mode == 'line') { + if (!cursorIsBefore(sel.head, sel.anchor)) { + anchor.ch = 0; + + var lastLine = cm.lastLine(); + if (head.line > lastLine) { + head.line = lastLine; + } + head.ch = lineLength(cm, head.line); + } else { + head.ch = 0; + anchor.ch = lineLength(cm, anchor.line); + } + return { + ranges: [{anchor: anchor, head: head}], + primary: 0 + }; + } else if (mode == 'block') { + var top = Math.min(anchor.line, head.line), + left = Math.min(anchor.ch, head.ch), + bottom = Math.max(anchor.line, head.line), + right = Math.max(anchor.ch, head.ch) + 1; + var height = bottom - top + 1; + var primary = head.line == top ? 0 : height - 1; + var ranges = []; + for (var i = 0; i < height; i++) { + ranges.push({ + anchor: Pos(top + i, left), + head: Pos(top + i, right) + }); + } + return { + ranges: ranges, + primary: primary + }; + } + } + function getHead(cm) { + var cur = cm.getCursor('head'); + if (cm.getSelection().length == 1) { + cur = cursorMin(cur, cm.getCursor('anchor')); + } + return cur; + } + function exitVisualMode(cm, moveHead) { + var vim = cm.state.vim; + if (moveHead !== false) { + cm.setCursor(clipCursorToContent(cm, vim.sel.head)); + } + updateLastSelection(cm, vim); + vim.visualMode = false; + vim.visualLine = false; + vim.visualBlock = false; + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + if (vim.fakeCursor) { + vim.fakeCursor.clear(); + } + } + function clipToLine(cm, curStart, curEnd) { + var selection = cm.getRange(curStart, curEnd); + if (/\n\s*$/.test(selection)) { + var lines = selection.split('\n'); + lines.pop(); + var line; + for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) { + curEnd.line--; + curEnd.ch = 0; + } + if (line) { + curEnd.line--; + curEnd.ch = lineLength(cm, curEnd.line); + } else { + curEnd.ch = 0; + } + } + } + function expandSelectionToLine(_cm, curStart, curEnd) { + curStart.ch = 0; + curEnd.ch = 0; + curEnd.line++; + } + + function findFirstNonWhiteSpaceCharacter(text) { + if (!text) { + return 0; + } + var firstNonWS = text.search(/\S/); + return firstNonWS == -1 ? text.length : firstNonWS; + } + + function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) { + var cur = getHead(cm); + var line = cm.getLine(cur.line); + var idx = cur.ch; + var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0]; + while (!test(line.charAt(idx))) { + idx++; + if (idx >= line.length) { return null; } + } + + if (bigWord) { + test = bigWordCharTest[0]; + } else { + test = wordCharTest[0]; + if (!test(line.charAt(idx))) { + test = wordCharTest[1]; + } + } + + var end = idx, start = idx; + while (test(line.charAt(end)) && end < line.length) { end++; } + while (test(line.charAt(start)) && start >= 0) { start--; } + start++; + + if (inclusive) { + var wordEnd = end; + while (/\s/.test(line.charAt(end)) && end < line.length) { end++; } + if (wordEnd == end) { + var wordStart = start; + while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; } + if (!start) { start = wordStart; } + } + } + return { start: Pos(cur.line, start), end: Pos(cur.line, end) }; + } + + function recordJumpPosition(cm, oldCur, newCur) { + if (!cursorEqual(oldCur, newCur)) { + vimGlobalState.jumpList.add(cm, oldCur, newCur); + } + } + + function recordLastCharacterSearch(increment, args) { + vimGlobalState.lastChararacterSearch.increment = increment; + vimGlobalState.lastChararacterSearch.forward = args.forward; + vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter; + } + + var symbolToMode = { + '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket', + '[': 'section', ']': 'section', + '*': 'comment', '/': 'comment', + 'm': 'method', 'M': 'method', + '#': 'preprocess' + }; + var findSymbolModes = { + bracket: { + isComplete: function(state) { + if (state.nextCh === state.symb) { + state.depth++; + if (state.depth >= 1)return true; + } else if (state.nextCh === state.reverseSymb) { + state.depth--; + } + return false; + } + }, + section: { + init: function(state) { + state.curMoveThrough = true; + state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}'; + }, + isComplete: function(state) { + return state.index === 0 && state.nextCh === state.symb; + } + }, + comment: { + isComplete: function(state) { + var found = state.lastCh === '*' && state.nextCh === '/'; + state.lastCh = state.nextCh; + return found; + } + }, + method: { + init: function(state) { + state.symb = (state.symb === 'm' ? '{' : '}'); + state.reverseSymb = state.symb === '{' ? '}' : '{'; + }, + isComplete: function(state) { + if (state.nextCh === state.symb)return true; + return false; + } + }, + preprocess: { + init: function(state) { + state.index = 0; + }, + isComplete: function(state) { + if (state.nextCh === '#') { + var token = state.lineText.match(/#(\w+)/)[1]; + if (token === 'endif') { + if (state.forward && state.depth === 0) { + return true; + } + state.depth++; + } else if (token === 'if') { + if (!state.forward && state.depth === 0) { + return true; + } + state.depth--; + } + if (token === 'else' && state.depth === 0)return true; + } + return false; + } + } + }; + function findSymbol(cm, repeat, forward, symb) { + var cur = copyCursor(cm.getCursor()); + var increment = forward ? 1 : -1; + var endLine = forward ? cm.lineCount() : -1; + var curCh = cur.ch; + var line = cur.line; + var lineText = cm.getLine(line); + var state = { + lineText: lineText, + nextCh: lineText.charAt(curCh), + lastCh: null, + index: curCh, + symb: symb, + reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb], + forward: forward, + depth: 0, + curMoveThrough: false + }; + var mode = symbolToMode[symb]; + if (!mode)return cur; + var init = findSymbolModes[mode].init; + var isComplete = findSymbolModes[mode].isComplete; + if (init) { init(state); } + while (line !== endLine && repeat) { + state.index += increment; + state.nextCh = state.lineText.charAt(state.index); + if (!state.nextCh) { + line += increment; + state.lineText = cm.getLine(line) || ''; + if (increment > 0) { + state.index = 0; + } else { + var lineLen = state.lineText.length; + state.index = (lineLen > 0) ? (lineLen-1) : 0; + } + state.nextCh = state.lineText.charAt(state.index); + } + if (isComplete(state)) { + cur.line = line; + cur.ch = state.index; + repeat--; + } + } + if (state.nextCh || state.curMoveThrough) { + return Pos(line, state.index); + } + return cur; + } + function findWord(cm, cur, forward, bigWord, emptyLineIsWord) { + var lineNum = cur.line; + var pos = cur.ch; + var line = cm.getLine(lineNum); + var dir = forward ? 1 : -1; + var charTests = bigWord ? bigWordCharTest: wordCharTest; + + if (emptyLineIsWord && line == '') { + lineNum += dir; + line = cm.getLine(lineNum); + if (!isLine(cm, lineNum)) { + return null; + } + pos = (forward) ? 0 : line.length; + } + + while (true) { + if (emptyLineIsWord && line == '') { + return { from: 0, to: 0, line: lineNum }; + } + var stop = (dir > 0) ? line.length : -1; + var wordStart = stop, wordEnd = stop; + while (pos != stop) { + var foundWord = false; + for (var i = 0; i < charTests.length && !foundWord; ++i) { + if (charTests[i](line.charAt(pos))) { + wordStart = pos; + while (pos != stop && charTests[i](line.charAt(pos))) { + pos += dir; + } + wordEnd = pos; + foundWord = wordStart != wordEnd; + if (wordStart == cur.ch && lineNum == cur.line && + wordEnd == wordStart + dir) { + continue; + } else { + return { + from: Math.min(wordStart, wordEnd + 1), + to: Math.max(wordStart, wordEnd), + line: lineNum }; + } + } + } + if (!foundWord) { + pos += dir; + } + } + lineNum += dir; + if (!isLine(cm, lineNum)) { + return null; + } + line = cm.getLine(lineNum); + pos = (dir > 0) ? 0 : line.length; + } + throw new Error('The impossible happened.'); + } + function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) { + var curStart = copyCursor(cur); + var words = []; + if (forward && !wordEnd || !forward && wordEnd) { + repeat++; + } + var emptyLineIsWord = !(forward && wordEnd); + for (var i = 0; i < repeat; i++) { + var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord); + if (!word) { + var eodCh = lineLength(cm, cm.lastLine()); + words.push(forward + ? {line: cm.lastLine(), from: eodCh, to: eodCh} + : {line: 0, from: 0, to: 0}); + break; + } + words.push(word); + cur = Pos(word.line, forward ? (word.to - 1) : word.from); + } + var shortCircuit = words.length != repeat; + var firstWord = words[0]; + var lastWord = words.pop(); + if (forward && !wordEnd) { + if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) { + lastWord = words.pop(); + } + return Pos(lastWord.line, lastWord.from); + } else if (forward && wordEnd) { + return Pos(lastWord.line, lastWord.to - 1); + } else if (!forward && wordEnd) { + if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) { + lastWord = words.pop(); + } + return Pos(lastWord.line, lastWord.to); + } else { + return Pos(lastWord.line, lastWord.from); + } + } + + function moveToCharacter(cm, repeat, forward, character) { + var cur = cm.getCursor(); + var start = cur.ch; + var idx; + for (var i = 0; i < repeat; i ++) { + var line = cm.getLine(cur.line); + idx = charIdxInLine(start, line, character, forward, true); + if (idx == -1) { + return null; + } + start = idx; + } + return Pos(cm.getCursor().line, idx); + } + + function moveToColumn(cm, repeat) { + var line = cm.getCursor().line; + return clipCursorToContent(cm, Pos(line, repeat - 1)); + } + + function updateMark(cm, vim, markName, pos) { + if (!inArray(markName, validMarks)) { + return; + } + if (vim.marks[markName]) { + vim.marks[markName].clear(); + } + vim.marks[markName] = cm.setBookmark(pos); + } + + function charIdxInLine(start, line, character, forward, includeChar) { + var idx; + if (forward) { + idx = line.indexOf(character, start + 1); + if (idx != -1 && !includeChar) { + idx -= 1; + } + } else { + idx = line.lastIndexOf(character, start - 1); + if (idx != -1 && !includeChar) { + idx += 1; + } + } + return idx; + } + + function findParagraph(cm, head, repeat, dir, inclusive) { + var line = head.line; + var min = cm.firstLine(); + var max = cm.lastLine(); + var start, end, i = line; + function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch + function isBoundary(i, dir, any) { + if (any) { return isEmpty(i) != isEmpty(i + dir); } + return !isEmpty(i) && isEmpty(i + dir); + } + function skipFold(i) { + dir = dir > 0 ? 1 : -1; + var foldLine = cm.ace.session.getFoldLine(i); + if (foldLine) { + if (i + dir > foldLine.start.row && i + dir < foldLine.end.row) + dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i; + } + } + if (dir) { + while (min <= i && i <= max && repeat > 0) { + skipFold(i); + if (isBoundary(i, dir)) { repeat--; } + i += dir; + } + return new Pos(i, 0); + } + + var vim = cm.state.vim; + if (vim.visualLine && isBoundary(line, 1, true)) { + var anchor = vim.sel.anchor; + if (isBoundary(anchor.line, -1, true)) { + if (!inclusive || anchor.line != line) { + line += 1; + } + } + } + var startState = isEmpty(line); + for (i = line; i <= max && repeat; i++) { + if (isBoundary(i, 1, true)) { + if (!inclusive || isEmpty(i) != startState) { + repeat--; + } + } + } + end = new Pos(i, 0); + if (i > max && !startState) { startState = true; } + else { inclusive = false; } + for (i = line; i > min; i--) { + if (!inclusive || isEmpty(i) == startState || i == line) { + if (isBoundary(i, -1, true)) { break; } + } + } + start = new Pos(i, 0); + return { start: start, end: end }; + } + function selectCompanionObject(cm, head, symb, inclusive) { + var cur = head, start, end; + + var bracketRegexp = ({ + '(': /[()]/, ')': /[()]/, + '[': /[[\]]/, ']': /[[\]]/, + '{': /[{}]/, '}': /[{}]/})[symb]; + var openSym = ({ + '(': '(', ')': '(', + '[': '[', ']': '[', + '{': '{', '}': '{'})[symb]; + var curChar = cm.getLine(cur.line).charAt(cur.ch); + var offset = curChar === openSym ? 1 : 0; + + start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp}); + end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp}); + + if (!start || !end) { + return { start: cur, end: cur }; + } + + start = start.pos; + end = end.pos; + + if ((start.line == end.line && start.ch > end.ch) + || (start.line > end.line)) { + var tmp = start; + start = end; + end = tmp; + } + + if (inclusive) { + end.ch += 1; + } else { + start.ch += 1; + } + + return { start: start, end: end }; + } + function findBeginningAndEnd(cm, head, symb, inclusive) { + var cur = copyCursor(head); + var line = cm.getLine(cur.line); + var chars = line.split(''); + var start, end, i, len; + var firstIndex = chars.indexOf(symb); + if (cur.ch < firstIndex) { + cur.ch = firstIndex; + } + else if (firstIndex < cur.ch && chars[cur.ch] == symb) { + end = cur.ch; // assign end to the current cursor + --cur.ch; // make sure to look backwards + } + if (chars[cur.ch] == symb && !end) { + start = cur.ch + 1; // assign start to ahead of the cursor + } else { + for (i = cur.ch; i > -1 && !start; i--) { + if (chars[i] == symb) { + start = i + 1; + } + } + } + if (start && !end) { + for (i = start, len = chars.length; i < len && !end; i++) { + if (chars[i] == symb) { + end = i; + } + } + } + if (!start || !end) { + return { start: cur, end: cur }; + } + if (inclusive) { + --start; ++end; + } + + return { + start: Pos(cur.line, start), + end: Pos(cur.line, end) + }; + } + defineOption('pcre', true, 'boolean'); + function SearchState() {} + SearchState.prototype = { + getQuery: function() { + return vimGlobalState.query; + }, + setQuery: function(query) { + vimGlobalState.query = query; + }, + getOverlay: function() { + return this.searchOverlay; + }, + setOverlay: function(overlay) { + this.searchOverlay = overlay; + }, + isReversed: function() { + return vimGlobalState.isReversed; + }, + setReversed: function(reversed) { + vimGlobalState.isReversed = reversed; + }, + getScrollbarAnnotate: function() { + return this.annotate; + }, + setScrollbarAnnotate: function(annotate) { + this.annotate = annotate; + } + }; + function getSearchState(cm) { + var vim = cm.state.vim; + return vim.searchState_ || (vim.searchState_ = new SearchState()); + } + function dialog(cm, template, shortText, onClose, options) { + if (cm.openDialog) { + cm.openDialog(template, onClose, { bottom: true, value: options.value, + onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp, + selectValueOnOpen: false}); + } + else { + onClose(prompt(shortText, '')); + } + } + function splitBySlash(argString) { + var slashes = findUnescapedSlashes(argString) || []; + if (!slashes.length) return []; + var tokens = []; + if (slashes[0] !== 0) return; + for (var i = 0; i < slashes.length; i++) { + if (typeof slashes[i] == 'number') + tokens.push(argString.substring(slashes[i] + 1, slashes[i+1])); + } + return tokens; + } + + function findUnescapedSlashes(str) { + var escapeNextChar = false; + var slashes = []; + for (var i = 0; i < str.length; i++) { + var c = str.charAt(i); + if (!escapeNextChar && c == '/') { + slashes.push(i); + } + escapeNextChar = !escapeNextChar && (c == '\\'); + } + return slashes; + } + function translateRegex(str) { + var specials = '|(){'; + var unescape = '}'; + var escapeNextChar = false; + var out = []; + for (var i = -1; i < str.length; i++) { + var c = str.charAt(i) || ''; + var n = str.charAt(i+1) || ''; + var specialComesNext = (n && specials.indexOf(n) != -1); + if (escapeNextChar) { + if (c !== '\\' || !specialComesNext) { + out.push(c); + } + escapeNextChar = false; + } else { + if (c === '\\') { + escapeNextChar = true; + if (n && unescape.indexOf(n) != -1) { + specialComesNext = true; + } + if (!specialComesNext || n === '\\') { + out.push(c); + } + } else { + out.push(c); + if (specialComesNext && n !== '\\') { + out.push('\\'); + } + } + } + } + return out.join(''); + } + var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'}; + function translateRegexReplace(str) { + var escapeNextChar = false; + var out = []; + for (var i = -1; i < str.length; i++) { + var c = str.charAt(i) || ''; + var n = str.charAt(i+1) || ''; + if (charUnescapes[c + n]) { + out.push(charUnescapes[c+n]); + i++; + } else if (escapeNextChar) { + out.push(c); + escapeNextChar = false; + } else { + if (c === '\\') { + escapeNextChar = true; + if ((isNumber(n) || n === '$')) { + out.push('$'); + } else if (n !== '/' && n !== '\\') { + out.push('\\'); + } + } else { + if (c === '$') { + out.push('$'); + } + out.push(c); + if (n === '/') { + out.push('\\'); + } + } + } + } + return out.join(''); + } + var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'}; + function unescapeRegexReplace(str) { + var stream = new CodeMirror.StringStream(str); + var output = []; + while (!stream.eol()) { + while (stream.peek() && stream.peek() != '\\') { + output.push(stream.next()); + } + var matched = false; + for (var matcher in unescapes) { + if (stream.match(matcher, true)) { + matched = true; + output.push(unescapes[matcher]); + break; + } + } + if (!matched) { + output.push(stream.next()); + } + } + return output.join(''); + } + function parseQuery(query, ignoreCase, smartCase) { + var lastSearchRegister = vimGlobalState.registerController.getRegister('/'); + lastSearchRegister.setText(query); + if (query instanceof RegExp) { return query; } + var slashes = findUnescapedSlashes(query); + var regexPart; + var forceIgnoreCase; + if (!slashes.length) { + regexPart = query; + } else { + regexPart = query.substring(0, slashes[0]); + var flagsPart = query.substring(slashes[0]); + forceIgnoreCase = (flagsPart.indexOf('i') != -1); + } + if (!regexPart) { + return null; + } + if (!getOption('pcre')) { + regexPart = translateRegex(regexPart); + } + if (smartCase) { + ignoreCase = (/^[^A-Z]*$/).test(regexPart); + } + var regexp = new RegExp(regexPart, + (ignoreCase || forceIgnoreCase) ? 'i' : undefined); + return regexp; + } + function showConfirm(cm, text) { + if (cm.openNotification) { + cm.openNotification('' + text + '', + {bottom: true, duration: 5000}); + } else { + alert(text); + } + } + function makePrompt(prefix, desc) { + var raw = ''; + if (prefix) { + raw += '' + prefix + ''; + } + raw += ' ' + + ''; + if (desc) { + raw += ''; + raw += desc; + raw += ''; + } + return raw; + } + var searchPromptDesc = '(Javascript regexp)'; + function showPrompt(cm, options) { + var shortText = (options.prefix || '') + ' ' + (options.desc || ''); + var prompt = makePrompt(options.prefix, options.desc); + dialog(cm, prompt, shortText, options.onClose, options); + } + function regexEqual(r1, r2) { + if (r1 instanceof RegExp && r2 instanceof RegExp) { + var props = ['global', 'multiline', 'ignoreCase', 'source']; + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (r1[prop] !== r2[prop]) { + return false; + } + } + return true; + } + return false; + } + function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { + if (!rawQuery) { + return; + } + var state = getSearchState(cm); + var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase); + if (!query) { + return; + } + highlightSearchMatches(cm, query); + if (regexEqual(query, state.getQuery())) { + return query; + } + state.setQuery(query); + return query; + } + function searchOverlay(query) { + if (query.source.charAt(0) == '^') { + var matchSol = true; + } + return { + token: function(stream) { + if (matchSol && !stream.sol()) { + stream.skipToEnd(); + return; + } + var match = stream.match(query, false); + if (match) { + if (match[0].length == 0) { + stream.next(); + return 'searching'; + } + if (!stream.sol()) { + stream.backUp(1); + if (!query.exec(stream.next() + match[0])) { + stream.next(); + return null; + } + } + stream.match(query); + return 'searching'; + } + while (!stream.eol()) { + stream.next(); + if (stream.match(query, false)) break; + } + }, + query: query + }; + } + function highlightSearchMatches(cm, query) { + var searchState = getSearchState(cm); + var overlay = searchState.getOverlay(); + if (!overlay || query != overlay.query) { + if (overlay) { + cm.removeOverlay(overlay); + } + overlay = searchOverlay(query); + cm.addOverlay(overlay); + if (cm.showMatchesOnScrollbar) { + if (searchState.getScrollbarAnnotate()) { + searchState.getScrollbarAnnotate().clear(); + } + searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query)); + } + searchState.setOverlay(overlay); + } + } + function findNext(cm, prev, query, repeat) { + if (repeat === undefined) { repeat = 1; } + return cm.operation(function() { + var pos = cm.getCursor(); + var cursor = cm.getSearchCursor(query, pos); + for (var i = 0; i < repeat; i++) { + var found = cursor.find(prev); + if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); } + if (!found) { + cursor = cm.getSearchCursor(query, + (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) ); + if (!cursor.find(prev)) { + return; + } + } + } + return cursor.from(); + }); + } + function clearSearchHighlight(cm) { + var state = getSearchState(cm); + cm.removeOverlay(getSearchState(cm).getOverlay()); + state.setOverlay(null); + if (state.getScrollbarAnnotate()) { + state.getScrollbarAnnotate().clear(); + state.setScrollbarAnnotate(null); + } + } + function isInRange(pos, start, end) { + if (typeof pos != 'number') { + pos = pos.line; + } + if (start instanceof Array) { + return inArray(pos, start); + } else { + if (end) { + return (pos >= start && pos <= end); + } else { + return pos == start; + } + } + } + function getUserVisibleLines(cm) { + var renderer = cm.ace.renderer; + return { + top: renderer.getFirstFullyVisibleRow(), + bottom: renderer.getLastFullyVisibleRow() + } + } + + var ExCommandDispatcher = function() { + this.buildCommandMap_(); + }; + ExCommandDispatcher.prototype = { + processCommand: function(cm, input, opt_params) { + var that = this; + cm.operation(function () { + cm.curOp.isVimOp = true; + that._processCommand(cm, input, opt_params); + }); + }, + _processCommand: function(cm, input, opt_params) { + var vim = cm.state.vim; + var commandHistoryRegister = vimGlobalState.registerController.getRegister(':'); + var previousCommand = commandHistoryRegister.toString(); + if (vim.visualMode) { + exitVisualMode(cm); + } + var inputStream = new CodeMirror.StringStream(input); + commandHistoryRegister.setText(input); + var params = opt_params || {}; + params.input = input; + try { + this.parseInput_(cm, inputStream, params); + } catch(e) { + showConfirm(cm, e); + throw e; + } + var command; + var commandName; + if (!params.commandName) { + if (params.line !== undefined) { + commandName = 'move'; + } + } else { + command = this.matchCommand_(params.commandName); + if (command) { + commandName = command.name; + if (command.excludeFromCommandHistory) { + commandHistoryRegister.setText(previousCommand); + } + this.parseCommandArgs_(inputStream, params, command); + if (command.type == 'exToKey') { + for (var i = 0; i < command.toKeys.length; i++) { + CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping'); + } + return; + } else if (command.type == 'exToEx') { + this.processCommand(cm, command.toInput); + return; + } + } + } + if (!commandName) { + showConfirm(cm, 'Not an editor command ":' + input + '"'); + return; + } + try { + exCommands[commandName](cm, params); + if ((!command || !command.possiblyAsync) && params.callback) { + params.callback(); + } + } catch(e) { + showConfirm(cm, e); + throw e; + } + }, + parseInput_: function(cm, inputStream, result) { + inputStream.eatWhile(':'); + if (inputStream.eat('%')) { + result.line = cm.firstLine(); + result.lineEnd = cm.lastLine(); + } else { + result.line = this.parseLineSpec_(cm, inputStream); + if (result.line !== undefined && inputStream.eat(',')) { + result.lineEnd = this.parseLineSpec_(cm, inputStream); + } + } + var commandMatch = inputStream.match(/^(\w+)/); + if (commandMatch) { + result.commandName = commandMatch[1]; + } else { + result.commandName = inputStream.match(/.*/)[0]; + } + + return result; + }, + parseLineSpec_: function(cm, inputStream) { + var numberMatch = inputStream.match(/^(\d+)/); + if (numberMatch) { + return parseInt(numberMatch[1], 10) - 1; + } + switch (inputStream.next()) { + case '.': + return cm.getCursor().line; + case '$': + return cm.lastLine(); + case '\'': + var mark = cm.state.vim.marks[inputStream.next()]; + if (mark && mark.find()) { + return mark.find().line; + } + throw new Error('Mark not set'); + default: + inputStream.backUp(1); + return undefined; + } + }, + parseCommandArgs_: function(inputStream, params, command) { + if (inputStream.eol()) { + return; + } + params.argString = inputStream.match(/.*/)[0]; + var delim = command.argDelimiter || /\s+/; + var args = trim(params.argString).split(delim); + if (args.length && args[0]) { + params.args = args; + } + }, + matchCommand_: function(commandName) { + for (var i = commandName.length; i > 0; i--) { + var prefix = commandName.substring(0, i); + if (this.commandMap_[prefix]) { + var command = this.commandMap_[prefix]; + if (command.name.indexOf(commandName) === 0) { + return command; + } + } + } + return null; + }, + buildCommandMap_: function() { + this.commandMap_ = {}; + for (var i = 0; i < defaultExCommandMap.length; i++) { + var command = defaultExCommandMap[i]; + var key = command.shortName || command.name; + this.commandMap_[key] = command; + } + }, + map: function(lhs, rhs, ctx) { + if (lhs != ':' && lhs.charAt(0) == ':') { + if (ctx) { throw Error('Mode not supported for ex mappings'); } + var commandName = lhs.substring(1); + if (rhs != ':' && rhs.charAt(0) == ':') { + this.commandMap_[commandName] = { + name: commandName, + type: 'exToEx', + toInput: rhs.substring(1), + user: true + }; + } else { + this.commandMap_[commandName] = { + name: commandName, + type: 'exToKey', + toKeys: rhs, + user: true + }; + } + } else { + if (rhs != ':' && rhs.charAt(0) == ':') { + var mapping = { + keys: lhs, + type: 'keyToEx', + exArgs: { input: rhs.substring(1) }, + user: true}; + if (ctx) { mapping.context = ctx; } + defaultKeymap.unshift(mapping); + } else { + var mapping = { + keys: lhs, + type: 'keyToKey', + toKeys: rhs, + user: true + }; + if (ctx) { mapping.context = ctx; } + defaultKeymap.unshift(mapping); + } + } + }, + unmap: function(lhs, ctx) { + if (lhs != ':' && lhs.charAt(0) == ':') { + if (ctx) { throw Error('Mode not supported for ex mappings'); } + var commandName = lhs.substring(1); + if (this.commandMap_[commandName] && this.commandMap_[commandName].user) { + delete this.commandMap_[commandName]; + return; + } + } else { + var keys = lhs; + for (var i = 0; i < defaultKeymap.length; i++) { + if (keys == defaultKeymap[i].keys + && defaultKeymap[i].context === ctx + && defaultKeymap[i].user) { + defaultKeymap.splice(i, 1); + return; + } + } + } + } + }; + + var exCommands = { + colorscheme: function(cm, params) { + if (!params.args || params.args.length < 1) { + showConfirm(cm, cm.getOption('theme')); + return; + } + cm.setOption('theme', params.args[0]); + }, + map: function(cm, params, ctx) { + var mapArgs = params.args; + if (!mapArgs || mapArgs.length < 2) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx); + }, + imap: function(cm, params) { this.map(cm, params, 'insert'); }, + nmap: function(cm, params) { this.map(cm, params, 'normal'); }, + vmap: function(cm, params) { this.map(cm, params, 'visual'); }, + unmap: function(cm, params, ctx) { + var mapArgs = params.args; + if (!mapArgs || mapArgs.length < 1) { + if (cm) { + showConfirm(cm, 'No such mapping: ' + params.input); + } + return; + } + exCommandDispatcher.unmap(mapArgs[0], ctx); + }, + move: function(cm, params) { + commandDispatcher.processCommand(cm, cm.state.vim, { + type: 'motion', + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: false, explicitRepeat: true, + linewise: true }, + repeatOverride: params.line+1}); + }, + set: function(cm, params) { + var setArgs = params.args; + var setCfg = params.setCfg || {}; + if (!setArgs || setArgs.length < 1) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + var expr = setArgs[0].split('='); + var optionName = expr[0]; + var value = expr[1]; + var forceGet = false; + + if (optionName.charAt(optionName.length - 1) == '?') { + if (value) { throw Error('Trailing characters: ' + params.argString); } + optionName = optionName.substring(0, optionName.length - 1); + forceGet = true; + } + if (value === undefined && optionName.substring(0, 2) == 'no') { + optionName = optionName.substring(2); + value = false; + } + + var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean'; + if (optionIsBoolean && value == undefined) { + value = true; + } + if (!optionIsBoolean && value === undefined || forceGet) { + var oldValue = getOption(optionName, cm, setCfg); + if (oldValue === true || oldValue === false) { + showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName); + } else { + showConfirm(cm, ' ' + optionName + '=' + oldValue); + } + } else { + setOption(optionName, value, cm, setCfg); + } + }, + setlocal: function (cm, params) { + params.setCfg = {scope: 'local'}; + this.set(cm, params); + }, + setglobal: function (cm, params) { + params.setCfg = {scope: 'global'}; + this.set(cm, params); + }, + registers: function(cm, params) { + var regArgs = params.args; + var registers = vimGlobalState.registerController.registers; + var regInfo = '----------Registers----------

'; + if (!regArgs) { + for (var registerName in registers) { + var text = registers[registerName].toString(); + if (text.length) { + regInfo += '"' + registerName + ' ' + text + '
'; + } + } + } else { + var registerName; + regArgs = regArgs.join(''); + for (var i = 0; i < regArgs.length; i++) { + registerName = regArgs.charAt(i); + if (!vimGlobalState.registerController.isValidRegister(registerName)) { + continue; + } + var register = registers[registerName] || new Register(); + regInfo += '"' + registerName + ' ' + register.toString() + '
'; + } + } + showConfirm(cm, regInfo); + }, + sort: function(cm, params) { + var reverse, ignoreCase, unique, number; + function parseArgs() { + if (params.argString) { + var args = new CodeMirror.StringStream(params.argString); + if (args.eat('!')) { reverse = true; } + if (args.eol()) { return; } + if (!args.eatSpace()) { return 'Invalid arguments'; } + var opts = args.match(/[a-z]+/); + if (opts) { + opts = opts[0]; + ignoreCase = opts.indexOf('i') != -1; + unique = opts.indexOf('u') != -1; + var decimal = opts.indexOf('d') != -1 && 1; + var hex = opts.indexOf('x') != -1 && 1; + var octal = opts.indexOf('o') != -1 && 1; + if (decimal + hex + octal > 1) { return 'Invalid arguments'; } + number = decimal && 'decimal' || hex && 'hex' || octal && 'octal'; + } + if (args.match(/\/.*\//)) { return 'patterns not supported'; } + } + } + var err = parseArgs(); + if (err) { + showConfirm(cm, err + ': ' + params.argString); + return; + } + var lineStart = params.line || cm.firstLine(); + var lineEnd = params.lineEnd || params.line || cm.lastLine(); + if (lineStart == lineEnd) { return; } + var curStart = Pos(lineStart, 0); + var curEnd = Pos(lineEnd, lineLength(cm, lineEnd)); + var text = cm.getRange(curStart, curEnd).split('\n'); + var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ : + (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i : + (number == 'octal') ? /([0-7]+)/ : null; + var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null; + var numPart = [], textPart = []; + if (number) { + for (var i = 0; i < text.length; i++) { + if (numberRegex.exec(text[i])) { + numPart.push(text[i]); + } else { + textPart.push(text[i]); + } + } + } else { + textPart = text; + } + function compareFn(a, b) { + if (reverse) { var tmp; tmp = a; a = b; b = tmp; } + if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); } + var anum = number && numberRegex.exec(a); + var bnum = number && numberRegex.exec(b); + if (!anum) { return a < b ? -1 : 1; } + anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix); + bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix); + return anum - bnum; + } + numPart.sort(compareFn); + textPart.sort(compareFn); + text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart); + if (unique) { // Remove duplicate lines + var textOld = text; + var lastLine; + text = []; + for (var i = 0; i < textOld.length; i++) { + if (textOld[i] != lastLine) { + text.push(textOld[i]); + } + lastLine = textOld[i]; + } + } + cm.replaceRange(text.join('\n'), curStart, curEnd); + }, + global: function(cm, params) { + var argString = params.argString; + if (!argString) { + showConfirm(cm, 'Regular Expression missing from global'); + return; + } + var lineStart = (params.line !== undefined) ? params.line : cm.firstLine(); + var lineEnd = params.lineEnd || params.line || cm.lastLine(); + var tokens = splitBySlash(argString); + var regexPart = argString, cmd; + if (tokens.length) { + regexPart = tokens[0]; + cmd = tokens.slice(1, tokens.length).join('/'); + } + if (regexPart) { + try { + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + return; + } + } + var query = getSearchState(cm).getQuery(); + var matchedLines = [], content = ''; + for (var i = lineStart; i <= lineEnd; i++) { + var matched = query.test(cm.getLine(i)); + if (matched) { + matchedLines.push(i+1); + content+= cm.getLine(i) + '
'; + } + } + if (!cmd) { + showConfirm(cm, content); + return; + } + var index = 0; + var nextCommand = function() { + if (index < matchedLines.length) { + var command = matchedLines[index] + cmd; + exCommandDispatcher.processCommand(cm, command, { + callback: nextCommand + }); + } + index++; + }; + nextCommand(); + }, + substitute: function(cm, params) { + if (!cm.getSearchCursor) { + throw new Error('Search feature not available. Requires searchcursor.js or ' + + 'any other getSearchCursor implementation.'); + } + var argString = params.argString; + var tokens = argString ? splitBySlash(argString) : []; + var regexPart, replacePart = '', trailing, flagsPart, count; + var confirm = false; // Whether to confirm each replace. + var global = false; // True to replace all instances on a line, false to replace only 1. + if (tokens.length) { + regexPart = tokens[0]; + replacePart = tokens[1]; + if (replacePart !== undefined) { + if (getOption('pcre')) { + replacePart = unescapeRegexReplace(replacePart); + } else { + replacePart = translateRegexReplace(replacePart); + } + vimGlobalState.lastSubstituteReplacePart = replacePart; + } + trailing = tokens[2] ? tokens[2].split(' ') : []; + } else { + if (argString && argString.length) { + showConfirm(cm, 'Substitutions should be of the form ' + + ':s/pattern/replace/'); + return; + } + } + if (trailing) { + flagsPart = trailing[0]; + count = parseInt(trailing[1]); + if (flagsPart) { + if (flagsPart.indexOf('c') != -1) { + confirm = true; + flagsPart.replace('c', ''); + } + if (flagsPart.indexOf('g') != -1) { + global = true; + flagsPart.replace('g', ''); + } + regexPart = regexPart + '/' + flagsPart; + } + } + if (regexPart) { + try { + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + return; + } + } + replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart; + if (replacePart === undefined) { + showConfirm(cm, 'No previous substitute regular expression'); + return; + } + var state = getSearchState(cm); + var query = state.getQuery(); + var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line; + var lineEnd = params.lineEnd || lineStart; + if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) { + lineEnd = Infinity; + } + if (count) { + lineStart = lineEnd; + lineEnd = lineStart + count - 1; + } + var startPos = clipCursorToContent(cm, Pos(lineStart, 0)); + var cursor = cm.getSearchCursor(query, startPos); + doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback); + }, + redo: CodeMirror.commands.redo, + undo: CodeMirror.commands.undo, + write: function(cm) { + if (CodeMirror.commands.save) { + CodeMirror.commands.save(cm); + } else { + cm.save(); + } + }, + nohlsearch: function(cm) { + clearSearchHighlight(cm); + }, + delmarks: function(cm, params) { + if (!params.argString || !trim(params.argString)) { + showConfirm(cm, 'Argument acequired'); + return; + } + + var state = cm.state.vim; + var stream = new CodeMirror.StringStream(trim(params.argString)); + while (!stream.eol()) { + stream.eatSpace(); + var count = stream.pos; + + if (!stream.match(/[a-zA-Z]/, false)) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + + var sym = stream.next(); + if (stream.match('-', true)) { + if (!stream.match(/[a-zA-Z]/, false)) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + + var startMark = sym; + var finishMark = stream.next(); + if (isLowerCase(startMark) && isLowerCase(finishMark) || + isUpperCase(startMark) && isUpperCase(finishMark)) { + var start = startMark.charCodeAt(0); + var finish = finishMark.charCodeAt(0); + if (start >= finish) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + for (var j = 0; j <= finish - start; j++) { + var mark = String.fromCharCode(start + j); + delete state.marks[mark]; + } + } else { + showConfirm(cm, 'Invalid argument: ' + startMark + '-'); + return; + } + } else { + delete state.marks[sym]; + } + } + } + }; + + var exCommandDispatcher = new ExCommandDispatcher(); + function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query, + replaceWith, callback) { + cm.state.vim.exMode = true; + var done = false; + var lastPos = searchCursor.from(); + function replaceAll() { + cm.operation(function() { + while (!done) { + replace(); + next(); + } + stop(); + }); + } + function replace() { + var text = cm.getRange(searchCursor.from(), searchCursor.to()); + var newText = text.replace(query, replaceWith); + searchCursor.replace(newText); + } + function next() { + while(searchCursor.findNext() && + isInRange(searchCursor.from(), lineStart, lineEnd)) { + if (!global && lastPos && searchCursor.from().line == lastPos.line) { + continue; + } + cm.scrollIntoView(searchCursor.from(), 30); + cm.setSelection(searchCursor.from(), searchCursor.to()); + lastPos = searchCursor.from(); + done = false; + return; + } + done = true; + } + function stop(close) { + if (close) { close(); } + cm.focus(); + if (lastPos) { + cm.setCursor(lastPos); + var vim = cm.state.vim; + vim.exMode = false; + vim.lastHPos = vim.lastHSPos = lastPos.ch; + } + if (callback) { callback(); } + } + function onPromptKeyDown(e, _value, close) { + CodeMirror.e_stop(e); + var keyName = CodeMirror.keyName(e); + switch (keyName) { + case 'Y': + replace(); next(); break; + case 'N': + next(); break; + case 'A': + var savedCallback = callback; + callback = undefined; + cm.operation(replaceAll); + callback = savedCallback; + break; + case 'L': + replace(); + case 'Q': + case 'Esc': + case 'Ctrl-C': + case 'Ctrl-[': + stop(close); + break; + } + if (done) { stop(close); } + return true; + } + next(); + if (done) { + showConfirm(cm, 'No matches for ' + query.source); + return; + } + if (!confirm) { + replaceAll(); + if (callback) { callback(); } + return; + } + showPrompt(cm, { + prefix: 'replace with ' + replaceWith + ' (y/n/a/q/l)', + onKeyDown: onPromptKeyDown + }); + } + + CodeMirror.keyMap.vim = { + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + function exitInsertMode(cm) { + var vim = cm.state.vim; + var macroModeState = vimGlobalState.macroModeState; + var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.'); + var isPlaying = macroModeState.isPlaying; + var lastChange = macroModeState.lastInsertModeChanges; + var text = []; + if (!isPlaying) { + var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1; + var changes = lastChange.changes; + var text = []; + var i = 0; + while (i < changes.length) { + text.push(changes[i]); + if (changes[i] instanceof InsertModeKey) { + i++; + } else { + i+= selLength; + } + } + lastChange.changes = text; + cm.off('change', onChange); + CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); + } + if (!isPlaying && vim.insertModeRepeat > 1) { + repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, + true /** repeatForInsert */); + vim.lastEditInputState.repeatOverride = vim.insertModeRepeat; + } + delete vim.insertModeRepeat; + vim.insertMode = false; + cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1); + cm.setOption('keyMap', 'vim'); + cm.setOption('disableInput', true); + cm.toggleOverwrite(false); // exit replace mode if we were in it. + insertModeChangeRegister.setText(lastChange.changes.join('')); + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + if (macroModeState.isRecording) { + logInsertModeChange(macroModeState); + } + } + + function _mapCommand(command) { + defaultKeymap.unshift(command); + } + + function mapCommand(keys, type, name, args, extra) { + var command = {keys: keys, type: type}; + command[type] = name; + command[type + "Args"] = args; + for (var key in extra) + command[key] = extra[key]; + _mapCommand(command); + } + defineOption('insertModeEscKeysTimeout', 200, 'number'); + + CodeMirror.keyMap['vim-insert'] = { + 'Ctrl-N': 'autocomplete', + 'Ctrl-P': 'autocomplete', + 'Enter': function(cm) { + var fn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + fn(cm); + }, + fallthrough: ['default'], + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + CodeMirror.keyMap['vim-replace'] = { + 'Backspace': 'goCharLeft', + fallthrough: ['vim-insert'], + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + function executeMacroRegister(cm, vim, macroModeState, registerName) { + var register = vimGlobalState.registerController.getRegister(registerName); + if (registerName == ':') { + if (register.keyBuffer[0]) { + exCommandDispatcher.processCommand(cm, register.keyBuffer[0]); + } + macroModeState.isPlaying = false; + return; + } + var keyBuffer = register.keyBuffer; + var imc = 0; + macroModeState.isPlaying = true; + macroModeState.replaySearchQueries = register.searchQueries.slice(0); + for (var i = 0; i < keyBuffer.length; i++) { + var text = keyBuffer[i]; + var match, key; + while (text) { + match = (/<\w+-.+?>|<\w+>|./).exec(text); + key = match[0]; + text = text.substring(match.index + key.length); + CodeMirror.Vim.handleKey(cm, key, 'macro'); + if (vim.insertMode) { + var changes = register.insertModeChanges[imc++].changes; + vimGlobalState.macroModeState.lastInsertModeChanges.changes = + changes; + repeatInsertModeChanges(cm, changes, 1); + exitInsertMode(cm); + } + } + } + macroModeState.isPlaying = false; + } + + function logKey(macroModeState, key) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register) { + register.pushText(key); + } + } + + function logInsertModeChange(macroModeState) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register && register.pushInsertModeChanges) { + register.pushInsertModeChanges(macroModeState.lastInsertModeChanges); + } + } + + function logSearchQuery(macroModeState, query) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register && register.pushSearchQuery) { + register.pushSearchQuery(query); + } + } + function onChange(_cm, changeObj) { + var macroModeState = vimGlobalState.macroModeState; + var lastChange = macroModeState.lastInsertModeChanges; + if (!macroModeState.isPlaying) { + while(changeObj) { + lastChange.expectCursorActivityForChange = true; + if (changeObj.origin == '+input' || changeObj.origin == 'paste' + || changeObj.origin === undefined /* only in testing */) { + var text = changeObj.text.join('\n'); + if (lastChange.maybeReset) { + lastChange.changes = []; + lastChange.maybeReset = false; + } + lastChange.changes.push(text); + } + changeObj = changeObj.next; + } + } + } + function onCursorActivity(cm) { + var vim = cm.state.vim; + if (vim.insertMode) { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { return; } + var lastChange = macroModeState.lastInsertModeChanges; + if (lastChange.expectCursorActivityForChange) { + lastChange.expectCursorActivityForChange = false; + } else { + lastChange.maybeReset = true; + } + } else if (!cm.curOp.isVimOp) { + handleExternalSelection(cm, vim); + } + if (vim.visualMode) { + updateFakeCursor(cm); + } + } + function updateFakeCursor(cm) { + var vim = cm.state.vim; + var from = clipCursorToContent(cm, copyCursor(vim.sel.head)); + var to = offsetCursor(from, 0, 1); + if (vim.fakeCursor) { + vim.fakeCursor.clear(); + } + vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'}); + } + function handleExternalSelection(cm, vim) { + var anchor = cm.getCursor('anchor'); + var head = cm.getCursor('head'); + if (vim.visualMode && !cm.somethingSelected()) { + exitVisualMode(cm, false); + } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) { + vim.visualMode = true; + vim.visualLine = false; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); + } + if (vim.visualMode) { + var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; + var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; + head = offsetCursor(head, 0, headOffset); + anchor = offsetCursor(anchor, 0, anchorOffset); + vim.sel = { + anchor: anchor, + head: head + }; + updateMark(cm, vim, '<', cursorMin(head, anchor)); + updateMark(cm, vim, '>', cursorMax(head, anchor)); + } else if (!vim.insertMode) { + vim.lastHPos = cm.getCursor().ch; + } + } + function InsertModeKey(keyName) { + this.keyName = keyName; + } + function onKeyEventTargetKeyDown(e) { + var macroModeState = vimGlobalState.macroModeState; + var lastChange = macroModeState.lastInsertModeChanges; + var keyName = CodeMirror.keyName(e); + if (!keyName) { return; } + function onKeyFound() { + if (lastChange.maybeReset) { + lastChange.changes = []; + lastChange.maybeReset = false; + } + lastChange.changes.push(new InsertModeKey(keyName)); + return true; + } + if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { + CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound); + } + } + function repeatLastEdit(cm, vim, repeat, repeatForInsert) { + var macroModeState = vimGlobalState.macroModeState; + macroModeState.isPlaying = true; + var isAction = !!vim.lastEditActionCommand; + var cachedInputState = vim.inputState; + function repeatCommand() { + if (isAction) { + commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); + } else { + commandDispatcher.evalInput(cm, vim); + } + } + function repeatInsert(repeat) { + if (macroModeState.lastInsertModeChanges.changes.length > 0) { + repeat = !vim.lastEditActionCommand ? 1 : repeat; + var changeObject = macroModeState.lastInsertModeChanges; + repeatInsertModeChanges(cm, changeObject.changes, repeat); + } + } + vim.inputState = vim.lastEditInputState; + if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { + for (var i = 0; i < repeat; i++) { + repeatCommand(); + repeatInsert(1); + } + } else { + if (!repeatForInsert) { + repeatCommand(); + } + repeatInsert(repeat); + } + vim.inputState = cachedInputState; + if (vim.insertMode && !repeatForInsert) { + exitInsertMode(cm); + } + macroModeState.isPlaying = false; + } + + function repeatInsertModeChanges(cm, changes, repeat) { + function keyHandler(binding) { + if (typeof binding == 'string') { + CodeMirror.commands[binding](cm); + } else { + binding(cm); + } + return true; + } + var head = cm.getCursor('head'); + var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock; + if (inVisualBlock) { + var vim = cm.state.vim; + var lastSel = vim.lastSelection; + var offset = getOffset(lastSel.anchor, lastSel.head); + selectForInsert(cm, head, offset.line + 1); + repeat = cm.listSelections().length; + cm.setCursor(head); + } + for (var i = 0; i < repeat; i++) { + if (inVisualBlock) { + cm.setCursor(offsetCursor(head, i, 0)); + } + for (var j = 0; j < changes.length; j++) { + var change = changes[j]; + if (change instanceof InsertModeKey) { + CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler); + } else { + var cur = cm.getCursor(); + cm.replaceRange(change, cur, cur); + } + } + } + if (inVisualBlock) { + cm.setCursor(offsetCursor(head, 0, 1)); + } + } + + resetVimGlobalState(); + CodeMirror.Vim = Vim(); + + Vim = CodeMirror.Vim; + + var specialKey = {'return':'CR',backspace:'BS','delete':'Del',esc:'Esc', + left:'Left',right:'Right',up:'Up',down:'Down',space: 'Space', + home:'Home',end:'End',pageup:'PageUp',pagedown:'PageDown', enter: 'CR' + }; + function lookupKey(hashId, key, e) { + if (key.length > 1 && key[0] == "n") { + key = key.replace("numpad", ""); + } + key = specialKey[key] || key; + var name = ''; + if (e.ctrlKey) { name += 'C-'; } + if (e.altKey) { name += 'A-'; } + if (e.shiftKey) { name += 'S-'; } + + name += key; + if (name.length > 1) { name = '<' + name + '>'; } + return name; + } + var handleKey = Vim.handleKey.bind(Vim); + Vim.handleKey = function(cm, key, origin) { + return cm.operation(function() { + return handleKey(cm, key, origin); + }, true); + } + function cloneVimState(state) { + var n = new state.constructor(); + Object.keys(state).forEach(function(key) { + var o = state[key]; + if (Array.isArray(o)) + o = o.slice(); + else if (o && typeof o == "object" && o.constructor != Object) + o = cloneVimState(o); + n[key] = o; + }); + if (state.sel) { + n.sel = { + head: state.sel.head && copyCursor(state.sel.head), + anchor: state.sel.anchor && copyCursor(state.sel.anchor) + }; + } + return n; + } + function multiSelectHandleKey(cm, key, origin) { + var isHandled = false; + var vim = Vim.maybeInitVimState_(cm); + var visualBlock = vim.visualBlock || vim.wasInVisualBlock; + if (vim.wasInVisualBlock && !cm.ace.inMultiSelectMode) { + vim.wasInVisualBlock = false; + } else if (cm.ace.inMultiSelectMode && vim.visualBlock) { + vim.wasInVisualBlock = true; + } + + if (key == '' && !vim.insertMode && !vim.visualMode && cm.ace.inMultiSelectMode) { + cm.ace.exitMultiSelectMode(); + } else if (visualBlock || !cm.ace.inMultiSelectMode || cm.ace.inVirtualSelectionMode) { + isHandled = Vim.handleKey(cm, key, origin); + } else { + var old = cloneVimState(vim); + cm.operation(function() { + cm.ace.forEachSelection(function() { + var sel = cm.ace.selection; + cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn; + var head = cm.getCursor("head"); + var anchor = cm.getCursor("anchor"); + var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; + var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; + head = offsetCursor(head, 0, headOffset); + anchor = offsetCursor(anchor, 0, anchorOffset); + cm.state.vim.sel.head = head; + cm.state.vim.sel.anchor = anchor; + + isHandled = handleKey(cm, key, origin); + sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos; + if (cm.virtualSelectionMode()) { + cm.state.vim = cloneVimState(old); + } + }); + if (cm.curOp.cursorActivity && !isHandled) + cm.curOp.cursorActivity = false; + }, true); + } + return isHandled; + } + exports.CodeMirror = CodeMirror; + var getVim = Vim.maybeInitVimState_; + exports.handler = { + $id: "ace/keyboard/vim", + drawCursor: function(style, pixelPos, config, sel, session) { + var vim = this.state.vim || {}; + var w = config.characterWidth; + var h = config.lineHeight; + var top = pixelPos.top; + var left = pixelPos.left; + if (!vim.insertMode) { + var isbackwards = !sel.cursor + ? session.selection.isBackwards() || session.selection.isEmpty() + : Range.comparePoints(sel.cursor, sel.start) <= 0; + if (!isbackwards && left > w) + left -= w; + } + if (!vim.insertMode && vim.status) { + h = h / 2; + top += h; + } + style.left = left + "px"; + style.top = top + "px"; + style.width = w + "px"; + style.height = h + "px"; + }, + handleKeyboard: function(data, hashId, key, keyCode, e) { + var editor = data.editor; + var cm = editor.state.cm; + var vim = getVim(cm); + if (keyCode == -1) return; + + if (key == "c" && hashId == 1) { // key == "ctrl-c" + if (!useragent.isMac && editor.getCopyText()) { + editor.once("copy", function() { + editor.selection.clearSelection(); + }); + return {command: "null", passEvent: true}; + } + } else if (!vim.insertMode) { + if (useragent.isMac && this.handleMacRepeat(data, hashId, key)) { + hashId = -1; + key = data.inputChar; + } + } + + if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) { + var insertMode = vim.insertMode; + var name = lookupKey(hashId, key, e || {}); + if (vim.status == null) + vim.status = ""; + var isHandled = multiSelectHandleKey(cm, name, 'user'); + vim = getVim(cm); // may be changed by multiSelectHandleKey + if (isHandled && vim.status != null) + vim.status += name; + else if (vim.status == null) + vim.status = ""; + cm._signal("changeStatus"); + if (!isHandled && (hashId != -1 || insertMode)) + return; + return {command: "null", passEvent: !isHandled}; + } + }, + attach: function(editor) { + if (!editor.state) editor.state = {}; + var cm = new CodeMirror(editor); + editor.state.cm = cm; + editor.$vimModeHandler = this; + CodeMirror.keyMap.vim.attach(cm); + getVim(cm).status = null; + cm.on('vim-command-done', function() { + if (cm.virtualSelectionMode()) return; + getVim(cm).status = null; + cm.ace._signal("changeStatus"); + cm.ace.session.markUndoGroup(); + }); + cm.on("changeStatus", function() { + cm.ace.renderer.updateCursor(); + cm.ace._signal("changeStatus"); + }); + cm.on("vim-mode-change", function() { + if (cm.virtualSelectionMode()) return; + cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); + cm._signal("changeStatus"); + }); + cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); + editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm); + this.updateMacCompositionHandlers(editor, true); + }, + detach: function(editor) { + var cm = editor.state.cm; + CodeMirror.keyMap.vim.detach(cm); + cm.destroy(); + editor.state.cm = null; + editor.$vimModeHandler = null; + editor.renderer.$cursorLayer.drawCursor = null; + editor.renderer.setStyle("normal-mode", false); + this.updateMacCompositionHandlers(editor, false); + }, + getStatusText: function(editor) { + var cm = editor.state.cm; + var vim = getVim(cm); + if (vim.insertMode) + return "INSERT"; + var status = ""; + if (vim.visualMode) { + status += "VISUAL"; + if (vim.visualLine) + status += " LINE"; + if (vim.visualBlock) + status += " BLOCK"; + } + if (vim.status) + status += (status ? " " : "") + vim.status; + return status; + }, + handleMacRepeat: function(data, hashId, key) { + if (hashId == -1) { + data.inputChar = key; + data.lastEvent = "input"; + } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) { + if (data.lastEvent == "input") { + data.lastEvent = "input1"; + } else if (data.lastEvent == "input1") { + return true; + } + } else { + data.$lastHash = hashId; + data.$lastKey = key; + data.lastEvent = "keypress"; + } + }, + updateMacCompositionHandlers: function(editor, enable) { + var onCompositionUpdateOverride = function(text) { + var cm = editor.state.cm; + var vim = getVim(cm); + if (!vim.insertMode) { + var el = this.textInput.getElement(); + el.blur(); + el.focus(); + el.value = text; + } else { + this.onCompositionUpdateOrig(text); + } + }; + var onCompositionStartOverride = function(text) { + var cm = editor.state.cm; + var vim = getVim(cm); + if (!vim.insertMode) { + this.onCompositionStartOrig(text); + } + }; + if (enable) { + if (!editor.onCompositionUpdateOrig) { + editor.onCompositionUpdateOrig = editor.onCompositionUpdate; + editor.onCompositionUpdate = onCompositionUpdateOverride; + editor.onCompositionStartOrig = editor.onCompositionStart; + editor.onCompositionStart = onCompositionStartOverride; + } + } else { + if (editor.onCompositionUpdateOrig) { + editor.onCompositionUpdate = editor.onCompositionUpdateOrig; + editor.onCompositionUpdateOrig = null; + editor.onCompositionStart = editor.onCompositionStartOrig; + editor.onCompositionStartOrig = null; + } + } + } + }; + var renderVirtualNumbers = { + getText: function(session, row) { + return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9? "\xb7" : "" ))) + ""; + }, + getWidth: function(session, lastLineNumber, config) { + return session.getLength().toString().length * config.characterWidth; + }, + update: function(e, editor) { + editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER); + }, + attach: function(editor) { + editor.renderer.$gutterLayer.$renderer = this; + editor.on("changeSelection", this.update); + }, + detach: function(editor) { + editor.renderer.$gutterLayer.$renderer = null; + editor.off("changeSelection", this.update); + } + }; + Vim.defineOption({ + name: "wrap", + set: function(value, cm) { + if (cm) {cm.ace.setOption("wrap", value)} + }, + type: "boolean" + }, false); + Vim.defineEx('write', 'w', function() { + console.log(':write is not implemented') + }); + defaultKeymap.push( + { keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } }, + { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } }, + { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } }, + { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, + { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } }, + { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } }, + { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, + { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, + + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } }, + { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } } + ); + actions.aceCommand = function(cm, actionArgs, vim) { + cm.vimCmd = actionArgs; + if (cm.ace.inVirtualSelectionMode) + cm.ace.on("beforeEndOperation", delayedExecAceCommand); + else + delayedExecAceCommand(null, cm.ace); + }; + function delayedExecAceCommand(op, ace) { + ace.off("beforeEndOperation", delayedExecAceCommand); + var cmd = ace.state.cm.vimCmd; + if (cmd) { + ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args); + } + ace.curOp = ace.prevOp; + } + actions.fold = function(cm, actionArgs, vim) { + cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall' + ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]); + }; + + exports.handler.defaultKeymap = defaultKeymap; + exports.handler.actions = actions; + exports.Vim = Vim; + + Vim.map("Y", "yy", "normal"); +}); + + +/***/ }), +/* 66 */ +/***/ (function(module, exports) { + +ace.define("ace/occur",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/edit_session","ace/search_highlight","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; +var Search = acequire("./search").Search; +var EditSession = acequire("./edit_session").EditSession; +var SearchHighlight = acequire("./search_highlight").SearchHighlight; +function Occur() {} + +oop.inherits(Occur, Search); + +(function() { + this.enter = function(editor, options) { + if (!options.needle) return false; + var pos = editor.getCursorPosition(); + this.displayOccurContent(editor, options); + var translatedPos = this.originalToOccurPosition(editor.session, pos); + editor.moveCursorToPosition(translatedPos); + return true; + } + this.exit = function(editor, options) { + var pos = options.translatePosition && editor.getCursorPosition(); + var translatedPos = pos && this.occurToOriginalPosition(editor.session, pos); + this.displayOriginalContent(editor); + if (translatedPos) + editor.moveCursorToPosition(translatedPos); + return true; + } + + this.highlight = function(sess, regexp) { + var hl = sess.$occurHighlight = sess.$occurHighlight || sess.addDynamicMarker( + new SearchHighlight(null, "ace_occur-highlight", "text")); + hl.setRegexp(regexp); + sess._emit("changeBackMarker"); // force highlight layer redraw + } + + this.displayOccurContent = function(editor, options) { + this.$originalSession = editor.session; + var found = this.matchingLines(editor.session, options); + var lines = found.map(function(foundLine) { return foundLine.content; }); + var occurSession = new EditSession(lines.join('\n')); + occurSession.$occur = this; + occurSession.$occurMatchingLines = found; + editor.setSession(occurSession); + this.$useEmacsStyleLineStart = this.$originalSession.$useEmacsStyleLineStart; + occurSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; + this.highlight(occurSession, options.re); + occurSession._emit('changeBackMarker'); + } + + this.displayOriginalContent = function(editor) { + editor.setSession(this.$originalSession); + this.$originalSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; + } + this.originalToOccurPosition = function(session, pos) { + var lines = session.$occurMatchingLines; + var nullPos = {row: 0, column: 0}; + if (!lines) return nullPos; + for (var i = 0; i < lines.length; i++) { + if (lines[i].row === pos.row) + return {row: i, column: pos.column}; + } + return nullPos; + } + this.occurToOriginalPosition = function(session, pos) { + var lines = session.$occurMatchingLines; + if (!lines || !lines[pos.row]) + return pos; + return {row: lines[pos.row].row, column: pos.column}; + } + + this.matchingLines = function(session, options) { + options = oop.mixin({}, options); + if (!session || !options.needle) return []; + var search = new Search(); + search.set(options); + return search.findAll(session).reduce(function(lines, range) { + var row = range.start.row; + var last = lines[lines.length-1]; + return last && last.row === row ? + lines : + lines.concat({row: row, content: session.getLine(row)}); + }, []); + } + +}).call(Occur.prototype); + +var dom = acequire('./lib/dom'); +dom.importCssString(".ace_occur-highlight {\n\ + border-radius: 4px;\n\ + background-color: rgba(87, 255, 8, 0.25);\n\ + position: absolute;\n\ + z-index: 4;\n\ + -moz-box-sizing: border-box;\n\ + -webkit-box-sizing: border-box;\n\ + box-sizing: border-box;\n\ + box-shadow: 0 0 4px rgb(91, 255, 50);\n\ +}\n\ +.ace_dark .ace_occur-highlight {\n\ + background-color: rgb(80, 140, 85);\n\ + box-shadow: 0 0 4px rgb(60, 120, 70);\n\ +}\n", "incremental-occur-highlighting"); + +exports.Occur = Occur; + +}); + +ace.define("ace/commands/occur_commands",["require","exports","module","ace/config","ace/occur","ace/keyboard/hash_handler","ace/lib/oop"], function(acequire, exports, module) { + +var config = acequire("../config"), + Occur = acequire("../occur").Occur; +var occurStartCommand = { + name: "occur", + exec: function(editor, options) { + var alreadyInOccur = !!editor.session.$occur; + var occurSessionActive = new Occur().enter(editor, options); + if (occurSessionActive && !alreadyInOccur) + OccurKeyboardHandler.installIn(editor); + }, + readOnly: true +}; + +var occurCommands = [{ + name: "occurexit", + bindKey: 'esc|Ctrl-G', + exec: function(editor) { + var occur = editor.session.$occur; + if (!occur) return; + occur.exit(editor, {}); + if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); + }, + readOnly: true +}, { + name: "occuraccept", + bindKey: 'enter', + exec: function(editor) { + var occur = editor.session.$occur; + if (!occur) return; + occur.exit(editor, {translatePosition: true}); + if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); + }, + readOnly: true +}]; + +var HashHandler = acequire("../keyboard/hash_handler").HashHandler; +var oop = acequire("../lib/oop"); + + +function OccurKeyboardHandler() {} + +oop.inherits(OccurKeyboardHandler, HashHandler); + +(function() { + + this.isOccurHandler = true; + + this.attach = function(editor) { + HashHandler.call(this, occurCommands, editor.commands.platform); + this.$editor = editor; + } + + var handleKeyboard$super = this.handleKeyboard; + this.handleKeyboard = function(data, hashId, key, keyCode) { + var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); + return (cmd && cmd.command) ? cmd : undefined; + } + +}).call(OccurKeyboardHandler.prototype); + +OccurKeyboardHandler.installIn = function(editor) { + var handler = new this(); + editor.keyBinding.addKeyboardHandler(handler); + editor.commands.addCommands(occurCommands); +} + +OccurKeyboardHandler.uninstallFrom = function(editor) { + editor.commands.removeCommands(occurCommands); + var handler = editor.getKeyboardHandler(); + if (handler.isOccurHandler) + editor.keyBinding.removeKeyboardHandler(handler); +} + +exports.occurStartCommand = occurStartCommand; + +}); + +ace.define("ace/commands/incremental_search_commands",["require","exports","module","ace/config","ace/lib/oop","ace/keyboard/hash_handler","ace/commands/occur_commands"], function(acequire, exports, module) { + +var config = acequire("../config"); +var oop = acequire("../lib/oop"); +var HashHandler = acequire("../keyboard/hash_handler").HashHandler; +var occurStartCommand = acequire("./occur_commands").occurStartCommand; +exports.iSearchStartCommands = [{ + name: "iSearch", + bindKey: {win: "Ctrl-F", mac: "Command-F"}, + exec: function(editor, options) { + config.loadModule(["core", "ace/incremental_search"], function(e) { + var iSearch = e.iSearch = e.iSearch || new e.IncrementalSearch(); + iSearch.activate(editor, options.backwards); + if (options.jumpToFirstMatch) iSearch.next(options); + }); + }, + readOnly: true +}, { + name: "iSearchBackwards", + exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {backwards: true}); }, + readOnly: true +}, { + name: "iSearchAndGo", + bindKey: {win: "Ctrl-K", mac: "Command-G"}, + exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {jumpToFirstMatch: true, useCurrentOrPrevSearch: true}); }, + readOnly: true +}, { + name: "iSearchBackwardsAndGo", + bindKey: {win: "Ctrl-Shift-K", mac: "Command-Shift-G"}, + exec: function(editor) { editor.execCommand('iSearch', {jumpToFirstMatch: true, backwards: true, useCurrentOrPrevSearch: true}); }, + readOnly: true +}]; +exports.iSearchCommands = [{ + name: "restartSearch", + bindKey: {win: "Ctrl-F", mac: "Command-F"}, + exec: function(iSearch) { + iSearch.cancelSearch(true); + } +}, { + name: "searchForward", + bindKey: {win: "Ctrl-S|Ctrl-K", mac: "Ctrl-S|Command-G"}, + exec: function(iSearch, options) { + options.useCurrentOrPrevSearch = true; + iSearch.next(options); + } +}, { + name: "searchBackward", + bindKey: {win: "Ctrl-R|Ctrl-Shift-K", mac: "Ctrl-R|Command-Shift-G"}, + exec: function(iSearch, options) { + options.useCurrentOrPrevSearch = true; + options.backwards = true; + iSearch.next(options); + } +}, { + name: "extendSearchTerm", + exec: function(iSearch, string) { + iSearch.addString(string); + } +}, { + name: "extendSearchTermSpace", + bindKey: "space", + exec: function(iSearch) { iSearch.addString(' '); } +}, { + name: "shrinkSearchTerm", + bindKey: "backspace", + exec: function(iSearch) { + iSearch.removeChar(); + } +}, { + name: 'confirmSearch', + bindKey: 'return', + exec: function(iSearch) { iSearch.deactivate(); } +}, { + name: 'cancelSearch', + bindKey: 'esc|Ctrl-G', + exec: function(iSearch) { iSearch.deactivate(true); } +}, { + name: 'occurisearch', + bindKey: 'Ctrl-O', + exec: function(iSearch) { + var options = oop.mixin({}, iSearch.$options); + iSearch.deactivate(); + occurStartCommand.exec(iSearch.$editor, options); + } +}, { + name: "yankNextWord", + bindKey: "Ctrl-w", + exec: function(iSearch) { + var ed = iSearch.$editor, + range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorWordRight(); }), + string = ed.session.getTextRange(range); + iSearch.addString(string); + } +}, { + name: "yankNextChar", + bindKey: "Ctrl-Alt-y", + exec: function(iSearch) { + var ed = iSearch.$editor, + range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorRight(); }), + string = ed.session.getTextRange(range); + iSearch.addString(string); + } +}, { + name: 'recenterTopBottom', + bindKey: 'Ctrl-l', + exec: function(iSearch) { iSearch.$editor.execCommand('recenterTopBottom'); } +}, { + name: 'selectAllMatches', + bindKey: 'Ctrl-space', + exec: function(iSearch) { + var ed = iSearch.$editor, + hl = ed.session.$isearchHighlight, + ranges = hl && hl.cache ? hl.cache + .reduce(function(ranges, ea) { + return ranges.concat(ea ? ea : []); }, []) : []; + iSearch.deactivate(false); + ranges.forEach(ed.selection.addRange.bind(ed.selection)); + } +}, { + name: 'searchAsRegExp', + bindKey: 'Alt-r', + exec: function(iSearch) { + iSearch.convertNeedleToRegExp(); + } +}].map(function(cmd) { + cmd.readOnly = true; + cmd.isIncrementalSearchCommand = true; + cmd.scrollIntoView = "animate-cursor"; + return cmd; +}); + +function IncrementalSearchKeyboardHandler(iSearch) { + this.$iSearch = iSearch; +} + +oop.inherits(IncrementalSearchKeyboardHandler, HashHandler); + +(function() { + + this.attach = function(editor) { + var iSearch = this.$iSearch; + HashHandler.call(this, exports.iSearchCommands, editor.commands.platform); + this.$commandExecHandler = editor.commands.addEventListener('exec', function(e) { + if (!e.command.isIncrementalSearchCommand) + return iSearch.deactivate(); + e.stopPropagation(); + e.preventDefault(); + var scrollTop = editor.session.getScrollTop(); + var result = e.command.exec(iSearch, e.args || {}); + editor.renderer.scrollCursorIntoView(null, 0.5); + editor.renderer.animateScrolling(scrollTop); + return result; + }); + }; + + this.detach = function(editor) { + if (!this.$commandExecHandler) return; + editor.commands.removeEventListener('exec', this.$commandExecHandler); + delete this.$commandExecHandler; + }; + + var handleKeyboard$super = this.handleKeyboard; + this.handleKeyboard = function(data, hashId, key, keyCode) { + if (((hashId === 1/*ctrl*/ || hashId === 8/*command*/) && key === 'v') + || (hashId === 1/*ctrl*/ && key === 'y')) return null; + var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); + if (cmd.command) { return cmd; } + if (hashId == -1) { + var extendCmd = this.commands.extendSearchTerm; + if (extendCmd) { return {command: extendCmd, args: key}; } + } + return false; + }; + +}).call(IncrementalSearchKeyboardHandler.prototype); + + +exports.IncrementalSearchKeyboardHandler = IncrementalSearchKeyboardHandler; + +}); + +ace.define("ace/incremental_search",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/search_highlight","ace/commands/incremental_search_commands","ace/lib/dom","ace/commands/command_manager","ace/editor","ace/config"], function(acequire, exports, module) { +"use strict"; + +var oop = acequire("./lib/oop"); +var Range = acequire("./range").Range; +var Search = acequire("./search").Search; +var SearchHighlight = acequire("./search_highlight").SearchHighlight; +var iSearchCommandModule = acequire("./commands/incremental_search_commands"); +var ISearchKbd = iSearchCommandModule.IncrementalSearchKeyboardHandler; +function IncrementalSearch() { + this.$options = {wrap: false, skipCurrent: false}; + this.$keyboardHandler = new ISearchKbd(this); +} + +oop.inherits(IncrementalSearch, Search); + +function isRegExp(obj) { + return obj instanceof RegExp; +} + +function regExpToObject(re) { + var string = String(re), + start = string.indexOf('/'), + flagStart = string.lastIndexOf('/'); + return { + expression: string.slice(start+1, flagStart), + flags: string.slice(flagStart+1) + } +} + +function stringToRegExp(string, flags) { + try { + return new RegExp(string, flags); + } catch (e) { return string; } +} + +function objectToRegExp(obj) { + return stringToRegExp(obj.expression, obj.flags); +} + +(function() { + + this.activate = function(ed, backwards) { + this.$editor = ed; + this.$startPos = this.$currentPos = ed.getCursorPosition(); + this.$options.needle = ''; + this.$options.backwards = backwards; + ed.keyBinding.addKeyboardHandler(this.$keyboardHandler); + this.$originalEditorOnPaste = ed.onPaste; ed.onPaste = this.onPaste.bind(this); + this.$mousedownHandler = ed.addEventListener('mousedown', this.onMouseDown.bind(this)); + this.selectionFix(ed); + this.statusMessage(true); + }; + + this.deactivate = function(reset) { + this.cancelSearch(reset); + var ed = this.$editor; + ed.keyBinding.removeKeyboardHandler(this.$keyboardHandler); + if (this.$mousedownHandler) { + ed.removeEventListener('mousedown', this.$mousedownHandler); + delete this.$mousedownHandler; + } + ed.onPaste = this.$originalEditorOnPaste; + this.message(''); + }; + + this.selectionFix = function(editor) { + if (editor.selection.isEmpty() && !editor.session.$emacsMark) { + editor.clearSelection(); + } + }; + + this.highlight = function(regexp) { + var sess = this.$editor.session, + hl = sess.$isearchHighlight = sess.$isearchHighlight || sess.addDynamicMarker( + new SearchHighlight(null, "ace_isearch-result", "text")); + hl.setRegexp(regexp); + sess._emit("changeBackMarker"); // force highlight layer redraw + }; + + this.cancelSearch = function(reset) { + var e = this.$editor; + this.$prevNeedle = this.$options.needle; + this.$options.needle = ''; + if (reset) { + e.moveCursorToPosition(this.$startPos); + this.$currentPos = this.$startPos; + } else { + e.pushEmacsMark && e.pushEmacsMark(this.$startPos, false); + } + this.highlight(null); + return Range.fromPoints(this.$currentPos, this.$currentPos); + }; + + this.highlightAndFindWithNeedle = function(moveToNext, needleUpdateFunc) { + if (!this.$editor) return null; + var options = this.$options; + if (needleUpdateFunc) { + options.needle = needleUpdateFunc.call(this, options.needle || '') || ''; + } + if (options.needle.length === 0) { + this.statusMessage(true); + return this.cancelSearch(true); + } + options.start = this.$currentPos; + var session = this.$editor.session, + found = this.find(session), + shouldSelect = this.$editor.emacsMark ? + !!this.$editor.emacsMark() : !this.$editor.selection.isEmpty(); + if (found) { + if (options.backwards) found = Range.fromPoints(found.end, found.start); + this.$editor.selection.setRange(Range.fromPoints(shouldSelect ? this.$startPos : found.end, found.end)); + if (moveToNext) this.$currentPos = found.end; + this.highlight(options.re); + } + + this.statusMessage(found); + + return found; + }; + + this.addString = function(s) { + return this.highlightAndFindWithNeedle(false, function(needle) { + if (!isRegExp(needle)) + return needle + s; + var reObj = regExpToObject(needle); + reObj.expression += s; + return objectToRegExp(reObj); + }); + }; + + this.removeChar = function(c) { + return this.highlightAndFindWithNeedle(false, function(needle) { + if (!isRegExp(needle)) + return needle.substring(0, needle.length-1); + var reObj = regExpToObject(needle); + reObj.expression = reObj.expression.substring(0, reObj.expression.length-1); + return objectToRegExp(reObj); + }); + }; + + this.next = function(options) { + options = options || {}; + this.$options.backwards = !!options.backwards; + this.$currentPos = this.$editor.getCursorPosition(); + return this.highlightAndFindWithNeedle(true, function(needle) { + return options.useCurrentOrPrevSearch && needle.length === 0 ? + this.$prevNeedle || '' : needle; + }); + }; + + this.onMouseDown = function(evt) { + this.deactivate(); + return true; + }; + + this.onPaste = function(text) { + this.addString(text); + }; + + this.convertNeedleToRegExp = function() { + return this.highlightAndFindWithNeedle(false, function(needle) { + return isRegExp(needle) ? needle : stringToRegExp(needle, 'ig'); + }); + }; + + this.convertNeedleToString = function() { + return this.highlightAndFindWithNeedle(false, function(needle) { + return isRegExp(needle) ? regExpToObject(needle).expression : needle; + }); + }; + + this.statusMessage = function(found) { + var options = this.$options, msg = ''; + msg += options.backwards ? 'reverse-' : ''; + msg += 'isearch: ' + options.needle; + msg += found ? '' : ' (not found)'; + this.message(msg); + }; + + this.message = function(msg) { + if (this.$editor.showCommandLine) { + this.$editor.showCommandLine(msg); + this.$editor.focus(); + } else { + console.log(msg); + } + }; + +}).call(IncrementalSearch.prototype); + + +exports.IncrementalSearch = IncrementalSearch; + +var dom = acequire('./lib/dom'); +dom.importCssString && dom.importCssString("\ +.ace_marker-layer .ace_isearch-result {\ + position: absolute;\ + z-index: 6;\ + -moz-box-sizing: border-box;\ + -webkit-box-sizing: border-box;\ + box-sizing: border-box;\ +}\ +div.ace_isearch-result {\ + border-radius: 4px;\ + background-color: rgba(255, 200, 0, 0.5);\ + box-shadow: 0 0 4px rgb(255, 200, 0);\ +}\ +.ace_dark div.ace_isearch-result {\ + background-color: rgb(100, 110, 160);\ + box-shadow: 0 0 4px rgb(80, 90, 140);\ +}", "incremental-search-highlighting"); +var commands = acequire("./commands/command_manager"); +(function() { + this.setupIncrementalSearch = function(editor, val) { + if (this.usesIncrementalSearch == val) return; + this.usesIncrementalSearch = val; + var iSearchCommands = iSearchCommandModule.iSearchStartCommands; + var method = val ? 'addCommands' : 'removeCommands'; + this[method](iSearchCommands); + }; +}).call(commands.CommandManager.prototype); +var Editor = acequire("./editor").Editor; +acequire("./config").defineOptions(Editor.prototype, "editor", { + useIncrementalSearch: { + set: function(val) { + this.keyBinding.$handlers.forEach(function(handler) { + if (handler.setupIncrementalSearch) { + handler.setupIncrementalSearch(this, val); + } + }); + this._emit('incrementalSearchSettingChanged', {isEnabled: val}); + } + } +}); + +}); + +ace.define("ace/keyboard/emacs",["require","exports","module","ace/lib/dom","ace/incremental_search","ace/commands/incremental_search_commands","ace/keyboard/hash_handler","ace/lib/keys"], function(acequire, exports, module) { +"use strict"; + +var dom = acequire("../lib/dom"); +acequire("../incremental_search"); +var iSearchCommandModule = acequire("../commands/incremental_search_commands"); + + +var screenToTextBlockCoordinates = function(x, y) { + var canvasPos = this.scroller.getBoundingClientRect(); + + var col = Math.floor( + (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, col); +}; + +var HashHandler = acequire("./hash_handler").HashHandler; +exports.handler = new HashHandler(); + +exports.handler.isEmacs = true; +exports.handler.$id = "ace/keyboard/emacs"; + +var initialized = false; +var $formerLongWords; +var $formerLineStart; + +exports.handler.attach = function(editor) { + if (!initialized) { + initialized = true; + dom.importCssString('\ + .emacs-mode .ace_cursor{\ + border: 1px rgba(50,250,50,0.8) solid!important;\ + -moz-box-sizing: border-box!important;\ + -webkit-box-sizing: border-box!important;\ + box-sizing: border-box!important;\ + background-color: rgba(0,250,0,0.9);\ + opacity: 0.5;\ + }\ + .emacs-mode .ace_hidden-cursors .ace_cursor{\ + opacity: 1;\ + background-color: transparent;\ + }\ + .emacs-mode .ace_overwrite-cursors .ace_cursor {\ + opacity: 1;\ + background-color: transparent;\ + border-width: 0 0 2px 2px !important;\ + }\ + .emacs-mode .ace_text-layer {\ + z-index: 4\ + }\ + .emacs-mode .ace_cursor-layer {\ + z-index: 2\ + }', 'emacsMode' + ); + } + $formerLongWords = editor.session.$selectLongWords; + editor.session.$selectLongWords = true; + $formerLineStart = editor.session.$useEmacsStyleLineStart; + editor.session.$useEmacsStyleLineStart = true; + + editor.session.$emacsMark = null; // the active mark + editor.session.$emacsMarkRing = editor.session.$emacsMarkRing || []; + + editor.emacsMark = function() { + return this.session.$emacsMark; + }; + + editor.setEmacsMark = function(p) { + this.session.$emacsMark = p; + }; + + editor.pushEmacsMark = function(p, activate) { + var prevMark = this.session.$emacsMark; + if (prevMark) + this.session.$emacsMarkRing.push(prevMark); + if (!p || activate) this.setEmacsMark(p); + else this.session.$emacsMarkRing.push(p); + }; + + editor.popEmacsMark = function() { + var mark = this.emacsMark(); + if (mark) { this.setEmacsMark(null); return mark; } + return this.session.$emacsMarkRing.pop(); + }; + + editor.getLastEmacsMark = function(p) { + return this.session.$emacsMark || this.session.$emacsMarkRing.slice(-1)[0]; + }; + + editor.emacsMarkForSelection = function(replacement) { + var sel = this.selection, + multiRangeLength = this.multiSelect ? + this.multiSelect.getAllRanges().length : 1, + selIndex = sel.index || 0, + markRing = this.session.$emacsMarkRing, + markIndex = markRing.length - (multiRangeLength - selIndex), + lastMark = markRing[markIndex] || sel.anchor; + if (replacement) { + markRing.splice(markIndex, 1, + "row" in replacement && "column" in replacement ? + replacement : undefined); + } + return lastMark; + } + + editor.on("click", $resetMarkMode); + editor.on("changeSession", $kbSessionChange); + editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates; + editor.setStyle("emacs-mode"); + editor.commands.addCommands(commands); + exports.handler.platform = editor.commands.platform; + editor.$emacsModeHandler = this; + editor.addEventListener('copy', this.onCopy); + editor.addEventListener('paste', this.onPaste); +}; + +exports.handler.detach = function(editor) { + delete editor.renderer.screenToTextCoordinates; + editor.session.$selectLongWords = $formerLongWords; + editor.session.$useEmacsStyleLineStart = $formerLineStart; + editor.removeEventListener("click", $resetMarkMode); + editor.removeEventListener("changeSession", $kbSessionChange); + editor.unsetStyle("emacs-mode"); + editor.commands.removeCommands(commands); + editor.removeEventListener('copy', this.onCopy); + editor.removeEventListener('paste', this.onPaste); + editor.$emacsModeHandler = null; +}; + +var $kbSessionChange = function(e) { + if (e.oldSession) { + e.oldSession.$selectLongWords = $formerLongWords; + e.oldSession.$useEmacsStyleLineStart = $formerLineStart; + } + + $formerLongWords = e.session.$selectLongWords; + e.session.$selectLongWords = true; + $formerLineStart = e.session.$useEmacsStyleLineStart; + e.session.$useEmacsStyleLineStart = true; + + if (!e.session.hasOwnProperty('$emacsMark')) + e.session.$emacsMark = null; + if (!e.session.hasOwnProperty('$emacsMarkRing')) + e.session.$emacsMarkRing = []; +}; + +var $resetMarkMode = function(e) { + e.editor.session.$emacsMark = null; +}; + +var keys = acequire("../lib/keys").KEY_MODS; +var eMods = {C: "ctrl", S: "shift", M: "alt", CMD: "command"}; +var combinations = ["C-S-M-CMD", + "S-M-CMD", "C-M-CMD", "C-S-CMD", "C-S-M", + "M-CMD", "S-CMD", "S-M", "C-CMD", "C-M", "C-S", + "CMD", "M", "S", "C"]; +combinations.forEach(function(c) { + var hashId = 0; + c.split("-").forEach(function(c) { + hashId = hashId | keys[eMods[c]]; + }); + eMods[hashId] = c.toLowerCase() + "-"; +}); + +exports.handler.onCopy = function(e, editor) { + if (editor.$handlesEmacsOnCopy) return; + editor.$handlesEmacsOnCopy = true; + exports.handler.commands.killRingSave.exec(editor); + editor.$handlesEmacsOnCopy = false; +}; + +exports.handler.onPaste = function(e, editor) { + editor.pushEmacsMark(editor.getCursorPosition()); +}; + +exports.handler.bindKey = function(key, command) { + if (typeof key == "object") + key = key[this.platform]; + if (!key) + return; + + var ckb = this.commandKeyBinding; + key.split("|").forEach(function(keyPart) { + keyPart = keyPart.toLowerCase(); + ckb[keyPart] = command; + var keyParts = keyPart.split(" ").slice(0,-1); + keyParts.reduce(function(keyMapKeys, keyPart, i) { + var prefix = keyMapKeys[i-1] ? keyMapKeys[i-1] + ' ' : ''; + return keyMapKeys.concat([prefix + keyPart]); + }, []).forEach(function(keyPart) { + if (!ckb[keyPart]) ckb[keyPart] = "null"; + }); + }, this); +}; + +exports.handler.getStatusText = function(editor, data) { + var str = ""; + if (data.count) + str += data.count; + if (data.keyChain) + str += " " + data.keyChain + return str; +}; + +exports.handler.handleKeyboard = function(data, hashId, key, keyCode) { + if (keyCode === -1) return undefined; + + var editor = data.editor; + editor._signal("changeStatus"); + if (hashId == -1) { + editor.pushEmacsMark(); + if (data.count) { + var str = new Array(data.count + 1).join(key); + data.count = null; + return {command: "insertstring", args: str}; + } + } + + var modifier = eMods[hashId]; + if (modifier == "c-" || data.count) { + var count = parseInt(key[key.length - 1]); + if (typeof count === 'number' && !isNaN(count)) { + data.count = Math.max(data.count, 0) || 0; + data.count = 10 * data.count + count; + return {command: "null"}; + } + } + if (modifier) key = modifier + key; + if (data.keyChain) key = data.keyChain += " " + key; + var command = this.commandKeyBinding[key]; + data.keyChain = command == "null" ? key : ""; + if (!command) return undefined; + if (command === "null") return {command: "null"}; + + if (command === "universalArgument") { + data.count = -4; + return {command: "null"}; + } + var args; + if (typeof command !== "string") { + args = command.args; + if (command.command) command = command.command; + if (command === "goorselect") { + command = editor.emacsMark() ? args[1] : args[0]; + args = null; + } + } + + if (typeof command === "string") { + if (command === "insertstring" || + command === "splitline" || + command === "togglecomment") { + editor.pushEmacsMark(); + } + command = this.commands[command] || editor.commands.commands[command]; + if (!command) return undefined; + } + + if (!command.readOnly && !command.isYank) + data.lastCommand = null; + + if (!command.readOnly && editor.emacsMark()) + editor.setEmacsMark(null) + + if (data.count) { + var count = data.count; + data.count = 0; + if (!command || !command.handlesCount) { + return { + args: args, + command: { + exec: function(editor, args) { + for (var i = 0; i < count; i++) + command.exec(editor, args); + }, + multiSelectAction: command.multiSelectAction + } + }; + } else { + if (!args) args = {}; + if (typeof args === 'object') args.count = count; + } + } + + return {command: command, args: args}; +}; + +exports.emacsKeys = { + "Up|C-p" : {command: "goorselect", args: ["golineup","selectup"]}, + "Down|C-n" : {command: "goorselect", args: ["golinedown","selectdown"]}, + "Left|C-b" : {command: "goorselect", args: ["gotoleft","selectleft"]}, + "Right|C-f" : {command: "goorselect", args: ["gotoright","selectright"]}, + "C-Left|M-b" : {command: "goorselect", args: ["gotowordleft","selectwordleft"]}, + "C-Right|M-f" : {command: "goorselect", args: ["gotowordright","selectwordright"]}, + "Home|C-a" : {command: "goorselect", args: ["gotolinestart","selecttolinestart"]}, + "End|C-e" : {command: "goorselect", args: ["gotolineend","selecttolineend"]}, + "C-Home|S-M-,": {command: "goorselect", args: ["gotostart","selecttostart"]}, + "C-End|S-M-." : {command: "goorselect", args: ["gotoend","selecttoend"]}, + "S-Up|S-C-p" : "selectup", + "S-Down|S-C-n" : "selectdown", + "S-Left|S-C-b" : "selectleft", + "S-Right|S-C-f" : "selectright", + "S-C-Left|S-M-b" : "selectwordleft", + "S-C-Right|S-M-f" : "selectwordright", + "S-Home|S-C-a" : "selecttolinestart", + "S-End|S-C-e" : "selecttolineend", + "S-C-Home" : "selecttostart", + "S-C-End" : "selecttoend", + + "C-l" : "recenterTopBottom", + "M-s" : "centerselection", + "M-g": "gotoline", + "C-x C-p": "selectall", + "C-Down": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, + "C-Up": {command: "goorselect", args: ["gotopageup","selectpageup"]}, + "PageDown|C-v": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, + "PageUp|M-v": {command: "goorselect", args: ["gotopageup","selectpageup"]}, + "S-C-Down": "selectpagedown", + "S-C-Up": "selectpageup", + + "C-s": "iSearch", + "C-r": "iSearchBackwards", + + "M-C-s": "findnext", + "M-C-r": "findprevious", + "S-M-5": "replace", + "Backspace": "backspace", + "Delete|C-d": "del", + "Return|C-m": {command: "insertstring", args: "\n"}, // "newline" + "C-o": "splitline", + + "M-d|C-Delete": {command: "killWord", args: "right"}, + "C-Backspace|M-Backspace|M-Delete": {command: "killWord", args: "left"}, + "C-k": "killLine", + + "C-y|S-Delete": "yank", + "M-y": "yankRotate", + "C-g": "keyboardQuit", + + "C-w|C-S-W": "killRegion", + "M-w": "killRingSave", + "C-Space": "setMark", + "C-x C-x": "exchangePointAndMark", + + "C-t": "transposeletters", + "M-u": "touppercase", // Doesn't work + "M-l": "tolowercase", + "M-/": "autocomplete", // Doesn't work + "C-u": "universalArgument", + + "M-;": "togglecomment", + + "C-/|C-x u|S-C--|C-z": "undo", + "S-C-/|S-C-x u|C--|S-C-z": "redo", // infinite undo? + "C-x r": "selectRectangularRegion", + "M-x": {command: "focusCommandLine", args: "M-x "} +}; + + +exports.handler.bindKeys(exports.emacsKeys); + +exports.handler.addCommands({ + recenterTopBottom: function(editor) { + var renderer = editor.renderer; + var pos = renderer.$cursorLayer.getPixelPosition(); + var h = renderer.$size.scrollerHeight - renderer.lineHeight; + var scrollTop = renderer.scrollTop; + if (Math.abs(pos.top - scrollTop) < 2) { + scrollTop = pos.top - h; + } else if (Math.abs(pos.top - scrollTop - h * 0.5) < 2) { + scrollTop = pos.top; + } else { + scrollTop = pos.top - h * 0.5; + } + editor.session.setScrollTop(scrollTop); + }, + selectRectangularRegion: function(editor) { + editor.multiSelect.toggleBlockSelection(); + }, + setMark: { + exec: function(editor, args) { + + if (args && args.count) { + if (editor.inMultiSelectMode) editor.forEachSelection(moveToMark); + else moveToMark(); + moveToMark(); + return; + } + + var mark = editor.emacsMark(), + ranges = editor.selection.getAllRanges(), + rangePositions = ranges.map(function(r) { return {row: r.start.row, column: r.start.column}; }), + transientMarkModeActive = true, + hasNoSelection = ranges.every(function(range) { return range.isEmpty(); }); + if (transientMarkModeActive && (mark || !hasNoSelection)) { + if (editor.inMultiSelectMode) editor.forEachSelection({exec: editor.clearSelection.bind(editor)}); + else editor.clearSelection(); + if (mark) editor.pushEmacsMark(null); + return; + } + + if (!mark) { + rangePositions.forEach(function(pos) { editor.pushEmacsMark(pos); }); + editor.setEmacsMark(rangePositions[rangePositions.length-1]); + return; + } + + function moveToMark() { + var mark = editor.popEmacsMark(); + mark && editor.moveCursorToPosition(mark); + } + + }, + readOnly: true, + handlesCount: true + }, + exchangePointAndMark: { + exec: function exchangePointAndMark$exec(editor, args) { + var sel = editor.selection; + if (!args.count && !sel.isEmpty()) { // just invert selection + sel.setSelectionRange(sel.getRange(), !sel.isBackwards()); + return; + } + + if (args.count) { // replace mark and point + var pos = {row: sel.lead.row, column: sel.lead.column}; + sel.clearSelection(); + sel.moveCursorToPosition(editor.emacsMarkForSelection(pos)); + } else { // create selection to last mark + sel.selectToPosition(editor.emacsMarkForSelection()); + } + }, + readOnly: true, + handlesCount: true, + multiSelectAction: "forEach" + }, + killWord: { + exec: function(editor, dir) { + editor.clearSelection(); + if (dir == "left") + editor.selection.selectWordLeft(); + else + editor.selection.selectWordRight(); + + var range = editor.getSelectionRange(); + var text = editor.session.getTextRange(range); + exports.killRing.add(text); + + editor.session.remove(range); + editor.clearSelection(); + }, + multiSelectAction: "forEach" + }, + killLine: function(editor) { + editor.pushEmacsMark(null); + editor.clearSelection(); + var range = editor.getSelectionRange(); + var line = editor.session.getLine(range.start.row); + range.end.column = line.length; + line = line.substr(range.start.column) + + var foldLine = editor.session.getFoldLine(range.start.row); + if (foldLine && range.end.row != foldLine.end.row) { + range.end.row = foldLine.end.row; + line = "x"; + } + if (/^\s*$/.test(line)) { + range.end.row++; + line = editor.session.getLine(range.end.row); + range.end.column = /^\s*$/.test(line) ? line.length : 0; + } + var text = editor.session.getTextRange(range); + if (editor.prevOp.command == this) + exports.killRing.append(text); + else + exports.killRing.add(text); + + editor.session.remove(range); + editor.clearSelection(); + }, + yank: function(editor) { + editor.onPaste(exports.killRing.get() || ''); + editor.keyBinding.$data.lastCommand = "yank"; + }, + yankRotate: function(editor) { + if (editor.keyBinding.$data.lastCommand != "yank") + return; + editor.undo(); + editor.session.$emacsMarkRing.pop(); // also undo recording mark + editor.onPaste(exports.killRing.rotate()); + editor.keyBinding.$data.lastCommand = "yank"; + }, + killRegion: { + exec: function(editor) { + exports.killRing.add(editor.getCopyText()); + editor.commands.byName.cut.exec(editor); + editor.setEmacsMark(null); + }, + readOnly: true, + multiSelectAction: "forEach" + }, + killRingSave: { + exec: function(editor) { + + editor.$handlesEmacsOnCopy = true; + var marks = editor.session.$emacsMarkRing.slice(), + deselectedMarks = []; + exports.killRing.add(editor.getCopyText()); + + setTimeout(function() { + function deselect() { + var sel = editor.selection, range = sel.getRange(), + pos = sel.isBackwards() ? range.end : range.start; + deselectedMarks.push({row: pos.row, column: pos.column}); + sel.clearSelection(); + } + editor.$handlesEmacsOnCopy = false; + if (editor.inMultiSelectMode) editor.forEachSelection({exec: deselect}); + else deselect(); + editor.session.$emacsMarkRing = marks.concat(deselectedMarks.reverse()); + }, 0); + }, + readOnly: true + }, + keyboardQuit: function(editor) { + editor.selection.clearSelection(); + editor.setEmacsMark(null); + editor.keyBinding.$data.count = null; + }, + focusCommandLine: function(editor, arg) { + if (editor.showCommandLine) + editor.showCommandLine(arg); + } +}); + +exports.handler.addCommands(iSearchCommandModule.iSearchStartCommands); + +var commands = exports.handler.commands; +commands.yank.isYank = true; +commands.yankRotate.isYank = true; + +exports.killRing = { + $data: [], + add: function(str) { + str && this.$data.push(str); + if (this.$data.length > 30) + this.$data.shift(); + }, + append: function(str) { + var idx = this.$data.length - 1; + var text = this.$data[idx] || ""; + if (str) text += str; + if (text) this.$data[idx] = text; + }, + get: function(n) { + n = n || 1; + return this.$data.slice(this.$data.length-n, this.$data.length).reverse().join('\n'); + }, + pop: function() { + if (this.$data.length > 1) + this.$data.pop(); + return this.get(); + }, + rotate: function() { + this.$data.unshift(this.$data.pop()); + return this.get(); + } +}; + +}); + + +/***/ }), +/* 67 */ +/***/ (function(module, exports) { + +ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"], function(acequire, exports, module) { +"use strict"; +var oop = acequire("./lib/oop"); +var EventEmitter = acequire("./lib/event_emitter").EventEmitter; +var lang = acequire("./lib/lang"); +var Range = acequire("./range").Range; +var Anchor = acequire("./anchor").Anchor; +var HashHandler = acequire("./keyboard/hash_handler").HashHandler; +var Tokenizer = acequire("./tokenizer").Tokenizer; +var comparePoints = Range.comparePoints; + +var SnippetManager = function() { + this.snippetMap = {}; + this.snippetNameMap = {}; +}; + +(function() { + oop.implement(this, EventEmitter); + + this.getTokenizer = function() { + function TabstopToken(str, _, stack) { + str = str.substr(1); + if (/^\d+$/.test(str) && !stack.inFormatString) + return [{tabstopId: parseInt(str, 10)}]; + return [{text: str}]; + } + function escape(ch) { + return "(?:[^\\\\" + ch + "]|\\\\.)"; + } + SnippetManager.$tokenizer = new Tokenizer({ + start: [ + {regex: /:/, onMatch: function(val, state, stack) { + if (stack.length && stack[0].expectIf) { + stack[0].expectIf = false; + stack[0].elseBranch = stack[0]; + return [stack[0]]; + } + return ":"; + }}, + {regex: /\\./, onMatch: function(val, state, stack) { + var ch = val[1]; + if (ch == "}" && stack.length) { + val = ch; + }else if ("`$\\".indexOf(ch) != -1) { + val = ch; + } else if (stack.inFormatString) { + if (ch == "n") + val = "\n"; + else if (ch == "t") + val = "\n"; + else if ("ulULE".indexOf(ch) != -1) { + val = {changeCase: ch, local: ch > "a"}; + } + } + + return [val]; + }}, + {regex: /}/, onMatch: function(val, state, stack) { + return [stack.length ? stack.shift() : val]; + }}, + {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken}, + {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) { + var t = TabstopToken(str.substr(1), state, stack); + stack.unshift(t[0]); + return t; + }, next: "snippetVar"}, + {regex: /\n/, token: "newline", merge: false} + ], + snippetVar: [ + {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) { + stack[0].choices = val.slice(1, -1).split(","); + }, next: "start"}, + {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?", + onMatch: function(val, state, stack) { + var ts = stack[0]; + ts.fmtString = val; + + val = this.splitRegex.exec(val); + ts.guard = val[1]; + ts.fmt = val[2]; + ts.flag = val[3]; + return ""; + }, next: "start"}, + {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) { + stack[0].code = val.splice(1, -1); + return ""; + }, next: "start"}, + {regex: "\\?", onMatch: function(val, state, stack) { + if (stack[0]) + stack[0].expectIf = true; + }, next: "start"}, + {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"} + ], + formatString: [ + {regex: "/(" + escape("/") + "+)/", token: "regex"}, + {regex: "", onMatch: function(val, state, stack) { + stack.inFormatString = true; + }, next: "start"} + ] + }); + SnippetManager.prototype.getTokenizer = function() { + return SnippetManager.$tokenizer; + }; + return SnippetManager.$tokenizer; + }; + + this.tokenizeTmSnippet = function(str, startState) { + return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) { + return x.value || x; + }); + }; + + this.$getDefaultValue = function(editor, name) { + if (/^[A-Z]\d+$/.test(name)) { + var i = name.substr(1); + return (this.variables[name[0] + "__"] || {})[i]; + } + if (/^\d+$/.test(name)) { + return (this.variables.__ || {})[name]; + } + name = name.replace(/^TM_/, ""); + + if (!editor) + return; + var s = editor.session; + switch(name) { + case "CURRENT_WORD": + var r = s.getWordRange(); + case "SELECTION": + case "SELECTED_TEXT": + return s.getTextRange(r); + case "CURRENT_LINE": + return s.getLine(editor.getCursorPosition().row); + case "PREV_LINE": // not possible in textmate + return s.getLine(editor.getCursorPosition().row - 1); + case "LINE_INDEX": + return editor.getCursorPosition().column; + case "LINE_NUMBER": + return editor.getCursorPosition().row + 1; + case "SOFT_TABS": + return s.getUseSoftTabs() ? "YES" : "NO"; + case "TAB_SIZE": + return s.getTabSize(); + case "FILENAME": + case "FILEPATH": + return ""; + case "FULLNAME": + return "Ace"; + } + }; + this.variables = {}; + this.getVariableValue = function(editor, varName) { + if (this.variables.hasOwnProperty(varName)) + return this.variables[varName](editor, varName) || ""; + return this.$getDefaultValue(editor, varName) || ""; + }; + this.tmStrFormat = function(str, ch, editor) { + var flag = ch.flag || ""; + var re = ch.guard; + re = new RegExp(re, flag.replace(/[^gi]/, "")); + var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString"); + var _self = this; + var formatted = str.replace(re, function() { + _self.variables.__ = arguments; + var fmtParts = _self.resolveVariables(fmtTokens, editor); + var gChangeCase = "E"; + for (var i = 0; i < fmtParts.length; i++) { + var ch = fmtParts[i]; + if (typeof ch == "object") { + fmtParts[i] = ""; + if (ch.changeCase && ch.local) { + var next = fmtParts[i + 1]; + if (next && typeof next == "string") { + if (ch.changeCase == "u") + fmtParts[i] = next[0].toUpperCase(); + else + fmtParts[i] = next[0].toLowerCase(); + fmtParts[i + 1] = next.substr(1); + } + } else if (ch.changeCase) { + gChangeCase = ch.changeCase; + } + } else if (gChangeCase == "U") { + fmtParts[i] = ch.toUpperCase(); + } else if (gChangeCase == "L") { + fmtParts[i] = ch.toLowerCase(); + } + } + return fmtParts.join(""); + }); + this.variables.__ = null; + return formatted; + }; + + this.resolveVariables = function(snippet, editor) { + var result = []; + for (var i = 0; i < snippet.length; i++) { + var ch = snippet[i]; + if (typeof ch == "string") { + result.push(ch); + } else if (typeof ch != "object") { + continue; + } else if (ch.skip) { + gotoNext(ch); + } else if (ch.processed < i) { + continue; + } else if (ch.text) { + var value = this.getVariableValue(editor, ch.text); + if (value && ch.fmtString) + value = this.tmStrFormat(value, ch); + ch.processed = i; + if (ch.expectIf == null) { + if (value) { + result.push(value); + gotoNext(ch); + } + } else { + if (value) { + ch.skip = ch.elseBranch; + } else + gotoNext(ch); + } + } else if (ch.tabstopId != null) { + result.push(ch); + } else if (ch.changeCase != null) { + result.push(ch); + } + } + function gotoNext(ch) { + var i1 = snippet.indexOf(ch, i + 1); + if (i1 != -1) + i = i1; + } + return result; + }; + + this.insertSnippetForSelection = function(editor, snippetText) { + var cursor = editor.getCursorPosition(); + var line = editor.session.getLine(cursor.row); + var tabString = editor.session.getTabString(); + var indentString = line.match(/^\s*/)[0]; + + if (cursor.column < indentString.length) + indentString = indentString.slice(0, cursor.column); + + snippetText = snippetText.replace(/\r/g, ""); + var tokens = this.tokenizeTmSnippet(snippetText); + tokens = this.resolveVariables(tokens, editor); + tokens = tokens.map(function(x) { + if (x == "\n") + return x + indentString; + if (typeof x == "string") + return x.replace(/\t/g, tabString); + return x; + }); + var tabstops = []; + tokens.forEach(function(p, i) { + if (typeof p != "object") + return; + var id = p.tabstopId; + var ts = tabstops[id]; + if (!ts) { + ts = tabstops[id] = []; + ts.index = id; + ts.value = ""; + } + if (ts.indexOf(p) !== -1) + return; + ts.push(p); + var i1 = tokens.indexOf(p, i + 1); + if (i1 === -1) + return; + + var value = tokens.slice(i + 1, i1); + var isNested = value.some(function(t) {return typeof t === "object"}); + if (isNested && !ts.value) { + ts.value = value; + } else if (value.length && (!ts.value || typeof ts.value !== "string")) { + ts.value = value.join(""); + } + }); + tabstops.forEach(function(ts) {ts.length = 0}); + var expanding = {}; + function copyValue(val) { + var copy = []; + for (var i = 0; i < val.length; i++) { + var p = val[i]; + if (typeof p == "object") { + if (expanding[p.tabstopId]) + continue; + var j = val.lastIndexOf(p, i - 1); + p = copy[j] || {tabstopId: p.tabstopId}; + } + copy[i] = p; + } + return copy; + } + for (var i = 0; i < tokens.length; i++) { + var p = tokens[i]; + if (typeof p != "object") + continue; + var id = p.tabstopId; + var i1 = tokens.indexOf(p, i + 1); + if (expanding[id]) { + if (expanding[id] === p) + expanding[id] = null; + continue; + } + + var ts = tabstops[id]; + var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value); + arg.unshift(i + 1, Math.max(0, i1 - i)); + arg.push(p); + expanding[id] = p; + tokens.splice.apply(tokens, arg); + + if (ts.indexOf(p) === -1) + ts.push(p); + } + var row = 0, column = 0; + var text = ""; + tokens.forEach(function(t) { + if (typeof t === "string") { + var lines = t.split("\n"); + if (lines.length > 1){ + column = lines[lines.length - 1].length; + row += lines.length - 1; + } else + column += t.length; + text += t; + } else { + if (!t.start) + t.start = {row: row, column: column}; + else + t.end = {row: row, column: column}; + } + }); + var range = editor.getSelectionRange(); + var end = editor.session.replace(range, text); + + var tabstopManager = new TabstopManager(editor); + var selectionId = editor.inVirtualSelectionMode && editor.selection.index; + tabstopManager.addTabstops(tabstops, range.start, end, selectionId); + }; + + this.insertSnippet = function(editor, snippetText) { + var self = this; + if (editor.inVirtualSelectionMode) + return self.insertSnippetForSelection(editor, snippetText); + + editor.forEachSelection(function() { + self.insertSnippetForSelection(editor, snippetText); + }, null, {keepOrder: true}); + + if (editor.tabstopManager) + editor.tabstopManager.tabNext(); + }; + + this.$getScope = function(editor) { + var scope = editor.session.$mode.$id || ""; + scope = scope.split("/").pop(); + if (scope === "html" || scope === "php") { + if (scope === "php" && !editor.session.$mode.inlinePhp) + scope = "html"; + var c = editor.getCursorPosition(); + var state = editor.session.getState(c.row); + if (typeof state === "object") { + state = state[0]; + } + if (state.substring) { + if (state.substring(0, 3) == "js-") + scope = "javascript"; + else if (state.substring(0, 4) == "css-") + scope = "css"; + else if (state.substring(0, 4) == "php-") + scope = "php"; + } + } + + return scope; + }; + + this.getActiveScopes = function(editor) { + var scope = this.$getScope(editor); + var scopes = [scope]; + var snippetMap = this.snippetMap; + if (snippetMap[scope] && snippetMap[scope].includeScopes) { + scopes.push.apply(scopes, snippetMap[scope].includeScopes); + } + scopes.push("_"); + return scopes; + }; + + this.expandWithTab = function(editor, options) { + var self = this; + var result = editor.forEachSelection(function() { + return self.expandSnippetForSelection(editor, options); + }, null, {keepOrder: true}); + if (result && editor.tabstopManager) + editor.tabstopManager.tabNext(); + return result; + }; + + this.expandSnippetForSelection = function(editor, options) { + var cursor = editor.getCursorPosition(); + var line = editor.session.getLine(cursor.row); + var before = line.substring(0, cursor.column); + var after = line.substr(cursor.column); + + var snippetMap = this.snippetMap; + var snippet; + this.getActiveScopes(editor).some(function(scope) { + var snippets = snippetMap[scope]; + if (snippets) + snippet = this.findMatchingSnippet(snippets, before, after); + return !!snippet; + }, this); + if (!snippet) + return false; + if (options && options.dryRun) + return true; + editor.session.doc.removeInLine(cursor.row, + cursor.column - snippet.replaceBefore.length, + cursor.column + snippet.replaceAfter.length + ); + + this.variables.M__ = snippet.matchBefore; + this.variables.T__ = snippet.matchAfter; + this.insertSnippetForSelection(editor, snippet.content); + + this.variables.M__ = this.variables.T__ = null; + return true; + }; + + this.findMatchingSnippet = function(snippetList, before, after) { + for (var i = snippetList.length; i--;) { + var s = snippetList[i]; + if (s.startRe && !s.startRe.test(before)) + continue; + if (s.endRe && !s.endRe.test(after)) + continue; + if (!s.startRe && !s.endRe) + continue; + + s.matchBefore = s.startRe ? s.startRe.exec(before) : [""]; + s.matchAfter = s.endRe ? s.endRe.exec(after) : [""]; + s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : ""; + s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : ""; + return s; + } + }; + + this.snippetMap = {}; + this.snippetNameMap = {}; + this.register = function(snippets, scope) { + var snippetMap = this.snippetMap; + var snippetNameMap = this.snippetNameMap; + var self = this; + + if (!snippets) + snippets = []; + + function wrapRegexp(src) { + if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src)) + src = "(?:" + src + ")"; + + return src || ""; + } + function guardedRegexp(re, guard, opening) { + re = wrapRegexp(re); + guard = wrapRegexp(guard); + if (opening) { + re = guard + re; + if (re && re[re.length - 1] != "$") + re = re + "$"; + } else { + re = re + guard; + if (re && re[0] != "^") + re = "^" + re; + } + return new RegExp(re); + } + + function addSnippet(s) { + if (!s.scope) + s.scope = scope || "_"; + scope = s.scope; + if (!snippetMap[scope]) { + snippetMap[scope] = []; + snippetNameMap[scope] = {}; + } + + var map = snippetNameMap[scope]; + if (s.name) { + var old = map[s.name]; + if (old) + self.unregister(old); + map[s.name] = s; + } + snippetMap[scope].push(s); + + if (s.tabTrigger && !s.trigger) { + if (!s.guard && /^\w/.test(s.tabTrigger)) + s.guard = "\\b"; + s.trigger = lang.escapeRegExp(s.tabTrigger); + } + + if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard) + return; + + s.startRe = guardedRegexp(s.trigger, s.guard, true); + s.triggerRe = new RegExp(s.trigger, "", true); + + s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true); + s.endTriggerRe = new RegExp(s.endTrigger, "", true); + } + + if (snippets && snippets.content) + addSnippet(snippets); + else if (Array.isArray(snippets)) + snippets.forEach(addSnippet); + + this._signal("registerSnippets", {scope: scope}); + }; + this.unregister = function(snippets, scope) { + var snippetMap = this.snippetMap; + var snippetNameMap = this.snippetNameMap; + + function removeSnippet(s) { + var nameMap = snippetNameMap[s.scope||scope]; + if (nameMap && nameMap[s.name]) { + delete nameMap[s.name]; + var map = snippetMap[s.scope||scope]; + var i = map && map.indexOf(s); + if (i >= 0) + map.splice(i, 1); + } + } + if (snippets.content) + removeSnippet(snippets); + else if (Array.isArray(snippets)) + snippets.forEach(removeSnippet); + }; + this.parseSnippetFile = function(str) { + str = str.replace(/\r/g, ""); + var list = [], snippet = {}; + var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm; + var m; + while (m = re.exec(str)) { + if (m[1]) { + try { + snippet = JSON.parse(m[1]); + list.push(snippet); + } catch (e) {} + } if (m[4]) { + snippet.content = m[4].replace(/^\t/gm, ""); + list.push(snippet); + snippet = {}; + } else { + var key = m[2], val = m[3]; + if (key == "regex") { + var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g; + snippet.guard = guardRe.exec(val)[1]; + snippet.trigger = guardRe.exec(val)[1]; + snippet.endTrigger = guardRe.exec(val)[1]; + snippet.endGuard = guardRe.exec(val)[1]; + } else if (key == "snippet") { + snippet.tabTrigger = val.match(/^\S*/)[0]; + if (!snippet.name) + snippet.name = val; + } else { + snippet[key] = val; + } + } + } + return list; + }; + this.getSnippetByName = function(name, editor) { + var snippetMap = this.snippetNameMap; + var snippet; + this.getActiveScopes(editor).some(function(scope) { + var snippets = snippetMap[scope]; + if (snippets) + snippet = snippets[name]; + return !!snippet; + }, this); + return snippet; + }; + +}).call(SnippetManager.prototype); + + +var TabstopManager = function(editor) { + if (editor.tabstopManager) + return editor.tabstopManager; + editor.tabstopManager = this; + this.$onChange = this.onChange.bind(this); + this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule; + this.$onChangeSession = this.onChangeSession.bind(this); + this.$onAfterExec = this.onAfterExec.bind(this); + this.attach(editor); +}; +(function() { + this.attach = function(editor) { + this.index = 0; + this.ranges = []; + this.tabstops = []; + this.$openTabstops = null; + this.selectedTabstop = null; + + this.editor = editor; + this.editor.on("change", this.$onChange); + this.editor.on("changeSelection", this.$onChangeSelection); + this.editor.on("changeSession", this.$onChangeSession); + this.editor.commands.on("afterExec", this.$onAfterExec); + this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); + }; + this.detach = function() { + this.tabstops.forEach(this.removeTabstopMarkers, this); + this.ranges = null; + this.tabstops = null; + this.selectedTabstop = null; + this.editor.removeListener("change", this.$onChange); + this.editor.removeListener("changeSelection", this.$onChangeSelection); + this.editor.removeListener("changeSession", this.$onChangeSession); + this.editor.commands.removeListener("afterExec", this.$onAfterExec); + this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); + this.editor.tabstopManager = null; + this.editor = null; + }; + + this.onChange = function(delta) { + var changeRange = delta; + var isRemove = delta.action[0] == "r"; + var start = delta.start; + var end = delta.end; + var startRow = start.row; + var endRow = end.row; + var lineDif = endRow - startRow; + var colDiff = end.column - start.column; + + if (isRemove) { + lineDif = -lineDif; + colDiff = -colDiff; + } + if (!this.$inChange && isRemove) { + var ts = this.selectedTabstop; + var changedOutside = ts && !ts.some(function(r) { + return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0; + }); + if (changedOutside) + return this.detach(); + } + var ranges = this.ranges; + for (var i = 0; i < ranges.length; i++) { + var r = ranges[i]; + if (r.end.row < start.row) + continue; + + if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) { + this.removeRange(r); + i--; + continue; + } + + if (r.start.row == startRow && r.start.column > start.column) + r.start.column += colDiff; + if (r.end.row == startRow && r.end.column >= start.column) + r.end.column += colDiff; + if (r.start.row >= startRow) + r.start.row += lineDif; + if (r.end.row >= startRow) + r.end.row += lineDif; + + if (comparePoints(r.start, r.end) > 0) + this.removeRange(r); + } + if (!ranges.length) + this.detach(); + }; + this.updateLinkedFields = function() { + var ts = this.selectedTabstop; + if (!ts || !ts.hasLinkedRanges) + return; + this.$inChange = true; + var session = this.editor.session; + var text = session.getTextRange(ts.firstNonLinked); + for (var i = ts.length; i--;) { + var range = ts[i]; + if (!range.linked) + continue; + var fmt = exports.snippetManager.tmStrFormat(text, range.original); + session.replace(range, fmt); + } + this.$inChange = false; + }; + this.onAfterExec = function(e) { + if (e.command && !e.command.readOnly) + this.updateLinkedFields(); + }; + this.onChangeSelection = function() { + if (!this.editor) + return; + var lead = this.editor.selection.lead; + var anchor = this.editor.selection.anchor; + var isEmpty = this.editor.selection.isEmpty(); + for (var i = this.ranges.length; i--;) { + if (this.ranges[i].linked) + continue; + var containsLead = this.ranges[i].contains(lead.row, lead.column); + var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column); + if (containsLead && containsAnchor) + return; + } + this.detach(); + }; + this.onChangeSession = function() { + this.detach(); + }; + this.tabNext = function(dir) { + var max = this.tabstops.length; + var index = this.index + (dir || 1); + index = Math.min(Math.max(index, 1), max); + if (index == max) + index = 0; + this.selectTabstop(index); + if (index === 0) + this.detach(); + }; + this.selectTabstop = function(index) { + this.$openTabstops = null; + var ts = this.tabstops[this.index]; + if (ts) + this.addTabstopMarkers(ts); + this.index = index; + ts = this.tabstops[this.index]; + if (!ts || !ts.length) + return; + + this.selectedTabstop = ts; + if (!this.editor.inVirtualSelectionMode) { + var sel = this.editor.multiSelect; + sel.toSingleRange(ts.firstNonLinked.clone()); + for (var i = ts.length; i--;) { + if (ts.hasLinkedRanges && ts[i].linked) + continue; + sel.addRange(ts[i].clone(), true); + } + if (sel.ranges[0]) + sel.addRange(sel.ranges[0].clone()); + } else { + this.editor.selection.setRange(ts.firstNonLinked); + } + + this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); + }; + this.addTabstops = function(tabstops, start, end) { + if (!this.$openTabstops) + this.$openTabstops = []; + if (!tabstops[0]) { + var p = Range.fromPoints(end, end); + moveRelative(p.start, start); + moveRelative(p.end, start); + tabstops[0] = [p]; + tabstops[0].index = 0; + } + + var i = this.index; + var arg = [i + 1, 0]; + var ranges = this.ranges; + tabstops.forEach(function(ts, index) { + var dest = this.$openTabstops[index] || ts; + + for (var i = ts.length; i--;) { + var p = ts[i]; + var range = Range.fromPoints(p.start, p.end || p.start); + movePoint(range.start, start); + movePoint(range.end, start); + range.original = p; + range.tabstop = dest; + ranges.push(range); + if (dest != ts) + dest.unshift(range); + else + dest[i] = range; + if (p.fmtString) { + range.linked = true; + dest.hasLinkedRanges = true; + } else if (!dest.firstNonLinked) + dest.firstNonLinked = range; + } + if (!dest.firstNonLinked) + dest.hasLinkedRanges = false; + if (dest === ts) { + arg.push(dest); + this.$openTabstops[index] = dest; + } + this.addTabstopMarkers(dest); + }, this); + + if (arg.length > 2) { + if (this.tabstops.length) + arg.push(arg.splice(2, 1)[0]); + this.tabstops.splice.apply(this.tabstops, arg); + } + }; + + this.addTabstopMarkers = function(ts) { + var session = this.editor.session; + ts.forEach(function(range) { + if (!range.markerId) + range.markerId = session.addMarker(range, "ace_snippet-marker", "text"); + }); + }; + this.removeTabstopMarkers = function(ts) { + var session = this.editor.session; + ts.forEach(function(range) { + session.removeMarker(range.markerId); + range.markerId = null; + }); + }; + this.removeRange = function(range) { + var i = range.tabstop.indexOf(range); + range.tabstop.splice(i, 1); + i = this.ranges.indexOf(range); + this.ranges.splice(i, 1); + this.editor.session.removeMarker(range.markerId); + if (!range.tabstop.length) { + i = this.tabstops.indexOf(range.tabstop); + if (i != -1) + this.tabstops.splice(i, 1); + if (!this.tabstops.length) + this.detach(); + } + }; + + this.keyboardHandler = new HashHandler(); + this.keyboardHandler.bindKeys({ + "Tab": function(ed) { + if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) { + return; + } + + ed.tabstopManager.tabNext(1); + }, + "Shift-Tab": function(ed) { + ed.tabstopManager.tabNext(-1); + }, + "Esc": function(ed) { + ed.tabstopManager.detach(); + }, + "Return": function(ed) { + return false; + } + }); +}).call(TabstopManager.prototype); + + + +var changeTracker = {}; +changeTracker.onChange = Anchor.prototype.onChange; +changeTracker.setPosition = function(row, column) { + this.pos.row = row; + this.pos.column = column; +}; +changeTracker.update = function(pos, delta, $insertRight) { + this.$insertRight = $insertRight; + this.pos = pos; + this.onChange(delta); +}; + +var movePoint = function(point, diff) { + if (point.row == 0) + point.column += diff.column; + point.row += diff.row; +}; + +var moveRelative = function(point, start) { + if (point.row == start.row) + point.column -= start.column; + point.row -= start.row; +}; + + +acequire("./lib/dom").importCssString("\ +.ace_snippet-marker {\ + -moz-box-sizing: border-box;\ + box-sizing: border-box;\ + background: rgba(194, 193, 208, 0.09);\ + border: 1px dotted rgba(211, 208, 235, 0.62);\ + position: absolute;\ +}"); + +exports.snippetManager = new SnippetManager(); + + +var Editor = acequire("./editor").Editor; +(function() { + this.insertSnippet = function(content, options) { + return exports.snippetManager.insertSnippet(this, content, options); + }; + this.expandSnippet = function(options) { + return exports.snippetManager.expandWithTab(this, options); + }; +}).call(Editor.prototype); + +}); + +ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(acequire, exports, module) { +"use strict"; + +var Renderer = acequire("../virtual_renderer").VirtualRenderer; +var Editor = acequire("../editor").Editor; +var Range = acequire("../range").Range; +var event = acequire("../lib/event"); +var lang = acequire("../lib/lang"); +var dom = acequire("../lib/dom"); + +var $singleLineEditor = function(el) { + var renderer = new Renderer(el); + + renderer.$maxLines = 4; + + var editor = new Editor(renderer); + + editor.setHighlightActiveLine(false); + editor.setShowPrintMargin(false); + editor.renderer.setShowGutter(false); + editor.renderer.setHighlightGutterLine(false); + + editor.$mouseHandler.$focusWaitTimout = 0; + editor.$highlightTagPending = true; + + return editor; +}; + +var AcePopup = function(parentNode) { + var el = dom.createElement("div"); + var popup = new $singleLineEditor(el); + + if (parentNode) + parentNode.appendChild(el); + el.style.display = "none"; + popup.renderer.content.style.cursor = "default"; + popup.renderer.setStyle("ace_autocomplete"); + + popup.setOption("displayIndentGuides", false); + popup.setOption("dragDelay", 150); + + var noop = function(){}; + + popup.focus = noop; + popup.$isFocused = true; + + popup.renderer.$cursorLayer.restartTimer = noop; + popup.renderer.$cursorLayer.element.style.opacity = 0; + + popup.renderer.$maxLines = 8; + popup.renderer.$keepTextAreaAtCursor = false; + + popup.setHighlightActiveLine(false); + popup.session.highlight(""); + popup.session.$searchHighlight.clazz = "ace_highlight-marker"; + + popup.on("mousedown", function(e) { + var pos = e.getDocumentPosition(); + popup.selection.moveToPosition(pos); + selectionMarker.start.row = selectionMarker.end.row = pos.row; + e.stop(); + }); + + var lastMouseEvent; + var hoverMarker = new Range(-1,0,-1,Infinity); + var selectionMarker = new Range(-1,0,-1,Infinity); + selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine"); + popup.setSelectOnHover = function(val) { + if (!val) { + hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine"); + } else if (hoverMarker.id) { + popup.session.removeMarker(hoverMarker.id); + hoverMarker.id = null; + } + }; + popup.setSelectOnHover(false); + popup.on("mousemove", function(e) { + if (!lastMouseEvent) { + lastMouseEvent = e; + return; + } + if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) { + return; + } + lastMouseEvent = e; + lastMouseEvent.scrollTop = popup.renderer.scrollTop; + var row = lastMouseEvent.getDocumentPosition().row; + if (hoverMarker.start.row != row) { + if (!hoverMarker.id) + popup.setRow(row); + setHoverMarker(row); + } + }); + popup.renderer.on("beforeRender", function() { + if (lastMouseEvent && hoverMarker.start.row != -1) { + lastMouseEvent.$pos = null; + var row = lastMouseEvent.getDocumentPosition().row; + if (!hoverMarker.id) + popup.setRow(row); + setHoverMarker(row, true); + } + }); + popup.renderer.on("afterRender", function() { + var row = popup.getRow(); + var t = popup.renderer.$textLayer; + var selected = t.element.childNodes[row - t.config.firstRow]; + if (selected == t.selectedNode) + return; + if (t.selectedNode) + dom.removeCssClass(t.selectedNode, "ace_selected"); + t.selectedNode = selected; + if (selected) + dom.addCssClass(selected, "ace_selected"); + }); + var hideHoverMarker = function() { setHoverMarker(-1) }; + var setHoverMarker = function(row, suppressRedraw) { + if (row !== hoverMarker.start.row) { + hoverMarker.start.row = hoverMarker.end.row = row; + if (!suppressRedraw) + popup.session._emit("changeBackMarker"); + popup._emit("changeHoverMarker"); + } + }; + popup.getHoveredRow = function() { + return hoverMarker.start.row; + }; + + event.addListener(popup.container, "mouseout", hideHoverMarker); + popup.on("hide", hideHoverMarker); + popup.on("changeSelection", hideHoverMarker); + + popup.session.doc.getLength = function() { + return popup.data.length; + }; + popup.session.doc.getLine = function(i) { + var data = popup.data[i]; + if (typeof data == "string") + return data; + return (data && data.value) || ""; + }; + + var bgTokenizer = popup.session.bgTokenizer; + bgTokenizer.$tokenizeRow = function(row) { + var data = popup.data[row]; + var tokens = []; + if (!data) + return tokens; + if (typeof data == "string") + data = {value: data}; + if (!data.caption) + data.caption = data.value || data.name; + + var last = -1; + var flag, c; + for (var i = 0; i < data.caption.length; i++) { + c = data.caption[i]; + flag = data.matchMask & (1 << i) ? 1 : 0; + if (last !== flag) { + tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c}); + last = flag; + } else { + tokens[tokens.length - 1].value += c; + } + } + + if (data.meta) { + var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth; + var metaData = data.meta; + if (metaData.length + data.caption.length > maxW - 2) { + metaData = metaData.substr(0, maxW - data.caption.length - 3) + "\u2026" + } + tokens.push({type: "rightAlignedText", value: metaData}); + } + return tokens; + }; + bgTokenizer.$updateOnChange = noop; + bgTokenizer.start = noop; + + popup.session.$computeWidth = function() { + return this.screenWidth = 0; + }; + + popup.$blockScrolling = Infinity; + popup.isOpen = false; + popup.isTopdown = false; + + popup.data = []; + popup.setData = function(list) { + popup.setValue(lang.stringRepeat("\n", list.length), -1); + popup.data = list || []; + popup.setRow(0); + }; + popup.getData = function(row) { + return popup.data[row]; + }; + + popup.getRow = function() { + return selectionMarker.start.row; + }; + popup.setRow = function(line) { + line = Math.max(0, Math.min(this.data.length, line)); + if (selectionMarker.start.row != line) { + popup.selection.clearSelection(); + selectionMarker.start.row = selectionMarker.end.row = line || 0; + popup.session._emit("changeBackMarker"); + popup.moveCursorTo(line || 0, 0); + if (popup.isOpen) + popup._signal("select"); + } + }; + + popup.on("changeSelection", function() { + if (popup.isOpen) + popup.setRow(popup.selection.lead.row); + popup.renderer.scrollCursorIntoView(); + }); + + popup.hide = function() { + this.container.style.display = "none"; + this._signal("hide"); + popup.isOpen = false; + }; + popup.show = function(pos, lineHeight, topdownOnly) { + var el = this.container; + var screenHeight = window.innerHeight; + var screenWidth = window.innerWidth; + var renderer = this.renderer; + var maxH = renderer.$maxLines * lineHeight * 1.4; + var top = pos.top + this.$borderSize; + var allowTopdown = top > screenHeight / 2 && !topdownOnly; + if (allowTopdown && top + lineHeight + maxH > screenHeight) { + renderer.$maxPixelHeight = top - 2 * this.$borderSize; + el.style.top = ""; + el.style.bottom = screenHeight - top + "px"; + popup.isTopdown = false; + } else { + top += lineHeight; + renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight; + el.style.top = top + "px"; + el.style.bottom = ""; + popup.isTopdown = true; + } + + el.style.display = ""; + this.renderer.$textLayer.checkForSizeChanges(); + + var left = pos.left; + if (left + el.offsetWidth > screenWidth) + left = screenWidth - el.offsetWidth; + + el.style.left = left + "px"; + + this._signal("show"); + lastMouseEvent = null; + popup.isOpen = true; + }; + + popup.getTextLeftOffset = function() { + return this.$borderSize + this.renderer.$padding + this.$imageSize; + }; + + popup.$imageSize = 0; + popup.$borderSize = 1; + + return popup; +}; + +dom.importCssString("\ +.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\ + background-color: #CAD6FA;\ + z-index: 1;\ +}\ +.ace_editor.ace_autocomplete .ace_line-hover {\ + border: 1px solid #abbffe;\ + margin-top: -1px;\ + background: rgba(233,233,253,0.4);\ +}\ +.ace_editor.ace_autocomplete .ace_line-hover {\ + position: absolute;\ + z-index: 2;\ +}\ +.ace_editor.ace_autocomplete .ace_scroller {\ + background: none;\ + border: none;\ + box-shadow: none;\ +}\ +.ace_rightAlignedText {\ + color: gray;\ + display: inline-block;\ + position: absolute;\ + right: 4px;\ + text-align: right;\ + z-index: -1;\ +}\ +.ace_editor.ace_autocomplete .ace_completion-highlight{\ + color: #000;\ + text-shadow: 0 0 0.01em;\ +}\ +.ace_editor.ace_autocomplete {\ + width: 280px;\ + z-index: 200000;\ + background: #fbfbfb;\ + color: #444;\ + border: 1px lightgray solid;\ + position: fixed;\ + box-shadow: 2px 3px 5px rgba(0,0,0,.2);\ + line-height: 1.4;\ +}"); + +exports.AcePopup = AcePopup; + +}); + +ace.define("ace/autocomplete/util",["require","exports","module"], function(acequire, exports, module) { +"use strict"; + +exports.parForEach = function(array, fn, callback) { + var completed = 0; + var arLength = array.length; + if (arLength === 0) + callback(); + for (var i = 0; i < arLength; i++) { + fn(array[i], function(result, err) { + completed++; + if (completed === arLength) + callback(result, err); + }); + } +}; + +var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/; + +exports.retrievePrecedingIdentifier = function(text, pos, regex) { + regex = regex || ID_REGEX; + var buf = []; + for (var i = pos-1; i >= 0; i--) { + if (regex.test(text[i])) + buf.push(text[i]); + else + break; + } + return buf.reverse().join(""); +}; + +exports.retrieveFollowingIdentifier = function(text, pos, regex) { + regex = regex || ID_REGEX; + var buf = []; + for (var i = pos; i < text.length; i++) { + if (regex.test(text[i])) + buf.push(text[i]); + else + break; + } + return buf; +}; + +exports.getCompletionPrefix = function (editor) { + var pos = editor.getCursorPosition(); + var line = editor.session.getLine(pos.row); + var prefix; + editor.completers.forEach(function(completer) { + if (completer.identifierRegexps) { + completer.identifierRegexps.forEach(function(identifierRegex) { + if (!prefix && identifierRegex) + prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex); + }.bind(this)); + } + }.bind(this)); + return prefix || this.retrievePrecedingIdentifier(line, pos.column); +}; + +}); + +ace.define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/event","ace/lib/lang","ace/lib/dom","ace/snippets"], function(acequire, exports, module) { +"use strict"; + +var HashHandler = acequire("./keyboard/hash_handler").HashHandler; +var AcePopup = acequire("./autocomplete/popup").AcePopup; +var util = acequire("./autocomplete/util"); +var event = acequire("./lib/event"); +var lang = acequire("./lib/lang"); +var dom = acequire("./lib/dom"); +var snippetManager = acequire("./snippets").snippetManager; + +var Autocomplete = function() { + this.autoInsert = false; + this.autoSelect = true; + this.exactMatch = false; + this.gatherCompletionsId = 0; + this.keyboardHandler = new HashHandler(); + this.keyboardHandler.bindKeys(this.commands); + + this.blurListener = this.blurListener.bind(this); + this.changeListener = this.changeListener.bind(this); + this.mousedownListener = this.mousedownListener.bind(this); + this.mousewheelListener = this.mousewheelListener.bind(this); + + this.changeTimer = lang.delayedCall(function() { + this.updateCompletions(true); + }.bind(this)); + + this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50); +}; + +(function() { + + this.$init = function() { + this.popup = new AcePopup(document.body || document.documentElement); + this.popup.on("click", function(e) { + this.insertMatch(); + e.stop(); + }.bind(this)); + this.popup.focus = this.editor.focus.bind(this.editor); + this.popup.on("show", this.tooltipTimer.bind(null, null)); + this.popup.on("select", this.tooltipTimer.bind(null, null)); + this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null)); + return this.popup; + }; + + this.getPopup = function() { + return this.popup || this.$init(); + }; + + this.openPopup = function(editor, prefix, keepPopupPosition) { + if (!this.popup) + this.$init(); + + this.popup.setData(this.completions.filtered); + + editor.keyBinding.addKeyboardHandler(this.keyboardHandler); + + var renderer = editor.renderer; + this.popup.setRow(this.autoSelect ? 0 : -1); + if (!keepPopupPosition) { + this.popup.setTheme(editor.getTheme()); + this.popup.setFontSize(editor.getFontSize()); + + var lineHeight = renderer.layerConfig.lineHeight; + + var pos = renderer.$cursorLayer.getPixelPosition(this.base, true); + pos.left -= this.popup.getTextLeftOffset(); + + var rect = editor.container.getBoundingClientRect(); + pos.top += rect.top - renderer.layerConfig.offset; + pos.left += rect.left - editor.renderer.scrollLeft; + pos.left += renderer.gutterWidth; + + this.popup.show(pos, lineHeight); + } else if (keepPopupPosition && !prefix) { + this.detach(); + } + }; + + this.detach = function() { + this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); + this.editor.off("changeSelection", this.changeListener); + this.editor.off("blur", this.blurListener); + this.editor.off("mousedown", this.mousedownListener); + this.editor.off("mousewheel", this.mousewheelListener); + this.changeTimer.cancel(); + this.hideDocTooltip(); + + this.gatherCompletionsId += 1; + if (this.popup && this.popup.isOpen) + this.popup.hide(); + + if (this.base) + this.base.detach(); + this.activated = false; + this.completions = this.base = null; + }; + + this.changeListener = function(e) { + var cursor = this.editor.selection.lead; + if (cursor.row != this.base.row || cursor.column < this.base.column) { + this.detach(); + } + if (this.activated) + this.changeTimer.schedule(); + else + this.detach(); + }; + + this.blurListener = function(e) { + if (e.relatedTarget && e.relatedTarget.nodeName == "A" && e.relatedTarget.href) { + window.open(e.relatedTarget.href, "_blank"); + } + var el = document.activeElement; + var text = this.editor.textInput.getElement(); + var fromTooltip = e.relatedTarget && e.relatedTarget == this.tooltipNode; + var container = this.popup && this.popup.container; + if (el != text && el.parentNode != container && !fromTooltip + && el != this.tooltipNode && e.relatedTarget != text + ) { + this.detach(); + } + }; + + this.mousedownListener = function(e) { + this.detach(); + }; + + this.mousewheelListener = function(e) { + this.detach(); + }; + + this.goTo = function(where) { + var row = this.popup.getRow(); + var max = this.popup.session.getLength() - 1; + + switch(where) { + case "up": row = row <= 0 ? max : row - 1; break; + case "down": row = row >= max ? -1 : row + 1; break; + case "start": row = 0; break; + case "end": row = max; break; + } + + this.popup.setRow(row); + }; + + this.insertMatch = function(data, options) { + if (!data) + data = this.popup.getData(this.popup.getRow()); + if (!data) + return false; + + if (data.completer && data.completer.insertMatch) { + data.completer.insertMatch(this.editor, data); + } else { + if (this.completions.filterText) { + var ranges = this.editor.selection.getAllRanges(); + for (var i = 0, range; range = ranges[i]; i++) { + range.start.column -= this.completions.filterText.length; + this.editor.session.remove(range); + } + } + if (data.snippet) + snippetManager.insertSnippet(this.editor, data.snippet); + else + this.editor.execCommand("insertstring", data.value || data); + } + this.detach(); + }; + + + this.commands = { + "Up": function(editor) { editor.completer.goTo("up"); }, + "Down": function(editor) { editor.completer.goTo("down"); }, + "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); }, + "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); }, + + "Esc": function(editor) { editor.completer.detach(); }, + "Return": function(editor) { return editor.completer.insertMatch(); }, + "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); }, + "Tab": function(editor) { + var result = editor.completer.insertMatch(); + if (!result && !editor.tabstopManager) + editor.completer.goTo("down"); + else + return result; + }, + + "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); }, + "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); } + }; + + this.gatherCompletions = function(editor, callback) { + var session = editor.getSession(); + var pos = editor.getCursorPosition(); + + var line = session.getLine(pos.row); + var prefix = util.getCompletionPrefix(editor); + + this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length); + this.base.$insertRight = true; + + var matches = []; + var total = editor.completers.length; + editor.completers.forEach(function(completer, i) { + completer.getCompletions(editor, session, pos, prefix, function(err, results) { + if (!err && results) + matches = matches.concat(results); + var pos = editor.getCursorPosition(); + var line = session.getLine(pos.row); + callback(null, { + prefix: prefix, + matches: matches, + finished: (--total === 0) + }); + }); + }); + return true; + }; + + this.showPopup = function(editor) { + if (this.editor) + this.detach(); + + this.activated = true; + + this.editor = editor; + if (editor.completer != this) { + if (editor.completer) + editor.completer.detach(); + editor.completer = this; + } + + editor.on("changeSelection", this.changeListener); + editor.on("blur", this.blurListener); + editor.on("mousedown", this.mousedownListener); + editor.on("mousewheel", this.mousewheelListener); + + this.updateCompletions(); + }; + + this.updateCompletions = function(keepPopupPosition) { + if (keepPopupPosition && this.base && this.completions) { + var pos = this.editor.getCursorPosition(); + var prefix = this.editor.session.getTextRange({start: this.base, end: pos}); + if (prefix == this.completions.filterText) + return; + this.completions.setFilter(prefix); + if (!this.completions.filtered.length) + return this.detach(); + if (this.completions.filtered.length == 1 + && this.completions.filtered[0].value == prefix + && !this.completions.filtered[0].snippet) + return this.detach(); + this.openPopup(this.editor, prefix, keepPopupPosition); + return; + } + var _id = this.gatherCompletionsId; + this.gatherCompletions(this.editor, function(err, results) { + var detachIfFinished = function() { + if (!results.finished) return; + return this.detach(); + }.bind(this); + + var prefix = results.prefix; + var matches = results && results.matches; + + if (!matches || !matches.length) + return detachIfFinished(); + if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId) + return; + + this.completions = new FilteredList(matches); + + if (this.exactMatch) + this.completions.exactMatch = true; + + this.completions.setFilter(prefix); + var filtered = this.completions.filtered; + if (!filtered.length) + return detachIfFinished(); + if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet) + return detachIfFinished(); + if (this.autoInsert && filtered.length == 1 && results.finished) + return this.insertMatch(filtered[0]); + + this.openPopup(this.editor, prefix, keepPopupPosition); + }.bind(this)); + }; + + this.cancelContextMenu = function() { + this.editor.$mouseHandler.cancelContextMenu(); + }; + + this.updateDocTooltip = function() { + var popup = this.popup; + var all = popup.data; + var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]); + var doc = null; + if (!selected || !this.editor || !this.popup.isOpen) + return this.hideDocTooltip(); + this.editor.completers.some(function(completer) { + if (completer.getDocTooltip) + doc = completer.getDocTooltip(selected); + return doc; + }); + if (!doc) + doc = selected; + + if (typeof doc == "string") + doc = {docText: doc}; + if (!doc || !(doc.docHTML || doc.docText)) + return this.hideDocTooltip(); + this.showDocTooltip(doc); + }; + + this.showDocTooltip = function(item) { + if (!this.tooltipNode) { + this.tooltipNode = dom.createElement("div"); + this.tooltipNode.className = "ace_tooltip ace_doc-tooltip"; + this.tooltipNode.style.margin = 0; + this.tooltipNode.style.pointerEvents = "auto"; + this.tooltipNode.tabIndex = -1; + this.tooltipNode.onblur = this.blurListener.bind(this); + } + + var tooltipNode = this.tooltipNode; + if (item.docHTML) { + tooltipNode.innerHTML = item.docHTML; + } else if (item.docText) { + tooltipNode.textContent = item.docText; + } + + if (!tooltipNode.parentNode) + document.body.appendChild(tooltipNode); + var popup = this.popup; + var rect = popup.container.getBoundingClientRect(); + tooltipNode.style.top = popup.container.style.top; + tooltipNode.style.bottom = popup.container.style.bottom; + + if (window.innerWidth - rect.right < 320) { + tooltipNode.style.right = window.innerWidth - rect.left + "px"; + tooltipNode.style.left = ""; + } else { + tooltipNode.style.left = (rect.right + 1) + "px"; + tooltipNode.style.right = ""; + } + tooltipNode.style.display = "block"; + }; + + this.hideDocTooltip = function() { + this.tooltipTimer.cancel(); + if (!this.tooltipNode) return; + var el = this.tooltipNode; + if (!this.editor.isFocused() && document.activeElement == el) + this.editor.focus(); + this.tooltipNode = null; + if (el.parentNode) + el.parentNode.removeChild(el); + }; + +}).call(Autocomplete.prototype); + +Autocomplete.startCommand = { + name: "startAutocomplete", + exec: function(editor) { + if (!editor.completer) + editor.completer = new Autocomplete(); + editor.completer.autoInsert = false; + editor.completer.autoSelect = true; + editor.completer.showPopup(editor); + editor.completer.cancelContextMenu(); + }, + bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space" +}; + +var FilteredList = function(array, filterText) { + this.all = array; + this.filtered = array; + this.filterText = filterText || ""; + this.exactMatch = false; +}; +(function(){ + this.setFilter = function(str) { + if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0) + var matches = this.filtered; + else + var matches = this.all; + + this.filterText = str; + matches = this.filterCompletions(matches, this.filterText); + matches = matches.sort(function(a, b) { + return b.exactMatch - a.exactMatch || b.score - a.score; + }); + var prev = null; + matches = matches.filter(function(item){ + var caption = item.snippet || item.caption || item.value; + if (caption === prev) return false; + prev = caption; + return true; + }); + + this.filtered = matches; + }; + this.filterCompletions = function(items, needle) { + var results = []; + var upper = needle.toUpperCase(); + var lower = needle.toLowerCase(); + loop: for (var i = 0, item; item = items[i]; i++) { + var caption = item.value || item.caption || item.snippet; + if (!caption) continue; + var lastIndex = -1; + var matchMask = 0; + var penalty = 0; + var index, distance; + + if (this.exactMatch) { + if (needle !== caption.substr(0, needle.length)) + continue loop; + }else{ + for (var j = 0; j < needle.length; j++) { + var i1 = caption.indexOf(lower[j], lastIndex + 1); + var i2 = caption.indexOf(upper[j], lastIndex + 1); + index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2; + if (index < 0) + continue loop; + distance = index - lastIndex - 1; + if (distance > 0) { + if (lastIndex === -1) + penalty += 10; + penalty += distance; + } + matchMask = matchMask | (1 << index); + lastIndex = index; + } + } + item.matchMask = matchMask; + item.exactMatch = penalty ? 0 : 1; + item.score = (item.score || 0) - penalty; + results.push(item); + } + return results; + }; +}).call(FilteredList.prototype); + +exports.Autocomplete = Autocomplete; +exports.FilteredList = FilteredList; + +}); + +ace.define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(acequire, exports, module) { + var Range = acequire("../range").Range; + + var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/; + + function getWordIndex(doc, pos) { + var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos)); + return textBefore.split(splitRegex).length - 1; + } + function wordDistance(doc, pos) { + var prefixPos = getWordIndex(doc, pos); + var words = doc.getValue().split(splitRegex); + var wordScores = Object.create(null); + + var currentWord = words[prefixPos]; + + words.forEach(function(word, idx) { + if (!word || word === currentWord) return; + + var distance = Math.abs(prefixPos - idx); + var score = words.length - distance; + if (wordScores[word]) { + wordScores[word] = Math.max(score, wordScores[word]); + } else { + wordScores[word] = score; + } + }); + return wordScores; + } + + exports.getCompletions = function(editor, session, pos, prefix, callback) { + var wordScore = wordDistance(session, pos, prefix); + var wordList = Object.keys(wordScore); + callback(null, wordList.map(function(word) { + return { + caption: word, + value: word, + score: wordScore[word], + meta: "local" + }; + })); + }; +}); + +ace.define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(acequire, exports, module) { +"use strict"; + +var snippetManager = acequire("../snippets").snippetManager; +var Autocomplete = acequire("../autocomplete").Autocomplete; +var config = acequire("../config"); +var lang = acequire("../lib/lang"); +var util = acequire("../autocomplete/util"); + +var textCompleter = acequire("../autocomplete/text_completer"); +var keyWordCompleter = { + getCompletions: function(editor, session, pos, prefix, callback) { + if (session.$mode.completer) { + return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback); + } + var state = editor.session.getState(pos.row); + var completions = session.$mode.getCompletions(state, session, pos, prefix); + callback(null, completions); + } +}; + +var snippetCompleter = { + getCompletions: function(editor, session, pos, prefix, callback) { + var snippetMap = snippetManager.snippetMap; + var completions = []; + snippetManager.getActiveScopes(editor).forEach(function(scope) { + var snippets = snippetMap[scope] || []; + for (var i = snippets.length; i--;) { + var s = snippets[i]; + var caption = s.name || s.tabTrigger; + if (!caption) + continue; + completions.push({ + caption: caption, + snippet: s.content, + meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet", + type: "snippet" + }); + } + }, this); + callback(null, completions); + }, + getDocTooltip: function(item) { + if (item.type == "snippet" && !item.docHTML) { + item.docHTML = [ + "", lang.escapeHTML(item.caption), "", "
", + lang.escapeHTML(item.snippet) + ].join(""); + } + } +}; + +var completers = [snippetCompleter, textCompleter, keyWordCompleter]; +exports.setCompleters = function(val) { + completers.length = 0; + if (val) completers.push.apply(completers, val); +}; +exports.addCompleter = function(completer) { + completers.push(completer); +}; +exports.textCompleter = textCompleter; +exports.keyWordCompleter = keyWordCompleter; +exports.snippetCompleter = snippetCompleter; + +var expandSnippet = { + name: "expandSnippet", + exec: function(editor) { + return snippetManager.expandWithTab(editor); + }, + bindKey: "Tab" +}; + +var onChangeMode = function(e, editor) { + loadSnippetsForMode(editor.session.$mode); +}; + +var loadSnippetsForMode = function(mode) { + var id = mode.$id; + if (!snippetManager.files) + snippetManager.files = {}; + loadSnippetFile(id); + if (mode.modes) + mode.modes.forEach(loadSnippetsForMode); +}; + +var loadSnippetFile = function(id) { + if (!id || snippetManager.files[id]) + return; + var snippetFilePath = id.replace("mode", "snippets"); + snippetManager.files[id] = {}; + config.loadModule(snippetFilePath, function(m) { + if (m) { + snippetManager.files[id] = m; + if (!m.snippets && m.snippetText) + m.snippets = snippetManager.parseSnippetFile(m.snippetText); + snippetManager.register(m.snippets || [], m.scope); + if (m.includeScopes) { + snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes; + m.includeScopes.forEach(function(x) { + loadSnippetFile("ace/mode/" + x); + }); + } + } + }); +}; + +var doLiveAutocomplete = function(e) { + var editor = e.editor; + var hasCompleter = editor.completer && editor.completer.activated; + if (e.command.name === "backspace") { + if (hasCompleter && !util.getCompletionPrefix(editor)) + editor.completer.detach(); + } + else if (e.command.name === "insertstring") { + var prefix = util.getCompletionPrefix(editor); + if (prefix && !hasCompleter) { + if (!editor.completer) { + editor.completer = new Autocomplete(); + } + editor.completer.autoInsert = false; + editor.completer.showPopup(editor); + } + } +}; + +var Editor = acequire("../editor").Editor; +acequire("../config").defineOptions(Editor.prototype, "editor", { + enableBasicAutocompletion: { + set: function(val) { + if (val) { + if (!this.completers) + this.completers = Array.isArray(val)? val: completers; + this.commands.addCommand(Autocomplete.startCommand); + } else { + this.commands.removeCommand(Autocomplete.startCommand); + } + }, + value: false + }, + enableLiveAutocompletion: { + set: function(val) { + if (val) { + if (!this.completers) + this.completers = Array.isArray(val)? val: completers; + this.commands.on('afterExec', doLiveAutocomplete); + } else { + this.commands.removeListener('afterExec', doLiveAutocomplete); + } + }, + value: false + }, + enableSnippets: { + set: function(val) { + if (val) { + this.commands.addCommand(expandSnippet); + this.on("changeMode", onChangeMode); + onChangeMode(null, this); + } else { + this.commands.removeCommand(expandSnippet); + this.off("changeMode", onChangeMode); + } + }, + value: false + } +}); +}); + (function() { + ace.acequire(["ace/ext/language_tools"], function() {}); + })(); + + +/***/ }), +/* 68 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FactionInfo; }); -//Contains the "information" property for all the Factions, which is just a description -//of each faction -let FactionInfo = { - //Endgame - IlluminatiInfo: "Humanity never changes. No matter how civilized society becomes, it will eventually fall back " + - "into chaos. And from this chaos, we are the Invisible hand that guides them to order. ", +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return TerminalHelpText; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HelpTexts; }); +/* HelpText.js */ +let TerminalHelpText = + "Type 'help name' to learn more about the command 'name'

" + + 'alias [-g] [name="value"] Create or display Terminal aliases
' + + "analyze Get information about the current machine
" + + "buy [-l/program] Purchase a program through the Dark Web
" + + "cat [file] Display a .msg or .lit file
" + + "check [script] [args...] Print a script's logs to Terminal
" + + "clear Clear all text on the terminal
" + + "cls See 'clear' command
" + + "connect [ip/hostname] Connects to a remote server
" + + "download [text file] Downloads a text (.txt) file to your computer
" + + "free Check the machine's memory (RAM) usage
" + + "hack Hack the current machine
" + + "help [command] Display this help text, or the help text for a command
" + + "home Connect to home computer
" + + "hostname Displays the hostname of the machine
" + + "ifconfig Displays the IP address of the machine
" + + "kill [script] [args...] Stops the specified script on the current server
" + + "killall Stops all running scripts on the current machine
" + + "ls [| grep pattern] Displays all files on the machine
" + + "lscpu Displays the number of CPU cores on the machine
" + + "mem [script] [-t] [n] Displays the amount of RAM required to run the script
" + + "nano [script] Script editor - Open up and edit a script
" + + "ps Display all scripts that are currently running
" + + "rm [file] Delete a file from the server
" + + "run [name] [-t] [n] [args...] Execute a program or script
" + + "scan Prints all immediately-available network connections
" + + "scan-analyze [d] [-a] Prints info for all servers up to d nodes away
" + + "scp [file] [server] Copies a script or .lit file to a destination server
" + + "sudov Shows whether you have root access on this computer
" + + "tail [script] [args...] Displays dynamic logs for the specified script
" + + "theme [preset] | bg txt hlgt Change the color scheme of the UI
" + + "top Displays all running scripts and their RAM usage
" + + 'unalias "[alias name]" Deletes the specified alias
'; - DaedalusInfo: "Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.", - - CovenantInfo: "Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " + - "Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.

" + - "Only then can you discover immortality.", - - //Megacorporations, each forms its own faction - ECorpInfo: "ECorp's mission is simple: to connect the world of today with the technology of tomorrow. " + - "With our wide range of Internet-related software and commercial hardware, ECorp makes the world's " + - "information universally accessible.", - - MegaCorpInfo: "MegaCorp does things that others don't. We imagine. We create. We invent. We build things that " + - "others have never even dreamed of. Our work fills the world's needs for food, water, power, and " + - "transporation on an unprecendented scale, in ways that no other company can.

" + - "In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.", - - BachmanAndAssociatesInfo: "Where Law and Business meet - thats where we are.

" + - "Legal Insight - Business Instinct - Experience Innovation", - - BladeIndustriesInfo: "Augmentation is salvation", - - NWOInfo: "The human being created civilization not because of willingness but of a need to be assimilated into higher orders of structure and meaning.", - - ClarkeIncorporatedInfo: "Unlocking the power of the genome", - - OmniTekIncorporatedInfo: "Simply put, our mission is to design and build robots that make a difference", - - FourSigmaInfo: "The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven by " + - "deep learning and innovative ideas. And improved by iteration. That's Four Sigma.", - - KuaiGongInternationalInfo: "Dream big. Work hard. Make history.", - - //Other Corporations - FulcrumSecretTechnologiesInfo: "TODO", - - //Hacker groups - BitRunnersInfo: "Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. "+ - "It's all transformed into bits, stored in bits, communicated through bits. It’s impossible for any person " + - "to move, to live, to operate at any level without the use of bits. " + - "And when a person moves, lives, and operates, they leave behind their bits, mere traces of seemingly " + - "meaningless fragments of information. But these bits can be reconstructed. Transformed. Used.

" + - "Those who run the bits, run the world", - - - BlackHandInfo: "The world, so afraid of strong government, now has no government. Only power - Digital power. Financial power. " + - "Technological power. " + - "And those at the top rule with an invisible hand. They built a society where the rich get richer, " + - "and everyone else suffers.

" + - "So much pain. So many lives. Their darkness must end.", - - NiteSecInfo: -" __..__
" + -" _.nITESECNIt.
" + -" .-'NITESECNITESEc.
" + -" .' NITESECNITESECn
" + -" / NITESECNITESEC;
" + -" : :NITESECNITESEC;
" + -" ; $ NITESECNITESECN
" + -" : _, ,N'ITESECNITESEC
" + -" : .+^^`, : `NITESECNIT
" + -" ) /), `-,-=,NITESECNI
" + -" / ^ ,-;|NITESECN;
" + -" / _.' '-';NITESECN
" + -" ( , ,-''`^NITE'
" + -" )` :`. .'
" + -" )-- ; `- /
" + -" \' _.-' :
" + -" ( _.-' \. \
" + -" \------. \ \
" + -" \. \ \
" + -" \ _.nIt
" + -" \ _.nITESECNi
" + -" nITESECNIT^' \
" + -" NITE^' ___ \
" + -" / .gP''''Tp. \
" + -" : d' . `b \
" + -" ; d' o `b ;
" + -" / d; `b|
" + -" /, $; @ `:
" + -" /' $$ ;
" + -" .' $$b o |
" + -" .' d$$$; :
" + -" / .d$$$$; , ;
" + -" d .dNITESEC $ |
" + -" :bp.__.gNITESEC$$ :$ ;
" + -" NITESECNITESECNIT $$b :
", - - //City factions, essentially governments - ChongqingInfo: "Serve the people", - Sector12Info: "The City of the Future", - HongKongInfo: "Asia's World City", - AevumInfo: "The Silicon City", - IshimaInfo: "The East Asian Order of the Future", - VolhavenInfo: "Benefit, Honour, and Glory", - - //Criminal Organizations/Gangs - SpeakersForTheDeadInfo: "It is better to reign in hell than to serve in heaven.", - - DarkArmyInfo: "The World doesn't care about right or wrong. It's all about power.", - - TheSyndicateInfo: "Honor holds you back", - - SilhouetteInfo: "Corporations have filled the void of power left behind by the collapse of Western government. The issue is they've become so big " + - "that you don't know who they're working for. And if you're employed at one of these corporations, you don't even know who you're working " + - "for.

" + - "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.", - - TetradsInfo: "Following the Mandate of Heaven and Carrying out the Way", - - SlumSnakesInfo: "Slum Snakes rule!", - - //Earlygame factions - factions the player will prestige with early on that don't - //belong in other categories - NetburnersInfo: "~~//*>H4CK|\|3T 8URN3R5**>?>\\~~", - - TianDiHuiInfo: "Obey Heaven and Work Righteousness", - - CyberSecInfo: "The Internet is the first thing that humanity has built that humanity doesn’t understand, " + - "the largest experiment in anarchy that we have ever had. And as the world becomes increasingly " + - "dominated by the internet, society approaches the brink of total chaos. " + - "We serve only to protect society, to protect humanity, to protect the world from its imminent collapse.", +let HelpTexts = { + alias: 'alias [-g] [name="value"]
' + + "Create or display aliases. An alias enables a replacement of a word with another string. " + + "It can be used to abbreviate a commonly used command, or commonly used parts of a command. The NAME " + + "of an alias defines the word that will be replaced, while the VALUE defines what it will be replaced by. For example, " + + "you could create the alias 'nuke' for the Terminal command 'run NUKE.exe' using the following:

" + + 'alias nuke="run NUKE.exe"

' + + "Then, to run the NUKE.exe program you would just have to enter 'nuke' in Terminal rather than the full command. " + + "It is important to note that 'default' aliases will only be substituted for the first word of a Terminal command. For " + + "example, if the following alias was set:

" + + 'alias worm="HTTPWorm.exe"

' + + "and then you tried to run the following terminal command:

" + + "run worm

" + + "This would fail because the worm alias is not the first word of a Terminal command. To allow an alias to be substituted " + + "anywhere in a Terminal command, rather than just the first word, you must set it to be a global alias using the -g flag:

" + + 'alias -g worm="HTTPWorm.exe"

' + + "Now, the 'worm' alias will be substituted anytime it shows up as an individual word in a Terminal command.

" + + "Entering just the command 'alias' without any arguments prints the list of all defined aliases in the reusable form " + + "'alias NAME=VALUE' on the Terminal.

" + + "The 'unalias' command can be used to remove aliases.

", + analyze: "analze
" + + "Prints details and statistics about the current server. The information that is printed includes basic " + + "server details such as the hostname, whether the player has root access, what ports are opened/closed, and also " + + "hacking-related information such as an estimated chance to successfully hack, an estimate of how much money is " + + "available on the server, etc.", + buy: "buy [-l / program]
" + + "Purchase a program through the Dark Web. Requires a TOR router to use.

" + + "If this command is ran with the '-l' flag, it will display a list of all programs that can be bought through the " + + "dark web to the Terminal, as well as their costs.

" + + "Otherwise, the name of the program must be passed in as a parameter. This is name is NOT case-sensitive.", + cat: "cat [file]
" + + "Display message files, which are files ending with the '.msg' extension, or a literature file, which " + + "are files ending with the '.lit' extension. Examples:

" + + "cat j1.msg
" + + "cat foo.lit", + check: "check [script name] [args...]
" + + "Print the logs of the script specified by the script name and arguments to the Terminal. Each argument must be separated by " + + "a space. Remember that a running script is uniquely " + + "identified both by its name and the arguments that are used to start it. So, if a script was ran with the following arguments:

" + + "run foo.script 1 2 foodnstuff

" + + "Then to run the 'check' command on this script you would have to pass the same arguments in:

" + + "check foo.script 1 2 foodnstuff", + clear: "clear
" + + "Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " + + "and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'cls' command", + cls: "cls
" + + "Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " + + "and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'clear' command", + connect: "connect [hostname/ip]
" + + "Connect to a remote server. The hostname or IP address of the remote server must be given as the argument " + + "to this command. Note that only servers that are immediately adjacent to the current server in the network can be connected to. To " + + "see which servers can be connected to, use the 'scan' command.", + download: "download [text file]
" + + "Downloads a text file to your computer (like your real life computer). Only works on text files, " + + "which are the ones with a .txt extension.", + free: "free
" + + "Display's the memory usage on the current machine. Print the amount of RAM that is available on the current server as well as " + + "how much of it is being used.", + hack: "hack
" + + "Attempt to hack the current server. Requires root access in order to be run. See the wiki page for hacking mechanics
", + help: "help [command]
" + + "Display Terminal help information. Without arguments, 'help' prints a list of all valid Terminal commands and a brief " + + "description of their functionality. You can also pass the name of a Terminal command as an argument to 'help' to print " + + "more detailed information about the Terminal command. Examples:

" + + "help alias
" + + "help scan-analyze", + home: "home
" + + "Connect to your home computer. This will work no matter what server you are currently connected to.", + hostname: "hostname
" + + "Prints the hostname of the current server", + ifconfig: "ipconfig
" + + "Prints the IP address of the current server", + kill: "kill [script name] [args...]
" + + "Kill the script specified by the script name and arguments. Each argument must be separated by " + + "a space. Remember that a running script is uniquely identified by " + + "both its name and the arguments that are used to start it. So, if a script was ran with the following arguments:

" + + "run foo.script 1 sigma-cosmetics

" + + "Then to kill this script the same arguments would have to be used:

" + + "kill foo.script 1 sigma-cosmetics

" + + "Note that after issuing the 'kill' command for a script, it may take a while for the script to actually stop running. " + + "This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " + + "The script will not be stopped/killed until after that time has elapsed.", + killall: "killall
" + + "Kills all scripts on the current server. " + + "Note that after the 'kill' command is issued for a script, it may take a while for the script to actually stop running. " + + "This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " + + "The script will not be stopped/killed until after that time has elapsed.", + ls: "ls [| grep pattern]
" + + "The ls command, with no arguments, prints all files on the current server to the Terminal screen. " + + "This includes all scripts, programs, and message files. " + + "The files will be displayed in alphabetical order.

" + + "The '| grep pattern' optional parameter can be used to only display files whose filenames match the specified pattern. " + + "For example, if you wanted to only display files with the .script extension, you could use:

" + + "ls | grep .script

" + + "Alternatively, if you wanted to display all files with the word purchase in the filename, you could use:

" + + "ls | grep purchase", + mem: "mem [script name] [-t] [num threads]
" + + "Displays the amount of RAM needed to run the specified script with a single thread. The command can also be used to print " + + "the amount of RAM needed to run a script with multiple threads using the '-t' flag. If the '-t' flag is specified, then " + + "an argument for the number of threads must be passed in afterwards. Examples:

" + + "mem foo.script
" + + "mem foo.script -t 50
" + + "The first example above will print the amount of RAM needed to run 'foo.script' with a single thread. The second example " + + "above will print the amount of RAM needed to run 'foo.script' with 50 threads.", + nano: "nano [script name]
" + + "Opens up the specified script in the Script Editor. If the script does not already exist, then a new, empty script " + + "will be created", + ps: "ps
" + + "Prints all scripts that are running on the current server", + rm: "rm [file]
" + + "Removes the specified file from the current server. A file can be a script, a program, or a message file.

" + + "WARNING: This is permanent and cannot be undone", + run: "run [file name] [-t] [num threads] [args...]
" + + "Execute a program or a script.

" + + "The '[-t]', '[num threads]', and '[args...]' arguments are only valid when running a script. The '-t' flag is used " + + "to indicate that the script should be run with the specified number of threads. If the flag is omitted, " + + "then the script will be run with a single thread by default. " + + "If the '-t' flag is used, then it MUST come immediately " + + "after the script name, and the [num threads] argument MUST come immediately afterwards.

" + + "[args...] represents a variable number of arguments that will be passed into the script. See the documentation " + + "about script arguments. Each specified argument must be separated by a space.

", + scan: "scan
" + + "Prints all immediately-available network connection. This will print a list of all servers that you can currently connect " + + "to using the 'connect' Terminal command.", + "scan-analyze": "scan-analyze [depth] [-a]
" + + "Prints detailed information about all servers up to [depth] nodes away on the network. Calling " + + "'scan-analyze 1' will display information for the same servers that are shown by the 'scan' Terminal " + + "command. This command also shows the relative paths to reach each server.

" + + "By default, the maximum depth that can be specified for 'scan-analyze' is 3. However, once you have " + + "the DeepscanV1.exe and DeepscanV2.exe programs, you can execute 'scan-analyze' with a depth up to " + + "5 and 10, respectively.

" + + "The information 'scan-analyze' displays about each server includes whether or not you have root access to it, " + + "its required hacking level, the number of open ports required to run NUKE.exe on it, and how much RAM " + + "it has.

" + + "By default, this command will not display servers that you have purchased. However, you can pass in the " + + "-a flag at the end of the command if you would like to enable that.", + scp: "scp [filename] [target server]
" + + "Copies the specified file from the current server to the target server. " + + "This command only works for script files (.script extension) and literature files (.lit extension). " + + "The second argument passed in must be the hostname or IP of the target server.", + sudov: "sudov
" + + "Prints whether or not you have root access to the current machine", + tail: "tail [script name] [args...]
" + + "Displays dynamic logs for the script specified by the script name and arguments. Each argument must be separated " + + "by a space. Remember that a running script is uniquely identified by both its name and the arguments that were used " + + "to run it. So, if a script was ran with the following arguments:

" + + "run foo.script 10 50000

" + + "Then in order to check its logs with 'tail' the same arguments must be used:

" + + "tail foo.script 10 50000", + theme: "theme [preset] | [#background #text #highlight]
" + + "Change the color of the game's user interface

" + + "This command can be called with a preset theme. Currently, the supported presets are 'default', 'muted', and 'solarized'. " + + "However, you can also specify your own color scheme using hex values. To do so, you must specify three hex color values " + + "for the background color, the text color, and the highlight color. These hex values must be preceded by a pound sign (#) and " + + "must be either 3 or 6 digits. Example:

" + + "theme #ffffff #385 #235012

" + + "A color picker such as " + + "Google's " + + "can be used to get your desired hex color values

" + + "Themes are not saved, so when the game is closed and then re-opened or reloaded then it will revert back to the default theme.", + top: "top
" + + "Prints a list of all scripts running on the current server as well as their thread count and how much " + + "RAM they are using in total.", + unalias: 'unalias "[alias name]"
' + + "Deletes the specified alias. Note that the double quotation marks are required.

" + + "As an example, if an alias was declared using:

" + + 'alias r="run"

' + + "Then it could be removed using:

" + + 'unalias "r"

' + + "It is not necessary to differentiate between global and non-global aliases when using 'unalias'", } @@ -47835,7 +78432,7 @@ let FactionInfo = { /***/ }), -/* 53 */ +/* 69 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -62391,30746 +92988,8 @@ let FactionInfo = { }).call(typeof window !== 'undefined' ? window : this); -/***/ }), -/* 54 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return factionInvitationBoxCreate; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_Faction_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__ = __webpack_require__(2); - - - - -/* Faction Invitation Pop-up box */ -function factionInvitationBoxClose() { - var factionInvitationBox = document.getElementById("faction-invitation-box-container"); - factionInvitationBox.style.display = "none"; -} - -function factionInvitationBoxOpen() { - var factionInvitationBox = document.getElementById("faction-invitation-box-container"); - factionInvitationBox.style.display = "block"; -} - -function factionInvitationSetText(txt) { - var textBox = document.getElementById("faction-invitation-box-text"); - textBox.innerHTML = txt; -} - -function factionInvitationSetMessage(msg) { - var msgBox = document.getElementById("faction-invitation-box-message"); - msgBox.innerHTML = msg; -} - -//ram argument is in GB -function factionInvitationBoxCreate(faction) { - factionInvitationSetText("You have received a faction invitation from " + faction.name); - //TODO Faction invitation message - - var newYesButton = Object(__WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__["b" /* clearEventListeners */])("faction-invitation-box-yes"); - newYesButton.addEventListener("click", function() { - Object(__WEBPACK_IMPORTED_MODULE_0__src_Faction_js__["h" /* joinFaction */])(faction); - factionInvitationBoxClose(); - return false; - }); - - var noButton = Object(__WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__["b" /* clearEventListeners */])("faction-invitation-box-no"); - noButton.addEventListener("click", function() { - factionInvitationBoxClose(); - faction.alreadyInvited = true; - __WEBPACK_IMPORTED_MODULE_1__src_Player_js__["a" /* Player */].factionInvitations.push(faction.name); - return false; - }); - - factionInvitationBoxOpen(); -} - - - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - -/* ***** BEGIN LICENSE BLOCK ***** - * Distributed under the BSD license: - * - * Copyright (c) 2010, Ajax.org B.V. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Ajax.org B.V. nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * ***** END LICENSE BLOCK ***** */ - -/** - * Define a module along with a payload - * @param module a name for the payload - * @param payload a function to call with (acequire, exports, module) params - */ - -(function() { - -var ACE_NAMESPACE = "ace"; - -var global = (function() { return this; })(); -if (!global && typeof window != "undefined") global = window; // strict mode - - -if (!ACE_NAMESPACE && typeof acequirejs !== "undefined") - return; - - -var define = function(module, deps, payload) { - if (typeof module !== "string") { - if (define.original) - define.original.apply(this, arguments); - else { - console.error("dropping module because define wasn\'t a string."); - console.trace(); - } - return; - } - if (arguments.length == 2) - payload = deps; - if (!define.modules[module]) { - define.payloads[module] = payload; - define.modules[module] = null; - } -}; - -define.modules = {}; -define.payloads = {}; - -/** - * Get at functionality define()ed using the function above - */ -var _acequire = function(parentId, module, callback) { - if (typeof module === "string") { - var payload = lookup(parentId, module); - if (payload != undefined) { - callback && callback(); - return payload; - } - } else 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 == undefined && acequire.original) - return; - params.push(dep); - } - return callback && callback.apply(null, params) || true; - } -}; - -var acequire = function(module, callback) { - var packagedModule = _acequire("", module, callback); - if (packagedModule == undefined && acequire.original) - return acequire.original.apply(this, arguments); - return packagedModule; -}; - -var normalizeModule = function(parentId, moduleName) { - // normalize plugin acequires - if (moduleName.indexOf("!") !== -1) { - var chunks = moduleName.split("!"); - return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); - } - // normalize relative acequires - 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; -}; - -/** - * Internal function to lookup moduleNames and resolve them by calling the - * definition function if needed. - */ -var lookup = function(parentId, moduleName) { - moduleName = normalizeModule(parentId, moduleName); - - var module = define.modules[moduleName]; - if (!module) { - module = define.payloads[moduleName]; - if (typeof module === 'function') { - var exports = {}; - var mod = { - id: moduleName, - uri: '', - exports: exports, - packaged: true - }; - - var req = function(module, callback) { - return _acequire(moduleName, module, callback); - }; - - var returnValue = module(req, exports, mod); - exports = returnValue || mod.exports; - define.modules[moduleName] = exports; - delete define.payloads[moduleName]; - } - module = define.modules[moduleName] = exports || module; - } - return module; -}; - -function exportAce(ns) { - var root = global; - if (ns) { - if (!global[ns]) - global[ns] = {}; - root = global[ns]; - } - - if (!root.define || !root.define.packaged) { - define.original = root.define; - root.define = define; - root.define.packaged = true; - } - - if (!root.acequire || !root.acequire.packaged) { - acequire.original = root.acequire; - root.acequire = acequire; - root.acequire.packaged = true; - } -} - -exportAce(ACE_NAMESPACE); - -})(); - -ace.define("ace/lib/regexp",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - - 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; - RegExp.prototype.exec = function (str) { - var match = real.exec.apply(this, arguments), - name, r2; - if ( typeof(str) == 'string' && match) { - if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { - r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); - 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; - } - }); - } - 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]; - } - } - if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) - this.lastIndex--; - } - return match; - }; - if (!compliantLastIndexIncrement) { - RegExp.prototype.test = function (str) { - var match = real.exec.call(this, str); - if (match && this.global && !match[0].length && (this.lastIndex > match.index)) - this.lastIndex--; - return !!match; - }; - } - - 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; - } - -}); - -ace.define("ace/lib/es5-shim",["require","exports","module"], function(acequire, exports, module) { - -function Empty() {} - -if (!Function.prototype.bind) { - Function.prototype.bind = function bind(that) { // .length is 1 - var target = this; - if (typeof target != "function") { - throw new TypeError("Function.prototype.bind called on incompatible " + target); - } - var args = slice.call(arguments, 1); // for normal call - var bound = function () { - - if (this instanceof bound) { - - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - - } - - }; - if(target.prototype) { - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - return bound; - }; -} -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); -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__); -} -if ([1,2].splice(0).length != 2) { - if(function() { // test IE < 9 to splice bug - see issue #138 - function makeArray(l) { - var a = new Array(l+2); - a[0] = a[1] = 0; - return a; - } - var array = [], lengthBefore; - - array.splice.apply(array, makeArray(20)); - array.splice.apply(array, makeArray(26)); - - lengthBefore = array.length; //46 - array.splice(5, 0, "XXX"); // add one element - - lengthBefore + 1 == array.length - - if (lengthBefore + 1 == array.length) { - return true;// has right splice implementation without bugs - } - }()) {//IE 6/7 - var array_splice = Array.prototype.splice; - Array.prototype.splice = function(start, deleteCount) { - if (!arguments.length) { - return []; - } else { - return array_splice.apply(this, [ - start === void 0 ? 0 : start, - deleteCount === void 0 ? (this.length - start) : deleteCount - ].concat(slice.call(arguments, 2))) - } - }; - } else {//IE8 - Array.prototype.splice = function(pos, removeCount){ - var length = this.length; - if (pos > 0) { - if (pos > length) - pos = length; - } else if (pos == void 0) { - pos = 0; - } else if (pos < 0) { - pos = Math.max(length + pos, 0); - } - - if (!(pos+removeCount < length)) - removeCount = length - pos; - - var removed = this.slice(pos, pos+removeCount); - var insert = slice.call(arguments, 2); - var add = insert.length; - if (pos === length) { - if (add) { - this.push.apply(this, insert); - } - } else { - var remove = Math.min(removeCount, length - pos); - var tailOldPos = pos + remove; - var tailNewPos = tailOldPos + add - remove; - var tailCount = length - tailOldPos; - var lengthAfterRemove = length - remove; - - if (tailNewPos < tailOldPos) { // case A - for (var i = 0; i < tailCount; ++i) { - this[tailNewPos+i] = this[tailOldPos+i]; - } - } else if (tailNewPos > tailOldPos) { // case B - for (i = tailCount; i--; ) { - this[tailNewPos+i] = this[tailOldPos+i]; - } - } // else, add == remove (nothing to do) - - if (add && pos === lengthAfterRemove) { - this.length = lengthAfterRemove; // truncate array - this.push.apply(this, insert); - } else { - this.length = lengthAfterRemove + add; // reserves space - for (i = 0; i < add; ++i) { - this[pos+i] = insert[i]; - } - } - } - return removed; - }; - } -} -if (!Array.isArray) { - Array.isArray = function isArray(obj) { - return _toString(obj) == "[object Array]"; - }; -} -var boxedString = Object("a"), - splitString = boxedString[0] != "a" || !(0 in boxedString); - -if (!Array.prototype.forEach) { - Array.prototype.forEach = function forEach(fun /*, thisp*/) { - var object = toObject(this), - self = splitString && _toString(this) == "[object String]" ? - this.split("") : - object, - thisp = arguments[1], - i = -1, - length = self.length >>> 0; - if (_toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - while (++i < length) { - if (i in self) { - fun.call(thisp, self[i], i, object); - } - } - }; -} -if (!Array.prototype.map) { - Array.prototype.map = function map(fun /*, thisp*/) { - var object = toObject(this), - self = splitString && _toString(this) == "[object String]" ? - this.split("") : - object, - length = self.length >>> 0, - result = Array(length), - thisp = arguments[1]; - if (_toString(fun) != "[object Function]") { - throw new TypeError(fun + " is not a function"); - } - - for (var i = 0; i < length; i++) { - if (i in self) - result[i] = fun.call(thisp, self[i], i, object); - } - return result; - }; -} -if (!Array.prototype.filter) { - Array.prototype.filter = function filter(fun /*, thisp */) { - var object = toObject(this), - self = splitString && _toString(this) == "[object String]" ? - this.split("") : - object, - length = self.length >>> 0, - result = [], - value, - thisp = arguments[1]; - if (_toString(fun) != "[object Function]") { - throw new TypeError(fun + " is not a function"); - } - - for (var i = 0; i < length; i++) { - if (i in self) { - value = self[i]; - if (fun.call(thisp, value, i, object)) { - result.push(value); - } - } - } - return result; - }; -} -if (!Array.prototype.every) { - Array.prototype.every = function every(fun /*, thisp */) { - var object = toObject(this), - self = splitString && _toString(this) == "[object String]" ? - this.split("") : - object, - length = self.length >>> 0, - thisp = arguments[1]; - if (_toString(fun) != "[object Function]") { - throw new TypeError(fun + " is not a function"); - } - - for (var i = 0; i < length; i++) { - if (i in self && !fun.call(thisp, self[i], i, object)) { - return false; - } - } - return true; - }; -} -if (!Array.prototype.some) { - Array.prototype.some = function some(fun /*, thisp */) { - var object = toObject(this), - self = splitString && _toString(this) == "[object String]" ? - this.split("") : - object, - length = self.length >>> 0, - thisp = arguments[1]; - if (_toString(fun) != "[object Function]") { - throw new TypeError(fun + " is not a function"); - } - - for (var i = 0; i < length; i++) { - if (i in self && fun.call(thisp, self[i], i, object)) { - return true; - } - } - return false; - }; -} -if (!Array.prototype.reduce) { - Array.prototype.reduce = function reduce(fun /*, initial*/) { - var object = toObject(this), - self = splitString && _toString(this) == "[object String]" ? - this.split("") : - object, - length = self.length >>> 0; - if (_toString(fun) != "[object Function]") { - throw new TypeError(fun + " is not a function"); - } - if (!length && arguments.length == 1) { - throw new TypeError("reduce of empty array with no initial value"); - } - - var i = 0; - var result; - if (arguments.length >= 2) { - result = arguments[1]; - } else { - do { - if (i in self) { - result = self[i++]; - break; - } - if (++i >= length) { - throw new TypeError("reduce of empty array with no initial value"); - } - } while (true); - } - - for (; i < length; i++) { - if (i in self) { - result = fun.call(void 0, result, self[i], i, object); - } - } - - return result; - }; -} -if (!Array.prototype.reduceRight) { - Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { - var object = toObject(this), - self = splitString && _toString(this) == "[object String]" ? - this.split("") : - object, - length = self.length >>> 0; - if (_toString(fun) != "[object Function]") { - throw new TypeError(fun + " is not a function"); - } - if (!length && arguments.length == 1) { - throw new TypeError("reduceRight of empty array with no initial value"); - } - - var result, i = length - 1; - if (arguments.length >= 2) { - result = arguments[1]; - } else { - do { - if (i in self) { - result = self[i--]; - break; - } - if (--i < 0) { - throw new TypeError("reduceRight of empty array with no initial value"); - } - } while (true); - } - - do { - if (i in this) { - result = fun.call(void 0, result, self[i], i, object); - } - } while (i--); - - return result; - }; -} -if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { - Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { - var self = splitString && _toString(this) == "[object String]" ? - this.split("") : - toObject(this), - length = self.length >>> 0; - - if (!length) { - return -1; - } - - var i = 0; - if (arguments.length > 1) { - i = toInteger(arguments[1]); - } - i = i >= 0 ? i : Math.max(0, length + i); - for (; i < length; i++) { - if (i in self && self[i] === sought) { - return i; - } - } - return -1; - }; -} -if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { - Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { - var self = splitString && _toString(this) == "[object String]" ? - this.split("") : - 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])); - } - i = i >= 0 ? i : length - Math.abs(i); - for (; i >= 0; i--) { - if (i in self && sought === self[i]) { - return i; - } - } - return -1; - }; -} -if (!Object.getPrototypeOf) { - Object.getPrototypeOf = function getPrototypeOf(object) { - return object.__proto__ || ( - object.constructor ? - object.constructor.prototype : - prototypeOfObject - ); - }; -} -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 (!owns(object, property)) - return; - - var descriptor, getter, setter; - descriptor = { enumerable: true, configurable: true }; - if (supportsAccessors) { - var prototype = object.__proto__; - object.__proto__ = prototypeOfObject; - - var getter = lookupGetter(object, property); - var setter = lookupSetter(object, property); - object.__proto__ = prototype; - - if (getter || setter) { - if (getter) descriptor.get = getter; - if (setter) descriptor.set = setter; - return descriptor; - } - } - descriptor.value = object[property]; - return descriptor; - }; -} -if (!Object.getOwnPropertyNames) { - Object.getOwnPropertyNames = function getOwnPropertyNames(object) { - return Object.keys(object); - }; -} -if (!Object.create) { - var createEmpty; - if (Object.prototype.__proto__ === null) { - createEmpty = function () { - return { "__proto__": null }; - }; - } else { - createEmpty = function () { - var empty = {}; - for (var i in empty) - empty[i] = null; - empty.constructor = - empty.hasOwnProperty = - empty.propertyIsEnumerable = - empty.isPrototypeOf = - empty.toLocaleString = - empty.toString = - empty.valueOf = - empty.__proto__ = null; - return empty; - } - } - - Object.create = function create(prototype, properties) { - var object; - if (prototype === null) { - object = createEmpty(); - } else { - if (typeof prototype != "object") - throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); - var Type = function () {}; - Type.prototype = prototype; - object = new Type(); - object.__proto__ = prototype; - } - if (properties !== void 0) - Object.defineProperties(object, properties); - return object; - }; -} - -function doesDefinePropertyWork(object) { - try { - Object.defineProperty(object, "sentinel", {}); - return "sentinel" in object; - } catch (exception) { - } -} -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); - if (definePropertyFallback) { - try { - return definePropertyFallback.call(Object, object, property, descriptor); - } catch (exception) { - } - } - if (owns(descriptor, "value")) { - - if (supportsAccessors && (lookupGetter(object, property) || - lookupSetter(object, property))) - { - var prototype = object.__proto__; - object.__proto__ = prototypeOfObject; - delete object[property]; - object[property] = descriptor.value; - object.__proto__ = prototype; - } else { - object[property] = descriptor.value; - } - } else { - if (!supportsAccessors) - throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); - if (owns(descriptor, "get")) - defineGetter(object, property, descriptor.get); - if (owns(descriptor, "set")) - defineSetter(object, property, descriptor.set); - } - - return object; - }; -} -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; - }; -} -if (!Object.seal) { - Object.seal = function seal(object) { - return object; - }; -} -if (!Object.freeze) { - Object.freeze = function freeze(object) { - return object; - }; -} -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); -} -if (!Object.preventExtensions) { - Object.preventExtensions = function preventExtensions(object) { - return object; - }; -} -if (!Object.isSealed) { - Object.isSealed = function isSealed(object) { - return false; - }; -} -if (!Object.isFrozen) { - Object.isFrozen = function isFrozen(object) { - return false; - }; -} -if (!Object.isExtensible) { - Object.isExtensible = function isExtensible(object) { - if (Object(object) === object) { - throw new TypeError(); // TODO message - } - var name = ''; - while (owns(object, name)) { - name += '?'; - } - object[name] = true; - var returnValue = owns(object, name); - delete object[name]; - return returnValue; - }; -} -if (!Object.keys) { - 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; - }; - -} -if (!Date.now) { - Date.now = function now() { - return new Date().getTime(); - }; -} -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()) { - 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, ""); - }; -} - -function toInteger(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; -} - -function isPrimitive(input) { - var type = typeof input; - return ( - input === null || - type === "undefined" || - type === "boolean" || - type === "number" || - type === "string" - ); -} - -function toPrimitive(input) { - var val, valueOf, toString; - if (isPrimitive(input)) { - return input; - } - valueOf = input.valueOf; - if (typeof valueOf === "function") { - val = valueOf.call(input); - if (isPrimitive(val)) { - return val; - } - } - toString = input.toString; - if (typeof toString === "function") { - val = toString.call(input); - if (isPrimitive(val)) { - return val; - } - } - throw new TypeError(); -} -var toObject = function (o) { - if (o == null) { // this matches both null and undefined - throw new TypeError("can't convert "+o+" to object"); - } - return Object(o); -}; - -}); - -ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"], function(acequire, exports, module) { -"use strict"; - -acequire("./regexp"); -acequire("./es5-shim"); - -}); - -ace.define("ace/lib/dom",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -var XHTML_NS = "http://www.w3.org/1999/xhtml"; - -exports.getDocumentHead = function(doc) { - if (!doc) - doc = document; - return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement; -} - -exports.createElement = function(tag, ns) { - return document.createElementNS ? - document.createElementNS(ns || XHTML_NS, tag) : - document.createElement(tag); -}; - -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 (id && exports.hasCssString(id, doc)) - return null; - - var style; - - if (id) - cssText += "\n/*# sourceURL=ace/css/" + id + " */"; - - if (doc.createStyleSheet) { - style = doc.createStyleSheet(); - style.cssText = cssText; - if (id) - style.owningElement.id = id; - } else { - style = exports.createElement("style"); - style.appendChild(doc.createTextNode(cssText)); - if (id) - style.id = id; - - exports.getDocumentHead(doc).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; - - exports.getDocumentHead(doc).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 - ); -}; - -exports.scrollbarWidth = function(document) { - var inner = exports.createElement("ace_inner"); - inner.style.width = "100%"; - inner.style.minWidth = "0px"; - inner.style.height = "200px"; - inner.style.display = "block"; - - var outer = exports.createElement("ace_outer"); - var style = outer.style; - - style.position = "absolute"; - style.left = "-10000px"; - style.overflow = "hidden"; - style.width = "200px"; - style.minWidth = "0px"; - style.height = "150px"; - style.display = "block"; - - outer.appendChild(inner); - - var 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; -}; - -if (typeof document == "undefined") { - exports.importCssString = function() {}; - return; -} - -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.setInnerHtml = function(el, innerHtml) { - var element = el.cloneNode(false);//document.createElement("div"); - element.innerHTML = innerHtml; - el.parentNode.replaceChild(element, el); - return element; -}; - -if ("textContent" in document.documentElement) { - exports.setInnerText = function(el, innerText) { - el.textContent = innerText; - }; - - exports.getInnerText = function(el) { - return el.textContent; - }; -} -else { - exports.setInnerText = function(el, innerText) { - el.innerText = innerText; - }; - - exports.getInnerText = function(el) { - return el.innerText; - }; -} - -exports.getParentWindow = function(document) { - return document.defaultView || document.parentWindow; -}; - -}); - -ace.define("ace/lib/oop",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -exports.inherits = function(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); -}; - -exports.mixin = function(obj, mixin) { - for (var key in mixin) { - obj[key] = mixin[key]; - } - return obj; -}; - -exports.implement = function(proto, mixin) { - exports.mixin(proto, mixin); -}; - -}); - -ace.define("ace/lib/keys",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop"], function(acequire, exports, module) { -"use strict"; - -acequire("./fixoldbrowsers"); - -var oop = acequire("./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, - "super": 8, "meta": 8, "command": 8, "cmd": 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", - '-13': "NumpadEnter", - 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: '.', - 186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`', - 219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*' - } - }; - var name, i; - for (i in ret.FUNCTION_KEYS) { - name = ret.FUNCTION_KEYS[i].toLowerCase(); - ret[name] = parseInt(i, 10); - } - for (i in ret.PRINTABLE_KEYS) { - name = ret.PRINTABLE_KEYS[i].toLowerCase(); - ret[name] = parseInt(i, 10); - } - oop.mixin(ret, ret.MODIFIER_KEYS); - oop.mixin(ret, ret.PRINTABLE_KEYS); - oop.mixin(ret, ret.FUNCTION_KEYS); - ret.enter = ret["return"]; - ret.escape = ret.esc; - ret.del = ret["delete"]; - ret[173] = '-'; - - (function() { - var mods = ["cmd", "ctrl", "alt", "shift"]; - for (var i = Math.pow(2, mods.length); i--;) { - ret.KEY_MODS[i] = mods.filter(function(x) { - return i & ret.KEY_MODS[x]; - }).join("-") + "-"; - } - })(); - - ret.KEY_MODS[0] = ""; - ret.KEY_MODS[-1] = "input-"; - - return ret; -})(); -oop.mixin(exports, Keys); - -exports.keyCodeToString = function(keyCode) { - var keyString = Keys[keyCode]; - if (typeof keyString != "string") - keyString = String.fromCharCode(keyCode); - return keyString.toLowerCase(); -}; - -}); - -ace.define("ace/lib/useragent",["require","exports","module"], function(acequire, exports, module) { -"use strict"; -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; - } -}; -if (typeof navigator != "object") - return; - -var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase(); -var ua = navigator.userAgent; -exports.isWin = (os == "win"); -exports.isMac = (os == "mac"); -exports.isLinux = (os == "linux"); -exports.isIE = - (navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0) - ? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]) - : parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie - -exports.isOldIE = exports.isIE && exports.isIE < 9; -exports.isGecko = exports.isMozilla = (window.Controllers || window.controllers) && window.navigator.product === "Gecko"; -exports.isOldGecko = exports.isGecko && parseInt((ua.match(/rv:(\d+)/)||[])[1], 10) < 4; -exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; -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.isChromeOS = ua.indexOf(" CrOS ") >= 0; - -}); - -ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { -"use strict"; - -var keys = acequire("./keys"); -var useragent = acequire("./useragent"); - -var pressedKeys = null; -var ts = 0; - -exports.addListener = function(elem, type, callback) { - if (elem.addEventListener) { - return elem.addEventListener(type, callback, false); - } - if (elem.attachEvent) { - var wrapper = function() { - callback.call(elem, 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; - if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey))) - return 2; - if (e.preventDefault) { - return e.button; - } - else { - return {1:0, 2:2, 4:1}[e.button]; - } -}; - -exports.capture = function(el, eventHandler, releaseCaptureHandler) { - function onMouseUp(e) { - eventHandler && eventHandler(e); - releaseCaptureHandler && releaseCaptureHandler(e); - - exports.removeListener(document, "mousemove", eventHandler, true); - exports.removeListener(document, "mouseup", onMouseUp, true); - exports.removeListener(document, "dragstart", onMouseUp, true); - } - - exports.addListener(document, "mousemove", eventHandler, true); - exports.addListener(document, "mouseup", onMouseUp, true); - exports.addListener(document, "dragstart", onMouseUp, true); - - return onMouseUp; -}; - -exports.addTouchMoveListener = function (el, callback) { - if ("ontouchmove" in el) { - var startx, starty; - exports.addListener(el, "touchstart", function (e) { - var touchObj = e.changedTouches[0]; - startx = touchObj.clientX; - starty = touchObj.clientY; - }); - exports.addListener(el, "touchmove", function (e) { - var factor = 1, - touchObj = e.changedTouches[0]; - - e.wheelX = -(touchObj.clientX - startx) / factor; - e.wheelY = -(touchObj.clientY - starty) / factor; - - startx = touchObj.clientX; - starty = touchObj.clientY; - - callback(e); - }); - } -}; - -exports.addMouseWheelListener = function(el, callback) { - if ("onmousewheel" in el) { - exports.addListener(el, "mousewheel", function(e) { - var factor = 8; - if (e.wheelDeltaX !== undefined) { - e.wheelX = -e.wheelDeltaX / factor; - e.wheelY = -e.wheelDeltaY / factor; - } else { - e.wheelX = 0; - e.wheelY = -e.wheelDelta / factor; - } - callback(e); - }); - } else if ("onwheel" in el) { - exports.addListener(el, "wheel", function(e) { - var factor = 0.35; - switch (e.deltaMode) { - case e.DOM_DELTA_PIXEL: - e.wheelX = e.deltaX * factor || 0; - e.wheelY = e.deltaY * factor || 0; - break; - case e.DOM_DELTA_LINE: - case e.DOM_DELTA_PAGE: - e.wheelX = (e.deltaX || 0) * 5; - e.wheelY = (e.deltaY || 0) * 5; - break; - } - - callback(e); - }); - } else { - exports.addListener(el, "DOMMouseScroll", function(e) { - 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.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName) { - var clicks = 0; - var startX, startY, timer; - var eventNames = { - 2: "dblclick", - 3: "tripleclick", - 4: "quadclick" - }; - - function onMousedown(e) { - if (exports.getButton(e) !== 0) { - clicks = 0; - } else if (e.detail > 1) { - clicks++; - if (clicks > 4) - clicks = 1; - } else { - clicks = 1; - } - if (useragent.isIE) { - var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5; - if (!timer || isNewClick) - clicks = 1; - if (timer) - clearTimeout(timer); - timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); - - if (clicks == 1) { - startX = e.clientX; - startY = e.clientY; - } - } - - e._clicks = clicks; - - eventHandler[callbackName]("mousedown", e); - - if (clicks > 4) - clicks = 0; - else if (clicks > 1) - return eventHandler[callbackName](eventNames[clicks], e); - } - function onDblclick(e) { - clicks = 2; - if (timer) - clearTimeout(timer); - timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600); - eventHandler[callbackName]("mousedown", e); - eventHandler[callbackName](eventNames[clicks], e); - } - if (!Array.isArray(elements)) - elements = [elements]; - elements.forEach(function(el) { - exports.addListener(el, "mousedown", onMousedown); - if (useragent.isOldIE) - exports.addListener(el, "dblclick", onDblclick); - }); -}; - -var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window) - ? function(e) { - return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0); - } - : function(e) { - return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0); - }; - -exports.getModifierString = function(e) { - return keys.KEY_MODS[getModifierHash(e)]; -}; - -function normalizeCommandKeys(callback, e, keyCode) { - var hashId = getModifierHash(e); - - if (!useragent.isMac && pressedKeys) { - if (e.getModifierState && (e.getModifierState("OS") || e.getModifierState("Win"))) - hashId |= 8; - if (pressedKeys.altGr) { - if ((3 & hashId) != 3) - pressedKeys.altGr = 0; - else - return; - } - if (keyCode === 18 || keyCode === 17) { - var location = "location" in e ? e.location : e.keyLocation; - if (keyCode === 17 && location === 1) { - if (pressedKeys[keyCode] == 1) - ts = e.timeStamp; - } else if (keyCode === 18 && hashId === 3 && location === 2) { - var dt = e.timeStamp - ts; - if (dt < 50) - pressedKeys.altGr = true; - } - } - } - - if (keyCode in keys.MODIFIER_KEYS) { - keyCode = -1; - } - if (hashId & 8 && (keyCode >= 91 && keyCode <= 93)) { - keyCode = -1; - } - - if (!hashId && keyCode === 13) { - var location = "location" in e ? e.location : e.keyLocation; - if (location === 3) { - callback(e, hashId, -keyCode); - if (e.defaultPrevented) - return; - } - } - - if (useragent.isChromeOS && hashId & 8) { - callback(e, hashId, keyCode); - if (e.defaultPrevented) - return; - else - hashId &= ~8; - } - 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 && !("KeyboardEvent" in window))) { - var lastKeyDownKeyCode = null; - addListener(el, "keydown", function(e) { - lastKeyDownKeyCode = e.keyCode; - }); - addListener(el, "keypress", function(e) { - return normalizeCommandKeys(callback, e, lastKeyDownKeyCode); - }); - } else { - var lastDefaultPrevented = null; - - addListener(el, "keydown", function(e) { - pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1; - var result = normalizeCommandKeys(callback, e, e.keyCode); - lastDefaultPrevented = e.defaultPrevented; - return result; - }); - - addListener(el, "keypress", function(e) { - if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) { - exports.stopEvent(e); - lastDefaultPrevented = null; - } - }); - - addListener(el, "keyup", function(e) { - pressedKeys[e.keyCode] = null; - }); - - if (!pressedKeys) { - resetPressedKeys(); - addListener(window, "focus", resetPressedKeys); - } - } -}; -function resetPressedKeys() { - pressedKeys = Object.create(null); -} - -if (typeof window == "object" && window.postMessage && !useragent.isOldIE) { - 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, "*"); - }; -} - - -exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame - || window.mozRequestAnimationFrame - || window.webkitRequestAnimationFrame - || window.msRequestAnimationFrame - || window.oRequestAnimationFrame); - -if (exports.nextFrame) - exports.nextFrame = exports.nextFrame.bind(window); -else - exports.nextFrame = function(callback) { - setTimeout(callback, 17); - }; -}); - -ace.define("ace/lib/lang",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -exports.last = function(a) { - return a[a.length - 1]; -}; - -exports.stringReverse = function(string) { - return string.split("").reverse().join(""); -}; - -exports.stringRepeat = function (string, count) { - var result = ''; - while (count > 0) { - if (count & 1) - result += string; - - if (count >>= 1) - string += string; - } - return result; -}; - -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= 53) { - onInput(); - } - }; - - - - var syncComposition = lang.delayedCall(onCompositionUpdate, 50); - - event.addListener(text, "compositionstart", onCompositionStart); - if (useragent.isGecko) { - event.addListener(text, "text", function(){syncComposition.schedule()}); - } else { - event.addListener(text, "keyup", function(){syncComposition.schedule()}); - event.addListener(text, "keydown", function(){syncComposition.schedule()}); - } - event.addListener(text, "compositionend", onCompositionEnd); - - this.getElement = function() { - return text; - }; - - this.setReadOnly = function(readOnly) { - text.readOnly = readOnly; - }; - - this.onContextMenu = function(e) { - afterContextMenu = true; - resetSelection(host.selection.isEmpty()); - host._emit("nativecontextmenu", {target: host, domEvent: e}); - this.moveToMouse(e, true); - }; - - this.moveToMouse = function(e, bringToFront) { - if (!bringToFront && useragent.isOldIE) - return; - if (!tempStyle) - tempStyle = text.style.cssText; - text.style.cssText = (bringToFront ? "z-index:100000;" : "") - + "height:" + text.style.height + ";" - + (useragent.isIE ? "opacity:0.1;" : ""); - - var rect = host.container.getBoundingClientRect(); - var style = dom.computedStyle(host.container); - var top = rect.top + (parseInt(style.borderTopWidth) || 0); - var left = rect.left + (parseInt(rect.borderLeftWidth) || 0); - var maxTop = rect.bottom - top - text.clientHeight -2; - var move = function(e) { - text.style.left = e.clientX - left - 2 + "px"; - text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px"; - }; - move(e); - - if (e.type != "mousedown") - return; - - if (host.renderer.$keepTextAreaAtCursor) - host.renderer.$keepTextAreaAtCursor = null; - - clearTimeout(closeTimeout); - if (useragent.isWin && !useragent.isOldIE) - event.capture(host.container, move, onContextMenuClose); - }; - - this.onContextMenuClose = onContextMenuClose; - var closeTimeout; - function onContextMenuClose() { - clearTimeout(closeTimeout); - closeTimeout = setTimeout(function () { - if (tempStyle) { - text.style.cssText = tempStyle; - tempStyle = ''; - } - if (host.renderer.$keepTextAreaAtCursor == null) { - host.renderer.$keepTextAreaAtCursor = true; - host.renderer.$moveTextAreaToCursor(); - } - }, useragent.isOldIE ? 200 : 0); - } - - var onContextMenu = function(e) { - host.textInput.onContextMenu(e); - onContextMenuClose(); - }; - event.addListener(text, "mouseup", onContextMenu); - event.addListener(text, "mousedown", function(e) { - e.preventDefault(); - onContextMenuClose(); - }); - event.addListener(host.renderer.scroller, "contextmenu", onContextMenu); - event.addListener(text, "contextmenu", onContextMenu); -}; - -exports.TextInput = TextInput; -}); - -ace.define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { -"use strict"; - -var dom = acequire("../lib/dom"); -var event = acequire("../lib/event"); -var useragent = acequire("../lib/useragent"); - -var DRAG_OFFSET = 0; // 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.onMouseWheel.bind(mouseHandler)); - editor.setDefaultHandler("touchmove", this.onTouchMove.bind(mouseHandler)); - - var exports = ["select", "startSelect", "selectEnd", "selectAllEnd", "selectByWordsEnd", - "selectByLinesEnd", "dragWait", "dragWaitEnd", "focusWait"]; - - exports.forEach(function(x) { - mouseHandler[x] = this[x]; - }, this); - - mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange"); - mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange"); -} - -(function() { - - this.onMouseDown = function(ev) { - var inSelection = ev.inSelection(); - var pos = ev.getDocumentPosition(); - this.mousedownEvent = ev; - var editor = this.editor; - - var button = ev.getButton(); - if (button !== 0) { - var selectionRange = editor.getSelectionRange(); - var selectionEmpty = selectionRange.isEmpty(); - editor.$blockScrolling++; - if (selectionEmpty || button == 1) - editor.selection.moveToPosition(pos); - editor.$blockScrolling--; - if (button == 2) - editor.textInput.onContextMenu(ev.domEvent); - return; // stopping event here breaks contextmenu on ff mac - } - - this.mousedownEvent.time = Date.now(); - if (inSelection && !editor.isFocused()) { - editor.focus(); - if (this.$focusTimout && !this.$clickSelection && !editor.inMultiSelectMode) { - this.setState("focusWait"); - this.captureMouse(ev); - return; - } - } - - this.captureMouse(ev); - this.startSelect(pos, ev.domEvent._clicks > 1); - return ev.preventDefault(); - }; - - this.startSelect = function(pos, waitForClickSelection) { - pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y); - var editor = this.editor; - editor.$blockScrolling++; - if (this.mousedownEvent.getShiftKey()) - editor.selection.selectToPosition(pos); - else if (!waitForClickSelection) - editor.selection.moveToPosition(pos); - if (!waitForClickSelection) - this.select(); - if (editor.renderer.scroller.setCapture) { - editor.renderer.scroller.setCapture(); - } - editor.setStyle("ace_selecting"); - this.setState("select"); - editor.$blockScrolling--; - }; - - this.select = function() { - var anchor, editor = this.editor; - var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y); - editor.$blockScrolling++; - 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 { - var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); - cursor = orientedRange.cursor; - anchor = orientedRange.anchor; - } - editor.selection.setSelectionAnchor(anchor.row, anchor.column); - } - editor.selection.selectToPosition(cursor); - editor.$blockScrolling--; - 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); - editor.$blockScrolling++; - 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; - if (range.end.row != cursor.row || range.end.column != cursor.column) - cursor = range.start; - } else if (cmpEnd == 1 && cmpStart >= 0) { - anchor = this.$clickSelection.start; - if (range.start.row != cursor.row || range.start.column != cursor.column) - cursor = range.end; - } else if (cmpStart == -1 && cmpEnd == 1) { - cursor = range.end; - anchor = range.start; - } else { - var orientedRange = calcRangeOrientation(this.$clickSelection, cursor); - cursor = orientedRange.cursor; - anchor = orientedRange.anchor; - } - editor.selection.setSelectionAnchor(anchor.row, anchor.column); - } - editor.selection.selectToPosition(cursor); - editor.$blockScrolling--; - editor.renderer.scrollCursorIntoView(); - }; - - this.selectEnd = - this.selectAllEnd = - this.selectByWordsEnd = - this.selectByLinesEnd = function() { - this.$clickSelection = null; - this.editor.unsetStyle("ace_selecting"); - if (this.editor.renderer.scroller.releaseCapture) { - this.editor.renderer.scroller.releaseCapture(); - } - }; - - this.focusWait = function() { - var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); - var time = Date.now(); - - if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimout) - this.startSelect(this.mousedownEvent.getDocumentPosition()); - }; - - this.onDoubleClick = function(ev) { - var pos = ev.getDocumentPosition(); - var editor = this.editor; - var session = editor.session; - - var range = session.getBracketRange(pos); - if (range) { - if (range.isEmpty()) { - range.start.column--; - range.end.column++; - } - this.setState("select"); - } else { - range = editor.selection.getWordRange(pos.row, pos.column); - this.setState("selectByWords"); - } - this.$clickSelection = range; - this.select(); - }; - - this.onTripleClick = function(ev) { - var pos = ev.getDocumentPosition(); - var editor = this.editor; - - this.setState("selectByLines"); - var range = editor.getSelectionRange(); - if (range.isMultiLine() && range.contains(pos.row, pos.column)) { - this.$clickSelection = editor.selection.getLineRange(range.start.row); - this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end; - } else { - this.$clickSelection = editor.selection.getLineRange(pos.row); - } - this.select(); - }; - - this.onQuadClick = function(ev) { - var editor = this.editor; - - editor.selectAll(); - this.$clickSelection = editor.getSelectionRange(); - this.setState("selectAll"); - }; - - this.onMouseWheel = function(ev) { - if (ev.getAccelKey()) - return; - if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) { - ev.wheelX = ev.wheelY; - ev.wheelY = 0; - } - - var t = ev.domEvent.timeStamp; - var dt = t - (this.$lastScrollTime||0); - - var editor = this.editor; - var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); - if (isScrolable || dt < 200) { - this.$lastScrollTime = t; - editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); - return ev.stop(); - } - }; - - this.onTouchMove = function (ev) { - var t = ev.domEvent.timeStamp; - var dt = t - (this.$lastScrollTime || 0); - - var editor = this.editor; - var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); - if (isScrolable || dt < 200) { - this.$lastScrollTime = t; - editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed); - return ev.stop(); - } - }; - -}).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)); -} - -function calcRangeOrientation(range, cursor) { - if (range.start.row == range.end.row) - var cmp = 2 * cursor.column - range.start.column - range.end.column; - else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column) - var cmp = cursor.column - 4; - else - var cmp = 2 * cursor.row - range.start.row - range.end.row; - - if (cmp < 0) - return {cursor: range.start, anchor: range.end}; - else - return {cursor: range.end, anchor: range.start}; -} - -}); - -ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var dom = acequire("./lib/dom"); -function Tooltip (parentNode) { - this.isOpen = false; - this.$element = null; - this.$parentNode = parentNode; -} - -(function() { - this.$init = function() { - this.$element = dom.createElement("div"); - this.$element.className = "ace_tooltip"; - this.$element.style.display = "none"; - this.$parentNode.appendChild(this.$element); - return this.$element; - }; - this.getElement = function() { - return this.$element || this.$init(); - }; - this.setText = function(text) { - dom.setInnerText(this.getElement(), text); - }; - this.setHtml = function(html) { - this.getElement().innerHTML = html; - }; - this.setPosition = function(x, y) { - this.getElement().style.left = x + "px"; - this.getElement().style.top = y + "px"; - }; - this.setClassName = function(className) { - dom.addCssClass(this.getElement(), className); - }; - this.show = function(text, x, y) { - if (text != null) - this.setText(text); - if (x != null && y != null) - this.setPosition(x, y); - if (!this.isOpen) { - this.getElement().style.display = "block"; - this.isOpen = true; - } - }; - - this.hide = function() { - if (this.isOpen) { - this.getElement().style.display = "none"; - this.isOpen = false; - } - }; - this.getHeight = function() { - return this.getElement().offsetHeight; - }; - this.getWidth = function() { - return this.getElement().offsetWidth; - }; - -}).call(Tooltip.prototype); - -exports.Tooltip = Tooltip; -}); - -ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(acequire, exports, module) { -"use strict"; -var dom = acequire("../lib/dom"); -var oop = acequire("../lib/oop"); -var event = acequire("../lib/event"); -var Tooltip = acequire("../tooltip").Tooltip; - -function GutterHandler(mouseHandler) { - var editor = mouseHandler.editor; - var gutter = editor.renderer.$gutterLayer; - var tooltip = new GutterTooltip(editor.container); - - mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) { - if (!editor.isFocused() || e.getButton() != 0) - return; - var gutterRegion = gutter.getRegion(e); - - if (gutterRegion == "foldWidgets") - return; - - var row = e.getDocumentPosition().row; - var selection = editor.session.selection; - - if (e.getShiftKey()) - selection.selectTo(row, 0); - else { - if (e.domEvent.detail == 2) { - editor.selectAll(); - return e.preventDefault(); - } - mouseHandler.$clickSelection = editor.selection.getLineRange(row); - } - mouseHandler.setState("selectByLines"); - mouseHandler.captureMouse(e); - return e.preventDefault(); - }); - - - var tooltipTimeout, mouseEvent, tooltipAnnotation; - - function showTooltip() { - var row = mouseEvent.getDocumentPosition().row; - var annotation = gutter.$annotations[row]; - if (!annotation) - return hideTooltip(); - - var maxRow = editor.session.getLength(); - if (row == maxRow) { - var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row; - var pos = mouseEvent.$pos; - if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column)) - return hideTooltip(); - } - - if (tooltipAnnotation == annotation) - return; - tooltipAnnotation = annotation.text.join("
"); - - tooltip.setHtml(tooltipAnnotation); - tooltip.show(); - editor._signal("showGutterTooltip", tooltip); - editor.on("mousewheel", hideTooltip); - - if (mouseHandler.$tooltipFollowsMouse) { - moveTooltip(mouseEvent); - } else { - var gutterElement = mouseEvent.domEvent.target; - var rect = gutterElement.getBoundingClientRect(); - var style = tooltip.getElement().style; - style.left = rect.right + "px"; - style.top = rect.bottom + "px"; - } - } - - function hideTooltip() { - if (tooltipTimeout) - tooltipTimeout = clearTimeout(tooltipTimeout); - if (tooltipAnnotation) { - tooltip.hide(); - tooltipAnnotation = null; - editor._signal("hideGutterTooltip", tooltip); - editor.removeEventListener("mousewheel", hideTooltip); - } - } - - function moveTooltip(e) { - tooltip.setPosition(e.x, e.y); - } - - mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) { - var target = e.domEvent.target || e.domEvent.srcElement; - if (dom.hasCssClass(target, "ace_fold-widget")) - return hideTooltip(); - - if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse) - moveTooltip(e); - - mouseEvent = e; - if (tooltipTimeout) - return; - tooltipTimeout = setTimeout(function() { - tooltipTimeout = null; - if (mouseEvent && !mouseHandler.isMousePressed) - showTooltip(); - else - hideTooltip(); - }, 50); - }); - - event.addListener(editor.renderer.$gutter, "mouseout", function(e) { - mouseEvent = null; - if (!tooltipAnnotation || tooltipTimeout) - return; - - tooltipTimeout = setTimeout(function() { - tooltipTimeout = null; - hideTooltip(); - }, 50); - }); - - editor.on("changeSession", hideTooltip); -} - -function GutterTooltip(parentNode) { - Tooltip.call(this, parentNode); -} - -oop.inherits(GutterTooltip, Tooltip); - -(function(){ - this.setPosition = function(x, y) { - var windowWidth = window.innerWidth || document.documentElement.clientWidth; - var windowHeight = window.innerHeight || document.documentElement.clientHeight; - var width = this.getWidth(); - var height = this.getHeight(); - x += 15; - y += 15; - if (x + width > windowWidth) { - x -= (x + width) - windowWidth; - } - if (y + height > windowHeight) { - y -= 20 + height; - } - Tooltip.prototype.setPosition.call(this, x, y); - }; - -}).call(GutterTooltip.prototype); - - - -exports.GutterHandler = GutterHandler; - -}); - -ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { -"use strict"; - -var event = acequire("../lib/event"); -var useragent = acequire("../lib/useragent"); -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; - - - 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 = useragent.isMac - ? function() { return this.domEvent.metaKey; } - : function() { return this.domEvent.ctrlKey; }; - -}).call(MouseEvent.prototype); - -}); - -ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { -"use strict"; - -var dom = acequire("../lib/dom"); -var event = acequire("../lib/event"); -var useragent = acequire("../lib/useragent"); - -var AUTOSCROLL_DELAY = 200; -var SCROLL_CURSOR_DELAY = 200; -var SCROLL_CURSOR_HYSTERESIS = 5; - -function DragdropHandler(mouseHandler) { - - var editor = mouseHandler.editor; - - var blankImage = dom.createElement("img"); - blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (useragent.isOpera) - blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;"; - - var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"]; - - exports.forEach(function(x) { - mouseHandler[x] = this[x]; - }, this); - editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler)); - - - var mouseTarget = editor.container; - var dragSelectionMarker, x, y; - var timerId, range; - var dragCursor, counter = 0; - var dragOperation; - var isInternal; - var autoScrollStartTime; - var cursorMovedTime; - var cursorPointOnCaretMoved; - - this.onDragStart = function(e) { - if (this.cancelDrag || !mouseTarget.draggable) { - var self = this; - setTimeout(function(){ - self.startSelect(); - self.captureMouse(e); - }, 0); - return e.preventDefault(); - } - range = editor.getSelectionRange(); - - var dataTransfer = e.dataTransfer; - dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove"; - if (useragent.isOpera) { - editor.container.appendChild(blankImage); - blankImage.scrollTop = 0; - } - dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0); - if (useragent.isOpera) { - editor.container.removeChild(blankImage); - } - dataTransfer.clearData(); - dataTransfer.setData("Text", editor.session.getTextRange()); - - isInternal = true; - this.setState("drag"); - }; - - this.onDragEnd = function(e) { - mouseTarget.draggable = false; - isInternal = false; - this.setState(null); - if (!editor.getReadOnly()) { - var dropEffect = e.dataTransfer.dropEffect; - if (!dragOperation && dropEffect == "move") - editor.session.remove(editor.getSelectionRange()); - editor.renderer.$cursorLayer.setBlinking(true); - } - this.editor.unsetStyle("ace_dragging"); - this.editor.renderer.setCursorStyle(""); - }; - - this.onDragEnter = function(e) { - if (editor.getReadOnly() || !canAccept(e.dataTransfer)) - return; - x = e.clientX; - y = e.clientY; - if (!dragSelectionMarker) - addDragMarker(); - counter++; - e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); - return event.preventDefault(e); - }; - - this.onDragOver = function(e) { - if (editor.getReadOnly() || !canAccept(e.dataTransfer)) - return; - x = e.clientX; - y = e.clientY; - if (!dragSelectionMarker) { - addDragMarker(); - counter++; - } - if (onMouseMoveTimer !== null) - onMouseMoveTimer = null; - - e.dataTransfer.dropEffect = dragOperation = getDropEffect(e); - return event.preventDefault(e); - }; - - this.onDragLeave = function(e) { - counter--; - if (counter <= 0 && dragSelectionMarker) { - clearDragMarker(); - dragOperation = null; - return event.preventDefault(e); - } - }; - - this.onDrop = function(e) { - if (!dragCursor) - return; - var dataTransfer = e.dataTransfer; - if (isInternal) { - switch (dragOperation) { - case "move": - if (range.contains(dragCursor.row, dragCursor.column)) { - range = { - start: dragCursor, - end: dragCursor - }; - } else { - range = editor.moveText(range, dragCursor); - } - break; - case "copy": - range = editor.moveText(range, dragCursor, true); - break; - } - } else { - var dropData = dataTransfer.getData('Text'); - range = { - start: dragCursor, - end: editor.session.insert(dragCursor, dropData) - }; - editor.focus(); - dragOperation = null; - } - clearDragMarker(); - return event.preventDefault(e); - }; - - event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler)); - event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler)); - event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler)); - event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler)); - event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler)); - event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler)); - - function scrollCursorIntoView(cursor, prevCursor) { - var now = Date.now(); - var vMovement = !prevCursor || cursor.row != prevCursor.row; - var hMovement = !prevCursor || cursor.column != prevCursor.column; - if (!cursorMovedTime || vMovement || hMovement) { - editor.$blockScrolling += 1; - editor.moveCursorToPosition(cursor); - editor.$blockScrolling -= 1; - cursorMovedTime = now; - cursorPointOnCaretMoved = {x: x, y: y}; - } else { - var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y); - if (distance > SCROLL_CURSOR_HYSTERESIS) { - cursorMovedTime = null; - } else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) { - editor.renderer.scrollCursorIntoView(); - cursorMovedTime = null; - } - } - } - - function autoScroll(cursor, prevCursor) { - var now = Date.now(); - var lineHeight = editor.renderer.layerConfig.lineHeight; - var characterWidth = editor.renderer.layerConfig.characterWidth; - var editorRect = editor.renderer.scroller.getBoundingClientRect(); - var offsets = { - x: { - left: x - editorRect.left, - right: editorRect.right - x - }, - y: { - top: y - editorRect.top, - bottom: editorRect.bottom - y - } - }; - var nearestXOffset = Math.min(offsets.x.left, offsets.x.right); - var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom); - var scrollCursor = {row: cursor.row, column: cursor.column}; - if (nearestXOffset / characterWidth <= 2) { - scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2); - } - if (nearestYOffset / lineHeight <= 1) { - scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1); - } - var vScroll = cursor.row != scrollCursor.row; - var hScroll = cursor.column != scrollCursor.column; - var vMovement = !prevCursor || cursor.row != prevCursor.row; - if (vScroll || (hScroll && !vMovement)) { - if (!autoScrollStartTime) - autoScrollStartTime = now; - else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY) - editor.renderer.scrollCursorIntoView(scrollCursor); - } else { - autoScrollStartTime = null; - } - } - - function onDragInterval() { - var prevCursor = dragCursor; - dragCursor = editor.renderer.screenToTextCoordinates(x, y); - scrollCursorIntoView(dragCursor, prevCursor); - autoScroll(dragCursor, prevCursor); - } - - function addDragMarker() { - range = editor.selection.toOrientedRange(); - dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle()); - editor.clearSelection(); - if (editor.isFocused()) - editor.renderer.$cursorLayer.setBlinking(false); - clearInterval(timerId); - onDragInterval(); - timerId = setInterval(onDragInterval, 20); - counter = 0; - event.addListener(document, "mousemove", onMouseMove); - } - - function clearDragMarker() { - clearInterval(timerId); - editor.session.removeMarker(dragSelectionMarker); - dragSelectionMarker = null; - editor.$blockScrolling += 1; - editor.selection.fromOrientedRange(range); - editor.$blockScrolling -= 1; - if (editor.isFocused() && !isInternal) - editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly()); - range = null; - dragCursor = null; - counter = 0; - autoScrollStartTime = null; - cursorMovedTime = null; - event.removeListener(document, "mousemove", onMouseMove); - } - var onMouseMoveTimer = null; - function onMouseMove() { - if (onMouseMoveTimer == null) { - onMouseMoveTimer = setTimeout(function() { - if (onMouseMoveTimer != null && dragSelectionMarker) - clearDragMarker(); - }, 20); - } - } - - function canAccept(dataTransfer) { - var types = dataTransfer.types; - return !types || Array.prototype.some.call(types, function(type) { - return type == 'text/plain' || type == 'Text'; - }); - } - - function getDropEffect(e) { - var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized']; - var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized']; - - var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey; - var effectAllowed = "uninitialized"; - try { - effectAllowed = e.dataTransfer.effectAllowed.toLowerCase(); - } catch (e) {} - var dropEffect = "none"; - - if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0) - dropEffect = "copy"; - else if (moveAllowed.indexOf(effectAllowed) >= 0) - dropEffect = "move"; - else if (copyAllowed.indexOf(effectAllowed) >= 0) - dropEffect = "copy"; - - return dropEffect; - } -} - -(function() { - - this.dragWait = function() { - var interval = Date.now() - this.mousedownEvent.time; - if (interval > this.editor.getDragDelay()) - this.startDrag(); - }; - - this.dragWaitEnd = function() { - var target = this.editor.container; - target.draggable = false; - this.startSelect(this.mousedownEvent.getDocumentPosition()); - this.selectEnd(); - }; - - this.dragReadyEnd = function(e) { - this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly()); - this.editor.unsetStyle("ace_dragging"); - this.editor.renderer.setCursorStyle(""); - this.dragWaitEnd(); - }; - - this.startDrag = function(){ - this.cancelDrag = false; - var editor = this.editor; - var target = editor.container; - target.draggable = true; - editor.renderer.$cursorLayer.setBlinking(false); - editor.setStyle("ace_dragging"); - var cursorStyle = useragent.isWin ? "default" : "move"; - editor.renderer.setCursorStyle(cursorStyle); - this.setState("dragReady"); - }; - - this.onMouseDrag = function(e) { - var target = this.editor.container; - if (useragent.isIE && this.state == "dragReady") { - var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); - if (distance > 3) - target.dragDrop(); - } - if (this.state === "dragWait") { - var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y); - if (distance > 0) { - target.draggable = false; - this.startSelect(this.mousedownEvent.getDocumentPosition()); - } - } - }; - - this.onMouseDown = function(e) { - if (!this.$dragEnabled) - return; - this.mousedownEvent = e; - var editor = this.editor; - - var inSelection = e.inSelection(); - var button = e.getButton(); - var clickCount = e.domEvent.detail || 1; - if (clickCount === 1 && button === 0 && inSelection) { - if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey())) - return; - this.mousedownEvent.time = Date.now(); - var eventTarget = e.domEvent.target || e.domEvent.srcElement; - if ("unselectable" in eventTarget) - eventTarget.unselectable = "on"; - if (editor.getDragDelay()) { - if (useragent.isWebKit) { - this.cancelDrag = true; - var mouseTarget = editor.container; - mouseTarget.draggable = true; - } - this.setState("dragWait"); - } else { - this.startDrag(); - } - this.captureMouse(e, this.onMouseDrag.bind(this)); - e.defaultPrevented = true; - } - }; - -}).call(DragdropHandler.prototype); - - -function calcDistance(ax, ay, bx, by) { - return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2)); -} - -exports.DragdropHandler = DragdropHandler; - -}); - -ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; -var dom = acequire("./dom"); - -exports.get = function (url, callback) { - var xhr = new XMLHttpRequest(); - xhr.open('GET', url, true); - xhr.onreadystatechange = function () { - if (xhr.readyState === 4) { - callback(xhr.responseText); - } - }; - xhr.send(null); -}; - -exports.loadScript = function(path, callback) { - var head = dom.getDocumentHead(); - var s = document.createElement('script'); - - s.src = path; - head.appendChild(s); - - s.onload = s.onreadystatechange = function(_, isAbort) { - if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") { - s = s.onload = s.onreadystatechange = null; - if (!isAbort) - callback(); - } - }; -}; -exports.qualifyURL = function(url) { - var a = document.createElement('a'); - a.href = url; - return a.href; -} - -}); - -ace.define("ace/lib/event_emitter",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -var EventEmitter = {}; -var stopPropagation = function() { this.propagationStopped = true; }; -var preventDefault = function() { this.defaultPrevented = true; }; - -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; - - if (typeof e != "object" || !e) - e = {}; - - if (!e.type) - e.type = eventName; - if (!e.stopPropagation) - e.stopPropagation = stopPropagation; - if (!e.preventDefault) - e.preventDefault = preventDefault; - - listeners = listeners.slice(); - for (var i=0; i 1) - base = parts[parts.length - 2]; - var path = options[component + "Path"]; - if (path == null) { - path = options.basePath; - } else if (sep == "/") { - component = sep = ""; - } - if (path && path.slice(-1) != "/") - path += "/"; - return path + component + sep + base + this.get("suffix"); -}; - -exports.setModuleUrl = function(name, subst) { - return options.$moduleUrls[name] = subst; -}; - -exports.$loading = {}; -exports.loadModule = function(moduleName, onLoad) { - var module, moduleType; - if (Array.isArray(moduleName)) { - moduleType = moduleName[0]; - moduleName = moduleName[1]; - } - - try { - module = acequire(moduleName); - } catch (e) {} - if (module && !exports.$loading[moduleName]) - return onLoad && onLoad(module); - - if (!exports.$loading[moduleName]) - exports.$loading[moduleName] = []; - - exports.$loading[moduleName].push(onLoad); - - if (exports.$loading[moduleName].length > 1) - return; - - var afterLoad = function() { - acequire([moduleName], function(module) { - exports._emit("load.module", {name: moduleName, module: module}); - var listeners = exports.$loading[moduleName]; - exports.$loading[moduleName] = null; - listeners.forEach(function(onLoad) { - onLoad && onLoad(module); - }); - }); - }; - - if (!exports.get("packaged")) - return afterLoad(); - net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad); -}; -init(true);function init(packaged) { - - if (!global || !global.document) - return; - - options.packaged = packaged || acequire.packaged || module.packaged || (global.define && __webpack_require__(42).packaged); - - var scriptOptions = {}; - var scriptUrl = ""; - var currentScript = (document.currentScript || document._currentScript ); // native or polyfill - var currentDocument = currentScript && currentScript.ownerDocument || document; - - var scripts = currentDocument.getElementsByTagName("script"); - for (var i=0; i [" + 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; - } - } - }; - this.comparePoint = function(p) { - return this.compare(p.row, p.column); - }; - this.containsRange = function(range) { - return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; - }; - this.intersects = function(range) { - var cmp = this.compareRange(range); - return (cmp == -1 || cmp == 0 || cmp == 1); - }; - this.isEnd = function(row, column) { - return this.end.row == row && this.end.column == column; - }; - this.isStart = function(row, column) { - return this.start.row == row && this.start.column == column; - }; - 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; - } - }; - 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; - } - }; - 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; - }; - this.insideStart = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isEnd(row, column)) { - return false; - } else { - return true; - } - } - return false; - }; - this.insideEnd = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isStart(row, column)) { - return false; - } else { - return true; - } - } - return false; - }; - 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); - } - }; - this.compareEnd = function(row, column) { - if (this.end.row == row && this.end.column == column) { - return 1; - } else { - return this.compare(row, column); - } - }; - 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); - } - }; - this.clipRows = function(firstRow, lastRow) { - if (this.end.row > lastRow) - var end = {row: lastRow + 1, column: 0}; - else if (this.end.row < firstRow) - var end = {row: firstRow, column: 0}; - - if (this.start.row > lastRow) - var start = {row: lastRow + 1, column: 0}; - else if (this.start.row < firstRow) - var start = {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 - ); - }; - this.moveBy = function(row, column) { - this.start.row += row; - this.start.column += column; - this.end.row += row; - this.end.column += column; - }; - -}).call(Range.prototype); -Range.fromPoints = function(start, end) { - return new Range(start.row, start.column, end.row, end.column); -}; -Range.comparePoints = comparePoints; - -Range.comparePoints = function(p1, p2) { - return p1.row - p2.row || p1.column - p2.column; -}; - - -exports.Range = Range; -}); - -ace.define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var lang = acequire("./lib/lang"); -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var Range = acequire("./range").Range; -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); - } - if (this.getRange().isEmpty()) - this.$isEmpty = true; - 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.moveTo = function(row, column) { - this.clearSelection(); - this.moveCursorTo(row, column); - }; - this.moveToPosition = function(pos) { - this.clearSelection(); - 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 === true) - 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) { - 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); - var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0); - var beforeCursor = this.session.getDisplayLine( - row, null, firstColumnPosition.row, - firstColumnPosition.column - ); - - var leadingSpace = beforeCursor.match(/^\s*/); - if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart) - firstColumnPosition.column += leadingSpace[0].length; - this.moveCursorToPosition(firstColumnPosition); - }; - this.moveCursorLineEnd = function() { - var lead = this.lead; - var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column); - if (this.lead.column == lineEnd.column) { - var line = this.session.getLine(lineEnd.row); - if (lineEnd.column == line.length) { - var textEnd = line.search(/\s+$/); - if (textEnd > 0) - lineEnd.column = textEnd; - } - } - - this.moveCursorTo(lineEnd.row, lineEnd.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; - var fold = this.session.getFoldAt(row, column, 1); - if (fold) { - this.moveCursorTo(fold.end.row, fold.end.column); - return; - } - if (match = this.session.nonTokenRe.exec(rightOfCursor)) { - column += this.session.nonTokenRe.lastIndex; - this.session.nonTokenRe.lastIndex = 0; - rightOfCursor = line.substring(column); - } - if (column >= line.length) { - this.moveCursorTo(row, line.length); - this.moveCursorRight(); - if (row < this.doc.getLength() - 1) - this.moveCursorWordRight(); - return; - } - 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; - 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; - 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 (column <= 0) { - this.moveCursorTo(row, 0); - this.moveCursorLeft(); - if (row > 0) - this.moveCursorWordLeft(); - return; - } - 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); - - if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) { - if (this.session.lineWidgets && this.session.lineWidgets[docPos.row]) { - if (docPos.row > 0 || rows > 0) - docPos.row++; - } - } - 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) { - 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); - }; - 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; - }; - this.getRangeOfMovements = function(func) { - var start = this.getCursor(); - try { - func(this); - var end = this.getCursor(); - return Range.fromPoints(start,end); - } catch(e) { - return Range.fromPoints(start,start); - } finally { - this.moveCursorToPosition(start); - } - }; - - this.toJSON = function() { - if (this.rangeCount) { - var data = this.ranges.map(function(r) { - var r1 = r.clone(); - r1.isBackwards = r.cursor == r.start; - return r1; - }); - } else { - var data = this.getRange(); - data.isBackwards = this.isBackwards(); - } - return data; - }; - - this.fromJSON = function(data) { - if (data.start == undefined) { - if (this.rangeList) { - this.toSingleRange(data[0]); - for (var i = data.length; i--; ) { - var r = Range.fromPoints(data[i].start, data[i].end); - if (data[i].isBackwards) - r.cursor = r.start; - this.addRange(r, true); - } - return; - } else - data = data[0]; - } - if (this.rangeList) - this.toSingleRange(data); - this.setSelectionRange(data, data.isBackwards); - }; - - this.isEqual = function(data) { - if ((data.length || this.rangeCount) && data.length != this.rangeCount) - return false; - if (!data.length || !this.ranges) - return this.getRange().isEqual(data); - - for (var i = this.ranges.length; i--; ) { - if (!this.ranges[i].isEqual(data[i])) - return false; - } - return true; - }; - -}).call(Selection.prototype); - -exports.Selection = Selection; -}); - -ace.define("ace/tokenizer",["require","exports","module","ace/config"], function(acequire, exports, module) { -"use strict"; - -var config = acequire("./config"); -var MAX_TOKEN_COUNT = 2000; -var Tokenizer = function(rules) { - this.states = rules; - - this.regExps = {}; - this.matchMappings = {}; - for (var key in this.states) { - var state = this.states[key]; - var ruleRegExps = []; - var matchTotal = 0; - var mapping = this.matchMappings[key] = {defaultToken: "text"}; - var flag = "g"; - - var splitterRurles = []; - for (var i = 0; i < state.length; i++) { - var rule = state[i]; - if (rule.defaultToken) - mapping.defaultToken = rule.defaultToken; - if (rule.caseInsensitive) - flag = "gi"; - if (rule.regex == null) - continue; - - if (rule.regex instanceof RegExp) - rule.regex = rule.regex.toString().slice(1, -1); - var adjustedregex = rule.regex; - var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2; - if (Array.isArray(rule.token)) { - if (rule.token.length == 1 || matchcount == 1) { - rule.token = rule.token[0]; - } else if (matchcount - 1 != rule.token.length) { - this.reportError("number of classes and regexp groups doesn't match", { - rule: rule, - groupCount: matchcount - 1 - }); - rule.token = rule.token[0]; - } else { - rule.tokenArray = rule.token; - rule.token = null; - rule.onMatch = this.$arrayTokens; - } - } else if (typeof rule.token == "function" && !rule.onMatch) { - if (matchcount > 1) - rule.onMatch = this.$applyToken; - else - rule.onMatch = rule.token; - } - - if (matchcount > 1) { - if (/\\\d/.test(rule.regex)) { - adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) { - return "\\" + (parseInt(digit, 10) + matchTotal + 1); - }); - } else { - matchcount = 1; - adjustedregex = this.removeCapturingGroups(rule.regex); - } - if (!rule.splitRegex && typeof rule.token != "string") - splitterRurles.push(rule); // flag will be known only at the very end - } - - mapping[matchTotal] = i; - matchTotal += matchcount; - - ruleRegExps.push(adjustedregex); - if (!rule.onMatch) - rule.onMatch = null; - } - - if (!ruleRegExps.length) { - mapping[0] = 0; - ruleRegExps.push("$"); - } - - splitterRurles.forEach(function(rule) { - rule.splitRegex = this.createSplitterRegexp(rule.regex, flag); - }, this); - - this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag); - } -}; - -(function() { - this.$setMaxTokenCount = function(m) { - MAX_TOKEN_COUNT = m | 0; - }; - - this.$applyToken = function(str) { - var values = this.splitRegex.exec(str).slice(1); - var types = this.token.apply(this, values); - if (typeof types === "string") - return [{type: types, value: str}]; - - var tokens = []; - for (var i = 0, l = types.length; i < l; i++) { - if (values[i]) - tokens[tokens.length] = { - type: types[i], - value: values[i] - }; - } - return tokens; - }; - - this.$arrayTokens = function(str) { - if (!str) - return []; - var values = this.splitRegex.exec(str); - if (!values) - return "text"; - var tokens = []; - var types = this.tokenArray; - for (var i = 0, l = types.length; i < l; i++) { - if (values[i + 1]) - tokens[tokens.length] = { - type: types[i], - value: values[i + 1] - }; - } - return tokens; - }; - - this.removeCapturingGroups = function(src) { - var r = src.replace( - /\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g, - function(x, y) {return y ? "(?:" : x;} - ); - return r; - }; - - this.createSplitterRegexp = function(src, flag) { - if (src.indexOf("(?=") != -1) { - var stack = 0; - var inChClass = false; - var lastCapture = {}; - src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function( - m, esc, parenOpen, parenClose, square, index - ) { - if (inChClass) { - inChClass = square != "]"; - } else if (square) { - inChClass = true; - } else if (parenClose) { - if (stack == lastCapture.stack) { - lastCapture.end = index+1; - lastCapture.stack = -1; - } - stack--; - } else if (parenOpen) { - stack++; - if (parenOpen.length != 1) { - lastCapture.stack = stack - lastCapture.start = index; - } - } - return m; - }); - - if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end))) - src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end); - } - if (src.charAt(0) != "^") src = "^" + src; - if (src.charAt(src.length - 1) != "$") src += "$"; - - return new RegExp(src, (flag||"").replace("g", "")); - }; - this.getLineTokens = function(line, startState) { - if (startState && typeof startState != "string") { - var stack = startState.slice(0); - startState = stack[0]; - if (startState === "#tmp") { - stack.shift() - startState = stack.shift() - } - } else - var stack = []; - - var currentState = startState || "start"; - var state = this.states[currentState]; - if (!state) { - currentState = "start"; - state = this.states[currentState]; - } - var mapping = this.matchMappings[currentState]; - var re = this.regExps[currentState]; - re.lastIndex = 0; - - var match, tokens = []; - var lastIndex = 0; - var matchAttempts = 0; - - var token = {type: null, value: ""}; - - while (match = re.exec(line)) { - var type = mapping.defaultToken; - var rule = null; - var value = match[0]; - var index = re.lastIndex; - - if (index - value.length > lastIndex) { - var skipped = line.substring(lastIndex, index - value.length); - if (token.type == type) { - token.value += skipped; - } else { - if (token.type) - tokens.push(token); - token = {type: type, value: skipped}; - } - } - - for (var i = 0; i < match.length-2; i++) { - if (match[i + 1] === undefined) - continue; - - rule = state[mapping[i]]; - - if (rule.onMatch) - type = rule.onMatch(value, currentState, stack); - else - type = rule.token; - - if (rule.next) { - if (typeof rule.next == "string") { - currentState = rule.next; - } else { - currentState = rule.next(currentState, stack); - } - - state = this.states[currentState]; - if (!state) { - this.reportError("state doesn't exist", currentState); - currentState = "start"; - state = this.states[currentState]; - } - mapping = this.matchMappings[currentState]; - lastIndex = index; - re = this.regExps[currentState]; - re.lastIndex = index; - } - break; - } - - if (value) { - if (typeof type === "string") { - if ((!rule || rule.merge !== false) && token.type === type) { - token.value += value; - } else { - if (token.type) - tokens.push(token); - token = {type: type, value: value}; - } - } else if (type) { - if (token.type) - tokens.push(token); - token = {type: null, value: ""}; - for (var i = 0; i < type.length; i++) - tokens.push(type[i]); - } - } - - if (lastIndex == line.length) - break; - - lastIndex = index; - - if (matchAttempts++ > MAX_TOKEN_COUNT) { - if (matchAttempts > 2 * line.length) { - this.reportError("infinite loop with in ace tokenizer", { - startState: startState, - line: line - }); - } - while (lastIndex < line.length) { - if (token.type) - tokens.push(token); - token = { - value: line.substring(lastIndex, lastIndex += 2000), - type: "overflow" - }; - } - currentState = "start"; - stack = []; - break; - } - } - - if (token.type) - tokens.push(token); - - if (stack.length > 1) { - if (stack[0] !== currentState) - stack.unshift("#tmp", currentState); - } - return { - tokens : tokens, - state : stack.length ? stack : currentState - }; - }; - - this.reportError = config.reportError; - -}).call(Tokenizer.prototype); - -exports.Tokenizer = Tokenizer; -}); - -ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(acequire, exports, module) { -"use strict"; - -var lang = acequire("../lib/lang"); - -var TextHighlightRules = function() { - - this.$rules = { - "start" : [{ - token : "empty_line", - regex : '^$' - }, { - defaultToken : "text" - }] - }; -}; - -(function() { - - this.addRules = function(rules, prefix) { - if (!prefix) { - for (var key in rules) - this.$rules[key] = rules[key]; - return; - } - 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.onMatch) { - if (typeof rule.next == "string") { - if (rule.next.indexOf(prefix) !== 0) - rule.next = prefix + rule.next; - } - if (rule.nextState && rule.nextState.indexOf(prefix) !== 0) - rule.nextState = prefix + rule.nextState; - } - } - this.$rules[prefix + key] = state; - } - }; - - this.getRules = function() { - return this.$rules; - }; - - this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) { - var embedRules = typeof HighlightRules == "function" - ? new HighlightRules().getRules() - : HighlightRules; - 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); - - if (escapeRules) { - var addRules = Array.prototype[append ? "push" : "unshift"]; - for (var i = 0; i < states.length; i++) - addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules)); - } - - if (!this.$embeds) - this.$embeds = []; - this.$embeds.push(prefix); - }; - - this.getEmbeds = function() { - return this.$embeds; - }; - - var pushState = function(currentState, stack) { - if (currentState != "start" || stack.length) - stack.unshift(this.nextState, currentState); - return this.nextState; - }; - var popState = function(currentState, stack) { - stack.shift(); - return stack.shift() || "start"; - }; - - this.normalizeRules = function() { - var id = 0; - var rules = this.$rules; - function processState(key) { - var state = rules[key]; - state.processed = true; - for (var i = 0; i < state.length; i++) { - var rule = state[i]; - var toInsert = null; - if (Array.isArray(rule)) { - toInsert = rule; - rule = {}; - } - if (!rule.regex && rule.start) { - rule.regex = rule.start; - if (!rule.next) - rule.next = []; - rule.next.push({ - defaultToken: rule.token - }, { - token: rule.token + ".end", - regex: rule.end || rule.start, - next: "pop" - }); - rule.token = rule.token + ".start"; - rule.push = true; - } - var next = rule.next || rule.push; - if (next && Array.isArray(next)) { - var stateName = rule.stateName; - if (!stateName) { - stateName = rule.token; - if (typeof stateName != "string") - stateName = stateName[0] || ""; - if (rules[stateName]) - stateName += id++; - } - rules[stateName] = next; - rule.next = stateName; - processState(stateName); - } else if (next == "pop") { - rule.next = popState; - } - - if (rule.push) { - rule.nextState = rule.next || rule.push; - rule.next = pushState; - delete rule.push; - } - - if (rule.rules) { - for (var r in rule.rules) { - if (rules[r]) { - if (rules[r].push) - rules[r].push.apply(rules[r], rule.rules[r]); - } else { - rules[r] = rule.rules[r]; - } - } - } - var includeName = typeof rule == "string" - ? rule - : typeof rule.include == "string" - ? rule.include - : ""; - if (includeName) { - toInsert = rules[includeName]; - } - - if (toInsert) { - var args = [i, 1].concat(toInsert); - if (rule.noEscape) - args = args.filter(function(x) {return !x.next;}); - state.splice.apply(state, args); - i--; - } - - if (rule.keywordMap) { - rule.token = this.createKeywordMapper( - rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive - ); - delete rule.defaultToken; - } - } - } - Object.keys(rules).forEach(processState, this); - }; - - this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) { - var keywords = Object.create(null); - Object.keys(map).forEach(function(className) { - var a = map[className]; - if (ignoreCase) - a = a.toLowerCase(); - var list = a.split(splitChar || "|"); - for (var i = list.length; i--; ) - keywords[list[i]] = className; - }); - if (Object.getPrototypeOf(keywords)) { - keywords.__proto__ = null; - } - this.$keywordList = Object.keys(keywords); - map = null; - return ignoreCase - ? function(value) {return keywords[value.toLowerCase()] || defaultToken } - : function(value) {return keywords[value] || defaultToken }; - }; - - this.getKeywords = function() { - return this.$keywords; - }; - -}).call(TextHighlightRules.prototype); - -exports.TextHighlightRules = TextHighlightRules; -}); - -ace.define("ace/mode/behaviour",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -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; -}); - -ace.define("ace/token_iterator",["require","exports","module"], function(acequire, exports, module) { -"use strict"; -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() { - 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() { - this.$tokenIndex += 1; - var rowCount; - while (this.$tokenIndex >= this.$rowTokens.length) { - this.$row += 1; - if (!rowCount) - rowCount = this.$session.getLength(); - 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; - var column = rowTokens[tokenIndex].start; - if (column !== undefined) - return column; - - column = 0; - while (tokenIndex > 0) { - tokenIndex -= 1; - column += rowTokens[tokenIndex].value.length; - } - - return column; - }; - this.getCurrentTokenPosition = function() { - return {row: this.$row, column: this.getCurrentTokenColumn()}; - }; - -}).call(TokenIterator.prototype); - -exports.TokenIterator = TokenIterator; -}); - -ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../../lib/oop"); -var Behaviour = acequire("../behaviour").Behaviour; -var TokenIterator = acequire("../../token_iterator").TokenIterator; -var lang = acequire("../../lib/lang"); - -var SAFE_INSERT_IN_TOKENS = - ["text", "paren.rparen", "punctuation.operator"]; -var SAFE_INSERT_BEFORE_TOKENS = - ["text", "paren.rparen", "punctuation.operator", "comment"]; - -var context; -var contextCache = {}; -var initContext = function(editor) { - var id = -1; - if (editor.multiSelect) { - id = editor.selection.index; - if (contextCache.rangeCount != editor.multiSelect.rangeCount) - contextCache = {rangeCount: editor.multiSelect.rangeCount}; - } - if (contextCache[id]) - return context = contextCache[id]; - context = contextCache[id] = { - autoInsertedBrackets: 0, - autoInsertedRow: -1, - autoInsertedLineEnd: "", - maybeInsertedBrackets: 0, - maybeInsertedRow: -1, - maybeInsertedLineStart: "", - maybeInsertedLineEnd: "" - }; -}; - -var getWrapped = function(selection, selected, opening, closing) { - var rowDiff = selection.end.row - selection.start.row; - return { - text: opening + selected + closing, - selection: [ - 0, - selection.start.column + 1, - rowDiff, - selection.end.column + (rowDiff ? 0 : 1) - ] - }; -}; - -var CstyleBehaviour = function() { - this.add("braces", "insertion", function(state, action, editor, session, text) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - if (text == '{') { - initContext(editor); - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, '{', '}'); - } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { - if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { - CstyleBehaviour.recordAutoInsert(editor, session, "}"); - return { - text: '{}', - selection: [1, 1] - }; - } else { - CstyleBehaviour.recordMaybeInsert(editor, session, "{"); - return { - text: '{', - selection: [1, 1] - }; - } - } - } else if (text == '}') { - initContext(editor); - 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 && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { - CstyleBehaviour.popAutoInsertedClosing(); - return { - text: '', - selection: [1, 1] - }; - } - } - } else if (text == "\n" || text == "\r\n") { - initContext(editor); - var closing = ""; - if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { - closing = lang.stringRepeat("}", context.maybeInsertedBrackets); - CstyleBehaviour.clearMaybeInsertedClosing(); - } - 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 next_indent = this.$getIndent(session.getLine(openBracePos.row)); - } else if (closing) { - var next_indent = this.$getIndent(line); - } else { - CstyleBehaviour.clearMaybeInsertedClosing(); - return; - } - var indent = next_indent + session.getTabString(); - - return { - text: '\n' + indent + '\n' + next_indent + closing, - selection: [1, indent.length, 1, indent.length] - }; - } else { - CstyleBehaviour.clearMaybeInsertedClosing(); - } - }); - - this.add("braces", "deletion", function(state, action, editor, session, range) { - var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '{') { - initContext(editor); - 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; - } else { - context.maybeInsertedBrackets--; - } - } - }); - - this.add("parens", "insertion", function(state, action, editor, session, text) { - if (text == '(') { - initContext(editor); - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, '(', ')'); - } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { - CstyleBehaviour.recordAutoInsert(editor, session, ")"); - return { - text: '()', - selection: [1, 1] - }; - } - } else if (text == ')') { - initContext(editor); - 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 && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { - CstyleBehaviour.popAutoInsertedClosing(); - 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 == '(') { - initContext(editor); - 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("brackets", "insertion", function(state, action, editor, session, text) { - if (text == '[') { - initContext(editor); - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, '[', ']'); - } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { - CstyleBehaviour.recordAutoInsert(editor, session, "]"); - return { - text: '[]', - selection: [1, 1] - }; - } - } else if (text == ']') { - initContext(editor); - 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 && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { - CstyleBehaviour.popAutoInsertedClosing(); - return { - text: '', - selection: [1, 1] - }; - } - } - } - }); - - this.add("brackets", "deletion", function(state, action, editor, session, range) { - var selected = session.doc.getTextRange(range); - if (!range.isMultiLine() && selected == '[') { - initContext(editor); - 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 == "'") { - if (this.lineCommentStart && this.lineCommentStart.indexOf(text) != -1) - return; - initContext(editor); - var quote = text; - var selection = editor.getSelectionRange(); - var selected = session.doc.getTextRange(selection); - if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { - return getWrapped(selection, selected, quote, quote); - } else if (!selected) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - var leftChar = line.substring(cursor.column-1, cursor.column); - var rightChar = line.substring(cursor.column, cursor.column + 1); - - var token = session.getTokenAt(cursor.row, cursor.column); - var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); - if (leftChar == "\\" && token && /escape/.test(token.type)) - return null; - - var stringBefore = token && /string|escape/.test(token.type); - var stringAfter = !rightToken || /string|escape/.test(rightToken.type); - - var pair; - if (rightChar == quote) { - pair = stringBefore !== stringAfter; - if (pair && /string\.end/.test(rightToken.type)) - pair = false; - } else { - if (stringBefore && !stringAfter) - return null; // wrap string with different quote - if (stringBefore && stringAfter) - return null; // do not pair quotes inside strings - var wordRe = session.$mode.tokenRe; - wordRe.lastIndex = 0; - var isWordBefore = wordRe.test(leftChar); - wordRe.lastIndex = 0; - var isWordAfter = wordRe.test(leftChar); - if (isWordBefore || isWordAfter) - return null; // before or after alphanumeric - if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) - return null; // there is rightChar and it isn't closing - pair = true; - } - return { - text: pair ? quote + quote : "", - 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 == "'")) { - initContext(editor); - var line = session.doc.getLine(range.start.row); - var rightChar = line.substring(range.start.column + 1, range.start.column + 2); - if (rightChar == selected) { - range.end.column++; - return range; - } - } - }); - -}; - - -CstyleBehaviour.isSaneInsertion = function(editor, session) { - var cursor = editor.getCursorPosition(); - var iterator = new TokenIterator(session, cursor.row, cursor.column); - if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { - var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); - if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) - return false; - } - iterator.stepForward(); - return iterator.getCurrentTokenRow() !== cursor.row || - this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); -}; - -CstyleBehaviour.$matchTokenType = function(token, types) { - return types.indexOf(token.type || token) > -1; -}; - -CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) - context.autoInsertedBrackets = 0; - context.autoInsertedRow = cursor.row; - context.autoInsertedLineEnd = bracket + line.substr(cursor.column); - context.autoInsertedBrackets++; -}; - -CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { - var cursor = editor.getCursorPosition(); - var line = session.doc.getLine(cursor.row); - if (!this.isMaybeInsertedClosing(cursor, line)) - context.maybeInsertedBrackets = 0; - context.maybeInsertedRow = cursor.row; - context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; - context.maybeInsertedLineEnd = line.substr(cursor.column); - context.maybeInsertedBrackets++; -}; - -CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { - return context.autoInsertedBrackets > 0 && - cursor.row === context.autoInsertedRow && - bracket === context.autoInsertedLineEnd[0] && - line.substr(cursor.column) === context.autoInsertedLineEnd; -}; - -CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { - return context.maybeInsertedBrackets > 0 && - cursor.row === context.maybeInsertedRow && - line.substr(cursor.column) === context.maybeInsertedLineEnd && - line.substr(0, cursor.column) == context.maybeInsertedLineStart; -}; - -CstyleBehaviour.popAutoInsertedClosing = function() { - context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); - context.autoInsertedBrackets--; -}; - -CstyleBehaviour.clearMaybeInsertedClosing = function() { - if (context) { - context.maybeInsertedBrackets = 0; - context.maybeInsertedRow = -1; - } -}; - - - -oop.inherits(CstyleBehaviour, Behaviour); - -exports.CstyleBehaviour = CstyleBehaviour; -}); - -ace.define("ace/unicode",["require","exports","module"], function(acequire, exports, module) { -"use strict"; -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$&"); -} - -}); - -ace.define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour/cstyle","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(acequire, exports, module) { -"use strict"; - -var Tokenizer = acequire("../tokenizer").Tokenizer; -var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; -var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; -var unicode = acequire("../unicode"); -var lang = acequire("../lib/lang"); -var TokenIterator = acequire("../token_iterator").TokenIterator; -var Range = acequire("../range").Range; - -var Mode = function() { - this.HighlightRules = TextHighlightRules; -}; - -(function() { - this.$defaultBehaviour = new CstyleBehaviour(); - - 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() { - if (!this.$tokenizer) { - this.$highlightRules = this.$highlightRules || new this.HighlightRules(this.$highlightRuleConfig); - this.$tokenizer = new Tokenizer(this.$highlightRules.getRules()); - } - return this.$tokenizer; - }; - - this.lineCommentStart = ""; - this.blockComment = ""; - - this.toggleCommentLines = function(state, session, startRow, endRow) { - var doc = session.doc; - - var ignoreBlankLines = true; - var shouldRemove = true; - var minIndent = Infinity; - var tabSize = session.getTabSize(); - var insertAtTabStop = false; - - if (!this.lineCommentStart) { - if (!this.blockComment) - return false; - var lineCommentStart = this.blockComment.start; - var lineCommentEnd = this.blockComment.end; - var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")"); - var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$"); - - var comment = function(line, i) { - if (testRemove(line, i)) - return; - if (!ignoreBlankLines || /\S/.test(line)) { - doc.insertInLine({row: i, column: line.length}, lineCommentEnd); - doc.insertInLine({row: i, column: minIndent}, lineCommentStart); - } - }; - - var uncomment = function(line, i) { - var m; - if (m = line.match(regexpEnd)) - doc.removeInLine(i, line.length - m[0].length, line.length); - if (m = line.match(regexpStart)) - doc.removeInLine(i, m[1].length, m[0].length); - }; - - var testRemove = function(line, row) { - if (regexpStart.test(line)) - return true; - var tokens = session.getTokens(row); - for (var i = 0; i < tokens.length; i++) { - if (tokens[i].type === "comment") - return true; - } - }; - } else { - if (Array.isArray(this.lineCommentStart)) { - var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|"); - var lineCommentStart = this.lineCommentStart[0]; - } else { - var regexpStart = lang.escapeRegExp(this.lineCommentStart); - var lineCommentStart = this.lineCommentStart; - } - regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?"); - - insertAtTabStop = session.getUseSoftTabs(); - - var uncomment = function(line, i) { - var m = line.match(regexpStart); - if (!m) return; - var start = m[1].length, end = m[0].length; - if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ") - end--; - doc.removeInLine(i, start, end); - }; - var commentWithSpace = lineCommentStart + " "; - var comment = function(line, i) { - if (!ignoreBlankLines || /\S/.test(line)) { - if (shouldInsertSpace(line, minIndent, minIndent)) - doc.insertInLine({row: i, column: minIndent}, commentWithSpace); - else - doc.insertInLine({row: i, column: minIndent}, lineCommentStart); - } - }; - var testRemove = function(line, i) { - return regexpStart.test(line); - }; - - var shouldInsertSpace = function(line, before, after) { - var spaces = 0; - while (before-- && line.charAt(before) == " ") - spaces++; - if (spaces % tabSize != 0) - return false; - var spaces = 0; - while (line.charAt(after++) == " ") - spaces++; - if (tabSize > 2) - return spaces % tabSize != tabSize - 1; - else - return spaces % tabSize == 0; - return true; - }; - } - - function iter(fun) { - for (var i = startRow; i <= endRow; i++) - fun(doc.getLine(i), i); - } - - - var minEmptyLength = Infinity; - iter(function(line, i) { - var indent = line.search(/\S/); - if (indent !== -1) { - if (indent < minIndent) - minIndent = indent; - if (shouldRemove && !testRemove(line, i)) - shouldRemove = false; - } else if (minEmptyLength > line.length) { - minEmptyLength = line.length; - } - }); - - if (minIndent == Infinity) { - minIndent = minEmptyLength; - ignoreBlankLines = false; - shouldRemove = false; - } - - if (insertAtTabStop && minIndent % tabSize != 0) - minIndent = Math.floor(minIndent / tabSize) * tabSize; - - iter(shouldRemove ? uncomment : comment); - }; - - this.toggleBlockComment = function(state, session, range, cursor) { - var comment = this.blockComment; - if (!comment) - return; - if (!comment.start && comment[0]) - comment = comment[0]; - - var iterator = new TokenIterator(session, cursor.row, cursor.column); - var token = iterator.getCurrentToken(); - - var sel = session.selection; - var initialRange = session.selection.toOrientedRange(); - var startRow, colDiff; - - if (token && /comment/.test(token.type)) { - var startRange, endRange; - while (token && /comment/.test(token.type)) { - var i = token.value.indexOf(comment.start); - if (i != -1) { - var row = iterator.getCurrentTokenRow(); - var column = iterator.getCurrentTokenColumn() + i; - startRange = new Range(row, column, row, column + comment.start.length); - break; - } - token = iterator.stepBackward(); - } - - var iterator = new TokenIterator(session, cursor.row, cursor.column); - var token = iterator.getCurrentToken(); - while (token && /comment/.test(token.type)) { - var i = token.value.indexOf(comment.end); - if (i != -1) { - var row = iterator.getCurrentTokenRow(); - var column = iterator.getCurrentTokenColumn() + i; - endRange = new Range(row, column, row, column + comment.end.length); - break; - } - token = iterator.stepForward(); - } - if (endRange) - session.remove(endRange); - if (startRange) { - session.remove(startRange); - startRow = startRange.start.row; - colDiff = -comment.start.length; - } - } else { - colDiff = comment.start.length; - startRow = range.start.row; - session.insert(range.end, comment.end); - session.insert(range.start, comment.start); - } - if (initialRange.start.row == startRow) - initialRange.start.column += colDiff; - if (initialRange.end.row == startRow) - initialRange.end.column += colDiff; - session.selection.fromOrientedRange(initialRange); - }; - - this.getNextLineIndent = function(state, line, tab) { - return this.$getIndent(line); - }; - - this.checkOutdent = function(state, line, input) { - return false; - }; - - this.autoOutdent = function(state, doc, row) { - }; - - this.$getIndent = function(line) { - return line.match(/^\s*/)[0]; - }; - - this.createWorker = function(session) { - return null; - }; - - this.createModeDelegates = function (mapping) { - this.$embeds = []; - this.$modes = {}; - for (var i in mapping) { - if (mapping[i]) { - this.$embeds.push(i); - this.$modes[i] = new mapping[i](); - } - } - - var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent", - "checkOutdent", "autoOutdent", "transformAction", "getCompletions"]; - - 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]; - if (typeof state != "string") - state = state[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; - } - } - } - } - }; - - this.getKeywords = function(append) { - if (!this.completionKeywords) { - var rules = this.$tokenizer.rules; - var completionKeywords = []; - for (var rule in rules) { - var ruleItr = rules[rule]; - for (var r = 0, l = ruleItr.length; r < l; r++) { - if (typeof ruleItr[r].token === "string") { - if (/keyword|support|storage/.test(ruleItr[r].token)) - completionKeywords.push(ruleItr[r].regex); - } - else if (typeof ruleItr[r].token === "object") { - for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) { - if (/keyword|support|storage/.test(ruleItr[r].token[a])) { - var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a]; - completionKeywords.push(rule.substr(1, rule.length - 2)); - } - } - } - } - } - this.completionKeywords = completionKeywords; - } - if (!append) - return this.$keywordList; - return completionKeywords.concat(this.$keywordList || []); - }; - - this.$createKeywordList = function() { - if (!this.$highlightRules) - this.getTokenizer(); - return this.$keywordList = this.$highlightRules.$keywordList || []; - }; - - this.getCompletions = function(state, session, pos, prefix) { - var keywords = this.$keywordList || this.$createKeywordList(); - return keywords.map(function(word) { - return { - name: word, - value: word, - score: 0, - meta: "keyword" - }; - }); - }; - - this.$id = "ace/mode/text"; -}).call(Mode.prototype); - -exports.Mode = Mode; -}); - -ace.define("ace/apply_delta",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -function throwDeltaError(delta, errorText){ - console.log("Invalid Delta:", delta); - throw "Invalid Delta: " + errorText; -} - -function positionInDocument(docLines, position) { - return position.row >= 0 && position.row < docLines.length && - position.column >= 0 && position.column <= docLines[position.row].length; -} - -function validateDelta(docLines, delta) { - if (delta.action != "insert" && delta.action != "remove") - throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); - if (!(delta.lines instanceof Array)) - throwDeltaError(delta, "delta.lines must be an Array"); - if (!delta.start || !delta.end) - throwDeltaError(delta, "delta.start/end must be an present"); - var start = delta.start; - if (!positionInDocument(docLines, delta.start)) - throwDeltaError(delta, "delta.start must be contained in document"); - var end = delta.end; - if (delta.action == "remove" && !positionInDocument(docLines, end)) - throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); - var numRangeRows = end.row - start.row; - var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); - if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) - throwDeltaError(delta, "delta.range must match delta lines"); -} - -exports.applyDelta = function(docLines, delta, doNotValidate) { - - var row = delta.start.row; - var startColumn = delta.start.column; - var line = docLines[row] || ""; - switch (delta.action) { - case "insert": - var lines = delta.lines; - if (lines.length === 1) { - docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); - } else { - var args = [row, 1].concat(delta.lines); - docLines.splice.apply(docLines, args); - docLines[row] = line.substring(0, startColumn) + docLines[row]; - docLines[row + delta.lines.length - 1] += line.substring(startColumn); - } - break; - case "remove": - var endColumn = delta.end.column; - var endRow = delta.end.row; - if (row === endRow) { - docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); - } else { - docLines.splice( - row, endRow - row + 1, - line.substring(0, startColumn) + docLines[endRow].substring(endColumn) - ); - } - break; - } -} -}); - -ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; - -var Anchor = exports.Anchor = function(doc, row, column) { - this.$onChange = this.onChange.bind(this); - this.attach(doc); - - if (typeof column == "undefined") - this.setPosition(row.row, row.column); - else - this.setPosition(row, column); -}; - -(function() { - - oop.implement(this, EventEmitter); - this.getPosition = function() { - return this.$clipPositionToDocument(this.row, this.column); - }; - this.getDocument = function() { - return this.document; - }; - this.$insertRight = false; - this.onChange = function(delta) { - if (delta.start.row == delta.end.row && delta.start.row != this.row) - return; - - if (delta.start.row > this.row) - return; - - var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); - this.setPosition(point.row, point.column, true); - }; - - function $pointsInOrder(point1, point2, equalPointsInOrder) { - var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; - return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); - } - - function $getTransformedPoint(delta, point, moveIfEqual) { - var deltaIsInsert = delta.action == "insert"; - var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); - var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); - var deltaStart = delta.start; - var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. - if ($pointsInOrder(point, deltaStart, moveIfEqual)) { - return { - row: point.row, - column: point.column - }; - } - if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { - return { - row: point.row + deltaRowShift, - column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) - }; - } - - return { - row: deltaStart.row, - column: deltaStart.column - }; - } - this.setPosition = function(row, column, noClip) { - var pos; - if (noClip) { - pos = { - row: row, - column: column - }; - } else { - pos = this.$clipPositionToDocument(row, column); - } - - if (this.row == pos.row && this.column == pos.column) - return; - - var old = { - row: this.row, - column: this.column - }; - - this.row = pos.row; - this.column = pos.column; - this._signal("change", { - old: old, - value: pos - }); - }; - this.detach = function() { - this.document.removeEventListener("change", this.$onChange); - }; - this.attach = function(doc) { - this.document = doc || this.document; - this.document.on("change", this.$onChange); - }; - this.$clipPositionToDocument = function(row, column) { - var pos = {}; - - if (row >= this.document.getLength()) { - pos.row = Math.max(0, this.document.getLength() - 1); - pos.column = this.document.getLine(pos.row).length; - } - else if (row < 0) { - pos.row = 0; - pos.column = 0; - } - else { - pos.row = row; - pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); - } - - if (column < 0) - pos.column = 0; - - return pos; - }; - -}).call(Anchor.prototype); - -}); - -ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var applyDelta = acequire("./apply_delta").applyDelta; -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var Range = acequire("./range").Range; -var Anchor = acequire("./anchor").Anchor; - -var Document = function(textOrLines) { - this.$lines = [""]; - if (textOrLines.length === 0) { - this.$lines = [""]; - } else if (Array.isArray(textOrLines)) { - this.insertMergedLines({row: 0, column: 0}, textOrLines); - } else { - this.insert({row: 0, column:0}, textOrLines); - } -}; - -(function() { - - oop.implement(this, EventEmitter); - this.setValue = function(text) { - var len = this.getLength() - 1; - this.remove(new Range(0, 0, len, this.getLine(len).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); - }; - 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); - this.$autoNewLine = match ? match[1] : "\n"; - this._signal("changeNewLineMode"); - }; - this.getNewLineCharacter = function() { - switch (this.$newLineMode) { - case "windows": - return "\r\n"; - case "unix": - return "\n"; - default: - return this.$autoNewLine || "\n"; - } - }; - - this.$autoNewLine = ""; - this.$newLineMode = "auto"; - this.setNewLineMode = function(newLineMode) { - if (this.$newLineMode === newLineMode) - return; - - this.$newLineMode = newLineMode; - this._signal("changeNewLineMode"); - }; - 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) { - return this.getLinesForRange(range).join(this.getNewLineCharacter()); - }; - this.getLinesForRange = function(range) { - var lines; - if (range.start.row === range.end.row) { - lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; - } else { - lines = this.getLines(range.start.row, range.end.row); - lines[0] = (lines[0] || "").substring(range.start.column); - var l = lines.length - 1; - if (range.end.row - range.start.row == l) - lines[l] = lines[l].substring(0, range.end.column); - } - return lines; - }; - this.insertLines = function(row, lines) { - console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); - return this.insertFullLines(row, lines); - }; - this.removeLines = function(firstRow, lastRow) { - console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); - return this.removeFullLines(firstRow, lastRow); - }; - this.insertNewLine = function(position) { - console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); - return this.insertMergedLines(position, ["", ""]); - }; - this.insert = function(position, text) { - if (this.getLength() <= 1) - this.$detectNewLine(text); - - return this.insertMergedLines(position, this.$split(text)); - }; - this.insertInLine = function(position, text) { - var start = this.clippedPos(position.row, position.column); - var end = this.pos(position.row, position.column + text.length); - - this.applyDelta({ - start: start, - end: end, - action: "insert", - lines: [text] - }, true); - - return this.clonePos(end); - }; - - this.clippedPos = function(row, column) { - var length = this.getLength(); - if (row === undefined) { - row = length; - } else if (row < 0) { - row = 0; - } else if (row >= length) { - row = length - 1; - column = undefined; - } - var line = this.getLine(row); - if (column == undefined) - column = line.length; - column = Math.min(Math.max(column, 0), line.length); - return {row: row, column: column}; - }; - - this.clonePos = function(pos) { - return {row: pos.row, column: pos.column}; - }; - - this.pos = function(row, column) { - return {row: row, column: column}; - }; - - 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; - } else { - position.row = Math.max(0, position.row); - position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); - } - return position; - }; - this.insertFullLines = function(row, lines) { - row = Math.min(Math.max(row, 0), this.getLength()); - var column = 0; - if (row < this.getLength()) { - lines = lines.concat([""]); - column = 0; - } else { - lines = [""].concat(lines); - row--; - column = this.$lines[row].length; - } - this.insertMergedLines({row: row, column: column}, lines); - }; - this.insertMergedLines = function(position, lines) { - var start = this.clippedPos(position.row, position.column); - var end = { - row: start.row + lines.length - 1, - column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length - }; - - this.applyDelta({ - start: start, - end: end, - action: "insert", - lines: lines - }); - - return this.clonePos(end); - }; - this.remove = function(range) { - var start = this.clippedPos(range.start.row, range.start.column); - var end = this.clippedPos(range.end.row, range.end.column); - this.applyDelta({ - start: start, - end: end, - action: "remove", - lines: this.getLinesForRange({start: start, end: end}) - }); - return this.clonePos(start); - }; - this.removeInLine = function(row, startColumn, endColumn) { - var start = this.clippedPos(row, startColumn); - var end = this.clippedPos(row, endColumn); - - this.applyDelta({ - start: start, - end: end, - action: "remove", - lines: this.getLinesForRange({start: start, end: end}) - }, true); - - return this.clonePos(start); - }; - this.removeFullLines = function(firstRow, lastRow) { - firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); - lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); - var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; - var deleteLastNewLine = lastRow < this.getLength() - 1; - var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); - var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); - var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); - var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); - var range = new Range(startRow, startCol, endRow, endCol); - var deletedLines = this.$lines.slice(firstRow, lastRow + 1); - - this.applyDelta({ - start: range.start, - end: range.end, - action: "remove", - lines: this.getLinesForRange(range) - }); - return deletedLines; - }; - this.removeNewLine = function(row) { - if (row < this.getLength() - 1 && row >= 0) { - this.applyDelta({ - start: this.pos(row, this.getLine(row).length), - end: this.pos(row + 1, 0), - action: "remove", - lines: ["", ""] - }); - } - }; - this.replace = function(range, text) { - if (!(range instanceof Range)) - range = Range.fromPoints(range.start, range.end); - if (text.length === 0 && range.isEmpty()) - return range.start; - if (text == this.getTextRange(range)) - return range.end; - - this.remove(range); - var end; - if (text) { - end = this.insert(range.start, text); - } - else { - end = range.start; - } - - return end; - }; - this.applyDeltas = function(deltas) { - for (var i=0; i=0; i--) { - this.revertDelta(deltas[i]); - } - }; - this.applyDelta = function(delta, doNotValidate) { - var isInsert = delta.action == "insert"; - if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] - : !Range.comparePoints(delta.start, delta.end)) { - return; - } - - if (isInsert && delta.lines.length > 20000) - this.$splitAndapplyLargeDelta(delta, 20000); - applyDelta(this.$lines, delta, doNotValidate); - this._signal("change", delta); - }; - - this.$splitAndapplyLargeDelta = function(delta, MAX) { - var lines = delta.lines; - var l = lines.length; - var row = delta.start.row; - var column = delta.start.column; - var from = 0, to = 0; - do { - from = to; - to += MAX - 1; - var chunk = lines.slice(from, to); - if (to > l) { - delta.lines = chunk; - delta.start.row = row + from; - delta.start.column = column; - break; - } - chunk.push(""); - this.applyDelta({ - start: this.pos(row + from, column), - end: this.pos(row + to, column = 0), - action: delta.action, - lines: chunk - }, true); - } while(true); - }; - this.revertDelta = function(delta) { - this.applyDelta({ - start: this.clonePos(delta.start), - end: this.clonePos(delta.end), - action: (delta.action == "insert" ? "remove" : "insert"), - lines: delta.lines.slice() - }); - }; - this.indexToPosition = function(index, startRow) { - var lines = this.$lines || this.getAllLines(); - var newlineLength = this.getNewLineCharacter().length; - for (var i = startRow || 0, l = lines.length; i < l; i++) { - index -= lines[i].length + newlineLength; - if (index < 0) - return {row: i, column: index + lines[i].length + newlineLength}; - } - return {row: l-1, column: lines[l-1].length}; - }; - this.positionToIndex = function(pos, startRow) { - var lines = this.$lines || this.getAllLines(); - var newlineLength = this.getNewLineCharacter().length; - var index = 0; - var row = Math.min(pos.row, lines.length); - for (var i = startRow || 0; i < row; ++i) - index += lines[i].length + newlineLength; - - return index + pos.column; - }; - -}).call(Document.prototype); - -exports.Document = Document; -}); - -ace.define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; - -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 currentLine = self.currentLine; - var endLine = -1; - var doc = self.doc; - - var startLine = currentLine; - while (self.lines[currentLine]) - currentLine++; - - var len = doc.getLength(); - var processedLines = 0; - self.running = false; - while (currentLine < len) { - self.$tokenizeRow(currentLine); - endLine = currentLine; - do { - currentLine++; - } while (self.lines[currentLine]); - processedLines ++; - if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) { - self.running = setTimeout(self.$worker, 20); - break; - } - } - self.currentLine = currentLine; - - if (startLine <= endLine) - self.fireUpdateEvent(startLine, endLine); - }; -}; - -(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._signal("update", {data: data}); - }; - this.start = function(startRow) { - this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength()); - this.lines.splice(this.currentLine, this.lines.length); - this.states.splice(this.currentLine, this.states.length); - - this.stop(); - this.running = setTimeout(this.$worker, 700); - }; - - this.scheduleStart = function() { - if (!this.running) - this.running = setTimeout(this.$worker, 700); - } - - this.$updateOnChange = function(delta) { - var startRow = delta.start.row; - var len = delta.end.row - startRow; - - if (len === 0) { - this.lines[startRow] = null; - } else if (delta.action == "remove") { - 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(); - }; - 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]; - - var data = this.tokenizer.getLineTokens(line, state, row); - - 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; -}); - -ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { -"use strict"; - -var lang = acequire("./lib/lang"); -var oop = acequire("./lib/oop"); -var Range = acequire("./range").Range; - -var SearchHighlight = function(regExp, clazz, type) { - this.setRegexp(regExp); - this.clazz = clazz; - this.type = type || "text"; -}; - -(function() { - this.MAX_RANGES = 500; - - 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); - if (ranges.length > this.MAX_RANGES) - ranges = ranges.slice(0, this.MAX_RANGES); - 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); - } - } - }; - -}).call(SearchHighlight.prototype); - -exports.SearchHighlight = SearchHighlight; -}); - -ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("../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() { - 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 new Error("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 new Error("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, - cmp, 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]; - - cmp = fold.range.compareStart(endRow, endColumn); - if (cmp == -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 (stop || cmp === 0) { - return; - } - 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) - { - 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 pos = this.getNextFoldTo(row, column); - - if (!pos || pos.kind == "inside") - return null; - - var fold = pos.fold; - var folds = this.folds; - var foldData = this.foldData; - - var i = folds.indexOf(fold); - var foldBefore = folds[i - 1]; - this.end.row = foldBefore.end.row; - this.end.column = foldBefore.end.column; - 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]); - } - 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; - - 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; -}); - -ace.define("ace/range_list",["require","exports","module","ace/range"], function(acequire, exports, module) { -"use strict"; -var Range = acequire("./range").Range; -var comparePoints = Range.comparePoints; - -var RangeList = function() { - this.ranges = []; -}; - -(function() { - this.comparePoints = comparePoints; - - this.pointIndex = function(pos, excludeEdges, startIndex) { - var list = this.ranges; - - for (var i = startIndex || 0; i < list.length; i++) { - var range = list[i]; - var cmpEnd = comparePoints(pos, range.end); - if (cmpEnd > 0) - continue; - var cmpStart = comparePoints(pos, range.start); - if (cmpEnd === 0) - return excludeEdges && cmpStart !== 0 ? -i-2 : i; - if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges)) - return i; - - return -i-1; - } - return -i - 1; - }; - - this.add = function(range) { - var excludeEdges = !range.isEmpty(); - var startIndex = this.pointIndex(range.start, excludeEdges); - if (startIndex < 0) - startIndex = -startIndex - 1; - - var endIndex = this.pointIndex(range.end, excludeEdges, 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.apply(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); - }; - this.merge = function() { - var removed = []; - var list = this.ranges; - - list = list.sort(function(a, b) { - return comparePoints(a.start, b.start); - }); - - var next = list[0], range; - for (var i = 1; i < list.length; i++) { - range = next; - next = list[i]; - var cmp = comparePoints(range.end, next.start); - if (cmp < 0) - continue; - - if (cmp == 0 && !range.isEmpty() && !next.isEmpty()) - continue; - - if (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--; - } - - this.ranges = list; - - 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(delta) { - if (delta.action == "insert"){ - var start = delta.start; - var end = delta.end; - } else { - var end = delta.start; - var start = delta.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 ) { - if (r.start.column == start.column && this.$insertRight) { - } else { - r.start.column += colDiff; - r.start.row += lineDif; - } - } - if (r.end.row == startRow && r.end.column >= start.column) { - if (r.end.column == start.column && this.$insertRight) { - continue; - } - if (r.end.column == start.column && colDiff > 0 && i < n - 1) { - if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column) - r.end.column -= colDiff; - } - 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; -}); - -ace.define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("../range").Range; -var RangeList = acequire("../range_list").RangeList; -var oop = acequire("../lib/oop") -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 = this.ranges = []; -}; - -oop.inherits(Fold, RangeList); - -(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()); - }); - fold.collapseChildren = this.collapseChildren; - return fold; - }; - - this.addSubFold = function(fold) { - if (this.range.isEqual(fold)) - return; - - if (!this.range.containsRange(fold)) - throw new Error("A fold can't intersect already existing fold" + fold.range + this.range); - consumeRange(fold, this.start); - - var row = fold.start.row, column = fold.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); - 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 new Error("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; - }; - - this.restoreRange = function(range) { - return restoreRange(range, this.start); - }; - -}).call(Fold.prototype); - -function consumePoint(point, anchor) { - point.row -= anchor.row; - if (point.row == 0) - point.column -= anchor.column; -} -function consumeRange(range, anchor) { - consumePoint(range.start, anchor); - consumePoint(range.end, anchor); -} -function restorePoint(point, anchor) { - if (point.row == 0) - point.column += anchor.column; - point.row += anchor.row; -} -function restoreRange(range, anchor) { - restorePoint(range.start, anchor); - restorePoint(range.end, anchor); -} - -}); - -ace.define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("../range").Range; -var FoldLine = acequire("./fold_line").FoldLine; -var Fold = acequire("./fold").Fold; -var TokenIterator = acequire("../token_iterator").TokenIterator; - -function Folding() { - 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) { - 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) { - continue; - } - else if (cmp == -2) { - 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 - if (cmp == 42) { - break; - } - foundFolds.push(fold); - } - } - start.column -= 1; - end.column += 1; - - return foundFolds; - }; - - this.getFoldsInRangeList = function(ranges) { - if (Array.isArray(ranges)) { - var folds = []; - ranges.forEach(function(range) { - folds = folds.concat(this.getFoldsInRange(range)); - }, this); - } else { - var folds = this.getFoldsInRange(ranges); - } - return folds; - }; - this.getAllFolds = function() { - var folds = []; - var foldLines = this.$foldData; - - for (var i = 0; i < foldLines.length; i++) - for (var j = 0; j < foldLines[i].folds.length; j++) - folds.push(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 } - }; - 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; - }; - 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); - fold.collapseChildren = range.collapseChildren; - } - this.$clipRangeToDocument(fold.range); - - var startRow = fold.start.row; - var startColumn = fold.start.column; - var endRow = fold.end.row; - var endColumn = fold.end.column; - if (!(startRow < endRow || - startRow == endRow && startColumn <= endColumn - 2)) - throw new Error("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)) - this.removeFold(startFold); - - if (endFold && !endFold.range.isEnd(endRow, endColumn)) - this.removeFold(endFold); - var folds = this.getFoldsInRange(fold.range); - if (folds.length > 0) { - this.removeFolds(folds); - folds.forEach(function(subFold) { - fold.addSubFold(subFold); - }); - } - - 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) { - var foldLineNext = foldData[i + 1]; - if (foldLineNext && foldLineNext.start.row == endRow) { - 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); - this.$modified = true; - this._signal("changeFold", { data: fold, action: "add" }); - - 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; - if (folds.length == 1) { - foldLines.splice(foldLines.indexOf(foldLine), 1); - } else - 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 (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 - if (fold.sameRow) { - folds.splice(folds.indexOf(fold), 1); - } else - { - 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.$updating) { - if (this.$useWrapMode) - this.$updateWrapData(startRow, endRow); - else - this.$updateRowLengthCache(startRow, endRow); - } - this.$modified = true; - this._signal("changeFold", { data: fold, action: "remove" }); - }; - - this.removeFolds = function(folds) { - 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(subFold) { - fold.restoreRange(subFold); - this.addFold(subFold); - }, this); - if (fold.collapseChildren > 0) { - this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1); - } - 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); - expandInner = true; - } 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.getFoldsInRangeList(range); - if (expandInner) { - this.removeFolds(folds); - } else { - var subFolds = folds; - while (subFolds.length) { - this.expandFolds(subFolds); - subFolds = this.getFoldsInRangeList(range); - } - } - if (folds.length) - return folds; - }; - 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.getRowFoldStart = function(docRow, startFoldRow) { - var foldLine = this.getFoldLine(docRow, startFoldRow); - return foldLine ? foldLine.start.row : docRow; - }; - - this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) { - if (startRow == null) - startRow = foldLine.start.row; - if (startColumn == null) - startColumn = 0; - if (endRow == null) - endRow = foldLine.end.row; - if (endColumn == null) - endColumn = this.getLine(endRow).length; - var doc = this.doc; - var textLine = ""; - - foldLine.walk(function(placeholder, row, column, lastColumn) { - if (row < startRow) - return; - if (row == startRow) { - if (column < startColumn) - return; - lastColumn = Math.max(startColumn, lastColumn); - } - - if (placeholder != null) { - textLine += placeholder; - } else { - textLine += doc.getLine(row).substring(lastColumn, column); - } - }, 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, dir) { - 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(/\..*/, "\\.")); - if (dir != 1) { - 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); - - if (dir != -1) { - do { - token = iterator.stepForward(); - } while (token && re.test(token.type)); - token = iterator.stepBackward(); - } else - token = iterator.getCurrentToken(); - - range.end.row = iterator.getCurrentTokenRow(); - range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2; - return range; - } - }; - - this.foldAll = function(startRow, endRow, depth) { - if (depth == undefined) - depth = 100000; // JSON.stringify doesn't hanle Infinity - var foldWidgets = this.foldWidgets; - if (!foldWidgets) - return; // mode doesn't support folding - endRow = endRow || this.getLength(); - startRow = startRow || 0; - for (var row = startRow; row < endRow; row++) { - if (foldWidgets[row] == null) - foldWidgets[row] = this.getFoldWidget(row); - if (foldWidgets[row] != "start") - continue; - - var range = this.getFoldWidgetRange(row); - if (range && range.isMultiLine() - && range.end.row <= endRow - && range.start.row >= startRow - ) { - row = range.end.row; - try { - var fold = this.addFold("...", range); - if (fold) - fold.collapseChildren = depth; - } 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(); - var mode = this.$foldMode; - this.$setFolding(null); - this.$setFolding(mode); - }; - - this.$setFolding = function(foldMode) { - if (this.$foldMode == foldMode) - return; - - this.$foldMode = foldMode; - - this.off('change', this.$updateFoldWidgets); - this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); - this._signal("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.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this); - this.on('change', this.$updateFoldWidgets); - this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets); - }; - - this.getParentFoldRangeData = function (row, ignoreCurrent) { - var fw = this.foldWidgets; - if (!fw || (ignoreCurrent && fw[row])) - return {}; - - var i = row - 1, firstRange; - while (i >= 0) { - var c = fw[i]; - if (c == null) - c = fw[i] = this.getFoldWidget(i); - - if (c == "start") { - var range = this.getFoldWidgetRange(i); - if (!firstRange) - firstRange = range; - if (range && range.end.row >= row) - break; - } - i--; - } - - return { - range: i !== -1 && range, - firstRange: firstRange - }; - }; - - this.onFoldWidgetClick = function(row, e) { - e = e.domEvent; - var options = { - children: e.shiftKey, - all: e.ctrlKey || e.metaKey, - siblings: e.altKey - }; - - var range = this.$toggleFoldWidget(row, options); - if (!range) { - var el = (e.target || e.srcElement); - if (el && /ace_fold-widget/.test(el.className)) - el.className += " ace_invalid"; - } - }; - - this.$toggleFoldWidget = function(row, options) { - if (!this.getFoldWidget) - return; - var type = this.getFoldWidget(row); - var line = this.getLine(row); - - var dir = type === "end" ? -1 : 1; - var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir); - - if (fold) { - if (options.children || options.all) - this.removeFold(fold); - else - this.expandFold(fold); - return fold; - } - - var range = this.getFoldWidgetRange(row, true); - if (range && !range.isMultiLine()) { - fold = this.getFoldAt(range.start.row, range.start.column, 1); - if (fold && range.isEqual(fold.range)) { - this.removeFold(fold); - return fold; - } - } - - if (options.siblings) { - var data = this.getParentFoldRangeData(row); - if (data.range) { - var startRow = data.range.start.row + 1; - var endRow = data.range.end.row; - } - this.foldAll(startRow, endRow, options.all ? 10000 : 0); - } else if (options.children) { - endRow = range ? range.end.row : this.getLength(); - this.foldAll(row + 1, endRow, options.all ? 10000 : 0); - } else if (range) { - if (options.all) - range.collapseChildren = 10000; - this.addFold("...", range); - } - - return range; - }; - - - - this.toggleFoldWidget = function(toggleParent) { - var row = this.selection.getCursor().row; - row = this.getRowFoldStart(row); - var range = this.$toggleFoldWidget(row, {}); - - if (range) - return; - var data = this.getParentFoldRangeData(row, true); - range = data.range || data.firstRange; - - if (range) { - row = range.start.row; - var fold = this.getFoldAt(row, this.getLine(row).length, 1); - - if (fold) { - this.removeFold(fold); - } else { - this.addFold("...", range); - } - } - }; - - this.updateFoldWidgets = function(delta) { - var firstRow = delta.start.row; - var len = delta.end.row - firstRow; - - if (len === 0) { - this.foldWidgets[firstRow] = null; - } else if (delta.action == 'remove') { - this.foldWidgets.splice(firstRow, len + 1, null); - } else { - var args = Array(len + 1); - args.unshift(firstRow, 1); - this.foldWidgets.splice.apply(this.foldWidgets, args); - } - }; - this.tokenizerUpdateFoldWidgets = function(e) { - var rows = e.data; - if (rows.first != rows.last) { - if (this.foldWidgets.length > rows.first) - this.foldWidgets.splice(rows.first, this.foldWidgets.length); - } - }; -} - -exports.Folding = Folding; - -}); - -ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(acequire, exports, module) { -"use strict"; - -var TokenIterator = acequire("../token_iterator").TokenIterator; -var Range = acequire("../range").Range; - - -function BracketMatch() { - - this.findMatchingBracket = function(position, chr) { - if (position.column == 0) return null; - - var charBeforeCursor = chr || 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.getBracketRange = function(pos) { - var line = this.getLine(pos.row); - var before = true, range; - - var chr = line.charAt(pos.column-1); - var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); - if (!match) { - chr = line.charAt(pos.column); - pos = {row: pos.row, column: pos.column + 1}; - match = chr && chr.match(/([\(\[\{])|([\)\]\}])/); - before = false; - } - if (!match) - return null; - - if (match[1]) { - var bracketPos = this.$findClosingBracket(match[1], pos); - if (!bracketPos) - return null; - range = Range.fromPoints(pos, bracketPos); - if (!before) { - range.end.column++; - range.start.column--; - } - range.cursor = range.end; - } else { - var bracketPos = this.$findOpeningBracket(match[2], pos); - if (!bracketPos) - return null; - range = Range.fromPoints(bracketPos, pos); - if (!before) { - range.start.column++; - range.end.column--; - } - range.cursor = range.start; - } - - return range; - }; - - 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") - .replace(/\b(?:end)\b/, "(?:start|begin|end)") - + ")+" - ); - } - 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; - } - 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) { - 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") - .replace(/\b(?:start|begin)\b/, "(?:start|begin|end)") - + ")+" - ); - } - 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; - } - do { - token = iterator.stepForward(); - } while (token && !typeRe.test(token.type)); - - if (token == null) - break; - - valueIndex = 0; - } - - return null; - }; -} -exports.BracketMatch = BracketMatch; - -}); - -ace.define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/config","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(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var lang = acequire("./lib/lang"); -var config = acequire("./config"); -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var Selection = acequire("./selection").Selection; -var TextMode = acequire("./mode/text").Mode; -var Range = acequire("./range").Range; -var Document = acequire("./document").Document; -var BackgroundTokenizer = acequire("./background_tokenizer").BackgroundTokenizer; -var SearchHighlight = acequire("./search_highlight").SearchHighlight; - -var EditSession = function(text, mode) { - this.$breakpoints = []; - this.$decorations = []; - this.$frontMarkers = {}; - this.$backMarkers = {}; - this.$markerId = 1; - this.$undoSelect = true; - - this.$foldData = []; - this.id = "session" + (++EditSession.$uid); - this.$foldData.toString = function() { - return this.join("\n"); - }; - this.on("changeFold", this.onChangeFold.bind(this)); - this.$onChange = this.onChange.bind(this); - - if (typeof text != "object" || !text.getLine) - text = new Document(text); - - this.setDocument(text); - this.selection = new Selection(this); - - config.resetOptions(this); - this.setMode(mode); - config._signal("session", this); -}; - - -(function() { - - oop.implement(this, EventEmitter); - this.setDocument = function(doc) { - if (this.doc) - this.doc.removeListener("change", this.$onChange); - - this.doc = doc; - doc.on("change", this.$onChange); - - if (this.bgTokenizer) - this.bgTokenizer.setDocument(this.getDocument()); - - this.resetCaches(); - }; - this.getDocument = function() { - return this.doc; - }; - this.$resetRowCache = function(docRow) { - if (!docRow) { - this.$docRowCache = []; - this.$screenRowCache = []; - return; - } - var l = this.$docRowCache.length; - var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1; - if (l > i) { - 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 -1; - }; - - this.resetCaches = function() { - this.$modified = true; - this.$wrapData = []; - this.$rowLengthCache = []; - this.$resetRowCache(0); - if (this.bgTokenizer) - this.bgTokenizer.start(0); - }; - - this.onChangeFold = function(e) { - var fold = e.data; - this.$resetRowCache(fold.start.row); - }; - - this.onChange = function(delta) { - this.$modified = true; - - this.$resetRowCache(delta.start.row); - - var removedFolds = this.$updateInternalDataOnChange(delta); - 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 && this.bgTokenizer.$updateOnChange(delta); - this._signal("change", delta); - }; - this.setValue = function(text) { - this.doc.setValue(text); - this.selection.moveTo(0, 0); - - this.$resetRowCache(0); - this.$deltas = []; - this.$deltasDoc = []; - this.$deltasFold = []; - this.setUndoManager(this.$undoManager); - this.getUndoManager().reset(); - }; - 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.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], - merge: self.mergeUndoDeltas - }); - } - self.mergeUndoDeltas = false; - self.$deltas = []; - }; - this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager); - } - }; - this.markUndoGroup = function() { - if (this.$syncInformUndoManager) - this.$syncInformUndoManager(); - }; - - this.$defaultUndoManager = { - undo: function() {}, - redo: function() {}, - reset: function() {} - }; - this.getUndoManager = function() { - return this.$undoManager || this.$defaultUndoManager; - }; - this.getTabString = function() { - if (this.getUseSoftTabs()) { - return lang.stringRepeat(" ", this.getTabSize()); - } else { - return "\t"; - } - }; - this.setUseSoftTabs = function(val) { - this.setOption("useSoftTabs", val); - }; - this.getUseSoftTabs = function() { - return this.$useSoftTabs && !this.$mode.$indentWithTabs; - }; - this.setTabSize = function(tabSize) { - this.setOption("tabSize", tabSize); - }; - 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) { - this.setOption("overwrite", overwrite); - }; - this.getOverwrite = function() { - return this.$overwrite; - }; - this.toggleOverwrite = function() { - this.setOverwrite(!this.$overwrite); - }; - this.addGutterDecoration = function(row, className) { - if (!this.$decorations[row]) - this.$decorations[row] = ""; - this.$decorations[row] += " " + className; - this._signal("changeBreakpoint", {}); - }; - this.removeGutterDecoration = function(row, className) { - this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, ""); - this._signal("changeBreakpoint", {}); - }; - this.getBreakpoints = function() { - return this.$breakpoints; - }; - this.setBreakpoints = function(rows) { - this.$breakpoints = []; - for (var i=0; i 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.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); }; - this.getUseWorker = function() { return this.$useWorker; }; - this.onReloadTokenizer = function(e) { - var rows = e.data; - this.bgTokenizer.start(rows.first); - this._signal("tokenizerUpdate", e); - }; - - this.$modes = {}; - this.$mode = null; - this.$modeId = null; - this.setMode = function(mode, cb) { - if (mode && typeof mode === "object") { - if (mode.getTokenizer) - return this.$onChangeMode(mode); - var options = mode; - var path = options.path; - } else { - path = mode || "ace/mode/text"; - } - if (!this.$modes["ace/mode/text"]) - this.$modes["ace/mode/text"] = new TextMode(); - - if (this.$modes[path] && !options) { - this.$onChangeMode(this.$modes[path]); - cb && cb(); - return; - } - this.$modeId = path; - config.loadModule(["mode", path], function(m) { - if (this.$modeId !== path) - return cb && cb(); - if (this.$modes[path] && !options) { - this.$onChangeMode(this.$modes[path]); - } else if (m && m.Mode) { - m = new m.Mode(options); - if (!options) { - this.$modes[path] = m; - m.$id = path; - } - this.$onChangeMode(m); - } - cb && cb(); - }.bind(this)); - if (!this.$mode) - this.$onChangeMode(this.$modes["ace/mode/text"], true); - }; - - this.$onChangeMode = function(mode, $isPlaceholder) { - if (!$isPlaceholder) - this.$modeId = mode.$id; - if (this.$mode === mode) - return; - - this.$mode = mode; - - 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._signal("tokenizerUpdate", e); - }); - } else { - this.bgTokenizer.setTokenizer(tokenizer); - } - - this.bgTokenizer.setDocument(this.getDocument()); - - this.tokenRe = mode.tokenRe; - this.nonTokenRe = mode.nonTokenRe; - - - if (!$isPlaceholder) { - if (mode.attachToSession) - mode.attachToSession(this); - this.$options.wrapMethod.set.call(this, this.$wrapMethod); - this.$setFolding(mode.foldingRules); - this.bgTokenizer.start(0); - this._emit("changeMode"); - } - }; - - this.$stopWorker = function() { - if (this.$worker) { - this.$worker.terminate(); - this.$worker = null; - } - }; - - this.$startWorker = function() { - try { - this.$worker = this.$mode.createWorker(this); - } catch (e) { - config.warn("Could not load worker", e); - this.$worker = null; - } - }; - this.getMode = function() { - return this.$mode; - }; - - this.$scrollTop = 0; - this.setScrollTop = function(scrollTop) { - if (this.$scrollTop === scrollTop || isNaN(scrollTop)) - return; - - this.$scrollTop = scrollTop; - this._signal("changeScrollTop", scrollTop); - }; - this.getScrollTop = function() { - return this.$scrollTop; - }; - - this.$scrollLeft = 0; - this.setScrollLeft = function(scrollLeft) { - if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft)) - return; - - this.$scrollLeft = scrollLeft; - this._signal("changeScrollLeft", scrollLeft); - }; - this.getScrollLeft = function() { - return this.$scrollLeft; - }; - this.getScreenWidth = function() { - this.$computeWidth(); - if (this.lineWidgets) - return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth); - return this.screenWidth; - }; - - this.getLineWidgetMaxWidth = function() { - if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth; - var width = 0; - this.lineWidgets.forEach(function(w) { - if (w && w.screenWidth > width) - width = w.screenWidth; - }); - return this.lineWidgetWidth = width; - }; - - 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.removeFullLines = function(firstRow, lastRow){ - return this.doc.removeFullLines(firstRow, lastRow); - }; - 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) { - return isUndo ? delta.action !== "insert" : delta.action === "insert"; - } - - var delta = deltas[0]; - var range, point; - var lastDeltaIsInsert = false; - if (isInsert(delta)) { - range = Range.fromPoints(delta.start, delta.end); - lastDeltaIsInsert = true; - } else { - range = Range.fromPoints(delta.start, delta.start); - lastDeltaIsInsert = false; - } - - for (var i = 1; i < deltas.length; i++) { - delta = deltas[i]; - if (isInsert(delta)) { - point = delta.start; - if (range.compare(point.row, point.column) == -1) { - range.setStart(point); - } - point = delta.end; - if (range.compare(point.row, point.column) == 1) { - range.setEnd(point); - } - lastDeltaIsInsert = true; - } else { - point = delta.start; - if (range.compare(point.row, point.column) == -1) { - range = Range.fromPoints(delta.start, delta.start); - } - lastDeltaIsInsert = false; - } - } - if (lastUndoRange != null) { - if (Range.comparePoints(lastUndoRange.start, range.start) === 0) { - lastUndoRange.start.column += range.end.column - range.start.column; - lastUndoRange.end.column += range.end.column - range.start.column; - } - - var cmp = lastUndoRange.compareRange(range); - if (cmp == 1) { - range.setStart(lastUndoRange.start); - } else if (cmp == -1) { - range.setEnd(lastUndoRange.end); - } - } - - return range; - }; - this.replace = function(range, text) { - return this.doc.replace(range, text); - }; - this.moveText = function(fromRange, toPosition, copy) { - var text = this.getTextRange(fromRange); - var folds = this.getFoldsInRange(fromRange); - - var toRange = Range.fromPoints(toPosition, toPosition); - if (!copy) { - this.remove(fromRange); - var rowDiff = fromRange.start.row - fromRange.end.row; - var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column; - if (collDiff) { - if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column) - toRange.start.column += collDiff; - if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column) - toRange.end.column += collDiff; - } - if (rowDiff && toRange.start.row >= fromRange.end.row) { - toRange.start.row += rowDiff; - toRange.end.row += rowDiff; - } - } - - toRange.end = this.insert(toRange.start, text); - if (folds.length) { - var oldStart = fromRange.start; - var newStart = toRange.start; - var rowDiff = newStart.row - oldStart.row; - var collDiff = newStart.column - oldStart.column; - this.addFolds(folds.map(function(x) { - x = x.clone(); - if (x.start.row == oldStart.row) - x.start.column += collDiff; - if (x.end.row == oldStart.row) - x.end.column += collDiff; - x.start.row += rowDiff; - x.end.row += rowDiff; - return x; - })); - } - - return toRange; - }; - this.indentRows = function(startRow, endRow, indentString) { - indentString = indentString.replace(/\t/g, this.getTabString()); - for (var row=startRow; row<=endRow; row++) - this.doc.insertInLine({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.$moveLines = function(firstRow, lastRow, dir) { - firstRow = this.getRowFoldStart(firstRow); - lastRow = this.getRowFoldEnd(lastRow); - if (dir < 0) { - var row = this.getRowFoldStart(firstRow + dir); - if (row < 0) return 0; - var diff = row-firstRow; - } else if (dir > 0) { - var row = this.getRowFoldEnd(lastRow + dir); - if (row > this.doc.getLength()-1) return 0; - var diff = row-lastRow; - } else { - firstRow = this.$clipRowToDocument(firstRow); - lastRow = this.$clipRowToDocument(lastRow); - var diff = lastRow - firstRow + 1; - } - - var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE); - var folds = this.getFoldsInRange(range).map(function(x){ - x = x.clone(); - x.start.row += diff; - x.end.row += diff; - return x; - }); - - var lines = dir == 0 - ? this.doc.getLines(firstRow, lastRow) - : this.doc.removeFullLines(firstRow, lastRow); - this.doc.insertFullLines(firstRow+diff, lines); - folds.length && this.addFolds(folds); - return diff; - }; - this.moveLinesUp = function(firstRow, lastRow) { - return this.$moveLines(firstRow, lastRow, -1); - }; - this.moveLinesDown = function(firstRow, lastRow) { - return this.$moveLines(firstRow, lastRow, 1); - }; - this.duplicateLines = function(firstRow, lastRow) { - return this.$moveLines(firstRow, lastRow, 0); - }; - - - 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; - }; - 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 (useWrapMode) { - var len = this.getLength(); - this.$wrapData = Array(len); - this.$updateWrapData(0, len - 1); - } - - this._signal("changeWrapMode"); - } - }; - this.getUseWrapMode = function() { - return this.$useWrapMode; - }; - this.setWrapLimitRange = function(min, max) { - if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) { - this.$wrapLimitRange = { min: min, max: max }; - this.$modified = true; - if (this.$useWrapMode) - this._signal("changeWrapMode"); - } - }; - this.adjustWrapLimit = function(desiredLimit, $printMargin) { - var limits = this.$wrapLimitRange; - if (limits.max < 0) - limits = {min: $printMargin, max: $printMargin}; - var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max); - if (wrapLimit != this.$wrapLimit && wrapLimit > 1) { - this.$wrapLimit = wrapLimit; - this.$modified = true; - if (this.$useWrapMode) { - this.$updateWrapData(0, this.getLength() - 1); - this.$resetRowCache(0); - this._signal("changeWrapLimit"); - } - return true; - } - return false; - }; - - this.$constrainWrapLimit = function(wrapLimit, min, max) { - if (min) - wrapLimit = Math.max(min, wrapLimit); - - if (max) - wrapLimit = Math.min(max, wrapLimit); - - return wrapLimit; - }; - this.getWrapLimit = function() { - return this.$wrapLimit; - }; - this.setWrapLimit = function (limit) { - this.setWrapLimitRange(limit, limit); - }; - this.getWrapLimitRange = function() { - return { - min : this.$wrapLimitRange.min, - max : this.$wrapLimitRange.max - }; - }; - - this.$updateInternalDataOnChange = function(delta) { - var useWrapMode = this.$useWrapMode; - var action = delta.action; - var start = delta.start; - var end = delta.end; - var firstRow = start.row; - var lastRow = end.row; - var len = lastRow - firstRow; - var removedFolds = null; - - this.$updating = true; - if (len != 0) { - if (action === "remove") { - this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len); - - var foldLines = this.$foldData; - removedFolds = this.getFoldsInRange(delta); - 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 = Array(len); - args.unshift(firstRow, 0); - var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache - arr.splice.apply(arr, args); - var foldLines = this.$foldData; - var foldLine = this.getFoldLine(firstRow); - var idx = 0; - if (foldLine) { - var cmp = foldLine.range.compareInside(start.row, start.column); - if (cmp == 0) { - foldLine = foldLine.split(start.row, start.column); - if (foldLine) { - foldLine.shiftRow(len); - foldLine.addRemoveChars(lastRow, 0, end.column - start.column); - } - } else - if (cmp == -1) { - foldLine.addRemoveChars(firstRow, 0, end.column - start.column); - foldLine.shiftRow(len); - } - idx = foldLines.indexOf(foldLine) + 1; - } - - for (idx; idx < foldLines.length; idx++) { - var foldLine = foldLines[idx]; - if (foldLine.start.row >= firstRow) { - foldLine.shiftRow(len); - } - } - } - } else { - len = Math.abs(delta.start.column - delta.end.column); - if (action === "remove") { - removedFolds = this.getFoldsInRange(delta); - 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!"); - } - this.$updating = false; - - if (useWrapMode) - this.$updateWrapData(firstRow, lastRow); - else - this.$updateRowLengthCache(firstRow, lastRow); - - return removedFolds; - }; - - this.$updateRowLengthCache = function(firstRow, lastRow, b) { - this.$rowLengthCache[firstRow] = null; - this.$rowLengthCache[lastRow] = null; - }; - - 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(lines[row]); - wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); - row ++; - } else { - tokens = []; - foldLine.walk(function(placeholder, row, column, lastColumn) { - var walkTokens; - if (placeholder != null) { - 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 - ); - - wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize); - row = foldLine.end.row + 1; - } - } - }; - 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, tabSize) { - if (tokens.length == 0) { - return []; - } - - var splits = []; - var displayLength = tokens.length; - var lastSplit = 0, lastDocSplit = 0; - - var isCode = this.$wrapAsCode; - - var indentedSoftWrap = this.$indentedSoftWrap; - var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8) - || indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2); - - function getWrapIndent() { - var indentation = 0; - if (maxIndent === 0) - return indentation; - if (indentedSoftWrap) { - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - if (token == SPACE) - indentation += 1; - else if (token == TAB) - indentation += tabSize; - else if (token == TAB_SPACE) - continue; - else - break; - } - } - if (isCode && indentedSoftWrap !== false) - indentation += tabSize; - return Math.min(indentation, maxIndent); - } - function addSplit(screenPos) { - var displayed = tokens.slice(lastSplit, screenPos); - var len = displayed.length; - displayed.join("") - .replace(/12/g, function() { - len -= 1; - }) - .replace(/2/g, function() { - len -= 1; - }); - - if (!splits.length) { - indent = getWrapIndent(); - splits.indent = indent; - } - lastDocSplit += len; - splits.push(lastDocSplit); - lastSplit = screenPos; - } - var indent = 0; - while (displayLength - lastSplit > wrapLimit - indent) { - var split = lastSplit + wrapLimit - indent; - if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) { - addSplit(split); - continue; - } - if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) { - for (split; split != lastSplit - 1; split--) { - if (tokens[split] == PLACEHOLDER_START) { - break; - } - } - if (split > lastSplit) { - addSplit(split); - continue; - } - split = lastSplit + wrapLimit; - for (split; split < tokens.length; split++) { - if (tokens[split] != PLACEHOLDER_BODY) { - break; - } - } - if (split == tokens.length) { - break; // Breaks the while-loop. - } - addSplit(split); - continue; - } - var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1); - while (split > minSplit && tokens[split] < PLACEHOLDER_START) { - split --; - } - if (isCode) { - while (split > minSplit && tokens[split] < PLACEHOLDER_START) { - split --; - } - while (split > minSplit && tokens[split] == PUNCTUATION) { - split --; - } - } else { - while (split > minSplit && tokens[split] < SPACE) { - split --; - } - } - if (split > minSplit) { - addSplit(++split); - continue; - } - split = lastSplit + wrapLimit; - if (tokens[split] == CHAR_EXT) - split--; - addSplit(split - indent); - } - return splits; - }; - 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); - if (c == 9) { - tabSize = this.getScreenTabSize(arr.length + offset); - arr.push(TAB); - for (var n = 1; n < tabSize; n++) { - arr.push(TAB_SPACE); - } - } - else if (c == 32) { - arr.push(SPACE); - } else if((c > 39 && c < 48) || (c > 57 && c < 64)) { - arr.push(PUNCTUATION); - } - else if (c >= 0x1100 && isFullWidth(c)) { - arr.push(CHAR, CHAR_EXT); - } else { - arr.push(CHAR); - } - } - return arr; - }; - 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); - if (c == 9) { - screenColumn += this.getScreenTabSize(screenColumn); - } - else if (c >= 0x1100 && isFullWidth(c)) { - screenColumn += 2; - } else { - screenColumn += 1; - } - if (screenColumn > maxScreenColumn) { - break; - } - } - - return [screenColumn, column]; - }; - - this.lineWidgets = null; - this.getRowLength = function(row) { - if (this.lineWidgets) - var h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; - else - h = 0 - if (!this.$useWrapMode || !this.$wrapData[row]) { - return 1 + h; - } else { - return this.$wrapData[row].length + 1 + h; - } - }; - this.getRowLineCount = function(row) { - if (!this.$useWrapMode || !this.$wrapData[row]) { - return 1; - } else { - return this.$wrapData[row].length + 1; - } - }; - - this.getRowWrapIndent = function(screenRow) { - if (this.$useWrapMode) { - var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE); - var splits = this.$wrapData[pos.row]; - return splits.length && splits[0] < pos.column ? splits.indent : 0; - } else { - return 0; - } - } - 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 l = rowCache.length; - if (l && i >= 0) { - var row = rowCache[i]; - var docRow = this.$docRowCache[i]; - var doCache = screenRow > rowCache[l - 1]; - } else { - var doCache = !l; - } - - 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 > 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) { - return { - row: maxRow, - column: this.getLine(maxRow).length - }; - } else { - line = this.getLine(docRow); - foldLine = null; - } - var wrapIndent = 0; - if (this.$useWrapMode) { - var splits = this.$wrapData[docRow]; - if (splits) { - var splitIndex = Math.floor(screenRow - row); - column = splits[splitIndex]; - if(splitIndex > 0 && splits.length) { - wrapIndent = splits.indent; - docColumn = splits[splitIndex - 1] || splits[splits.length - 1]; - line = line.substring(docColumn); - } - } - } - - docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1]; - if (this.$useWrapMode && docColumn >= column) - docColumn = column - 1; - - if (foldLine) - return foldLine.idxToPosition(docColumn); - - return {row: docRow, column: docColumn}; - }; - this.documentToScreenPosition = function(docRow, docColumn) { - 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; - 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); - var l = rowCache.length; - if (l && i >= 0) { - var row = rowCache[i]; - var screenRow = this.$screenRowCache[i]; - var doCache = docRow > rowCache[l - 1]; - } else { - var doCache = !l; - } - - 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); - } - } - var textLine = ""; - if (foldLine && row >= foldStart) { - textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn); - foldStartRow = foldLine.start.row; - } else { - textLine = this.getLine(docRow).substring(0, docColumn); - foldStartRow = docRow; - } - var wrapIndent = 0; - if (this.$useWrapMode) { - var wrapRow = this.$wrapData[foldStartRow]; - if (wrapRow) { - var screenRowOffset = 0; - while (textLine.length >= wrapRow[screenRowOffset]) { - screenRow ++; - screenRowOffset++; - } - textLine = textLine.substring( - wrapRow[screenRowOffset - 1] || 0, textLine.length - ); - wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0; - } - } - - return { - row: screenRow, - column: wrapIndent + 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(); - 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) { - var splits = this.$wrapData[row]; - screenRows += splits ? splits.length + 1 : 1; - row ++; - if (row > foldStart) { - row = fold.end.row+1; - fold = this.$foldData[i++]; - foldStart = fold ?fold.start.row :Infinity; - } - } - } - if (this.lineWidgets) - screenRows += this.$getWidgetScreenLength(); - - return screenRows; - }; - this.$setFontMetrics = function(fm) { - if (!this.$enableVarChar) return; - this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) { - if (maxScreenColumn === 0) - return [0, 0]; - if (!maxScreenColumn) - maxScreenColumn = Infinity; - screenColumn = screenColumn || 0; - - var c, column; - for (column = 0; column < str.length; column++) { - c = str.charAt(column); - if (c === "\t") { - screenColumn += this.getScreenTabSize(screenColumn); - } else { - screenColumn += fm.getCharacterWidth(c); - } - if (screenColumn > maxScreenColumn) { - break; - } - } - - return [screenColumn, column]; - }; - }; - - this.destroy = function() { - if (this.bgTokenizer) { - this.bgTokenizer.setDocument(null); - this.bgTokenizer = null; - } - this.$stopWorker(); - }; - 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); - -acequire("./edit_session/folding").Folding.call(EditSession.prototype); -acequire("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype); - - -config.defineOptions(EditSession.prototype, "session", { - wrap: { - set: function(value) { - if (!value || value == "off") - value = false; - else if (value == "free") - value = true; - else if (value == "printMargin") - value = -1; - else if (typeof value == "string") - value = parseInt(value, 10) || false; - - if (this.$wrap == value) - return; - this.$wrap = value; - if (!value) { - this.setUseWrapMode(false); - } else { - var col = typeof value == "number" ? value : null; - this.setWrapLimitRange(col, col); - this.setUseWrapMode(true); - } - }, - get: function() { - if (this.getUseWrapMode()) { - if (this.$wrap == -1) - return "printMargin"; - if (!this.getWrapLimitRange().min) - return "free"; - return this.$wrap; - } - return "off"; - }, - handlesSet: true - }, - wrapMethod: { - set: function(val) { - val = val == "auto" - ? this.$mode.type != "text" - : val != "text"; - if (val != this.$wrapAsCode) { - this.$wrapAsCode = val; - if (this.$useWrapMode) { - this.$modified = true; - this.$resetRowCache(0); - this.$updateWrapData(0, this.getLength() - 1); - } - } - }, - initialValue: "auto" - }, - indentedSoftWrap: { initialValue: true }, - firstLineNumber: { - set: function() {this._signal("changeBreakpoint");}, - initialValue: 1 - }, - useWorker: { - set: function(useWorker) { - this.$useWorker = useWorker; - - this.$stopWorker(); - if (useWorker) - this.$startWorker(); - }, - initialValue: true - }, - useSoftTabs: {initialValue: true}, - tabSize: { - set: function(tabSize) { - if (isNaN(tabSize) || this.$tabSize === tabSize) return; - - this.$modified = true; - this.$rowLengthCache = []; - this.$tabSize = tabSize; - this._signal("changeTabSize"); - }, - initialValue: 4, - handlesSet: true - }, - overwrite: { - set: function(val) {this._signal("changeOverwrite");}, - initialValue: false - }, - newLineMode: { - set: function(val) {this.doc.setNewLineMode(val)}, - get: function() {return this.doc.getNewLineMode()}, - handlesSet: true - }, - mode: { - set: function(val) { this.setMode(val) }, - get: function() { return this.$modeId } - } -}); - -exports.EditSession = EditSession; -}); - -ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) { -"use strict"; - -var lang = acequire("./lib/lang"); -var oop = acequire("./lib/oop"); -var Range = acequire("./range").Range; - -var Search = function() { - this.$options = {}; -}; - -(function() { - 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 options = this.$options; - var iterator = this.$matchIterator(session, 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); - if (!range.length && options.start && options.start.start - && options.skipCurrent != false && firstRange.isEqual(options.start) - ) { - firstRange = null; - return false; - } - } else - firstRange = range; - return true; - }); - - return firstRange; - }; - this.findAll = function(session) { - var options = this.$options; - if (!options.needle) - return []; - this.$assembleRegExp(options); - - var range = options.range; - var lines = range - ? session.getLines(range.start.row, range.end.row) - : session.doc.getAllLines(); - - var ranges = []; - var re = options.re; - if (options.$isMultiLine) { - var len = re.length; - var maxRow = lines.length - len; - var prevRange; - outer: for (var row = re.offset || 0; row <= maxRow; row++) { - for (var j = 0; j < len; j++) - if (lines[row + j].search(re[j]) == -1) - continue outer; - - var startLine = lines[row]; - var line = lines[row + len - 1]; - var startIndex = startLine.length - startLine.match(re[0])[0].length; - var endIndex = line.match(re[len - 1])[0].length; - - if (prevRange && prevRange.end.row === row && - prevRange.end.column > startIndex - ) { - continue; - } - ranges.push(prevRange = new Range( - row, startIndex, row + len - 1, endIndex - )); - if (len > 2) - row = row + len - 2; - } - } 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 (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--; - - ranges = ranges.slice(i, j + 1); - for (i = 0, j = ranges.length; i < j; i++) { - ranges[i].start.row += range.start.row; - ranges[i].end.row += range.start.row; - } - } - - 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 callback; - 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 (options.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; - }; - } - - var lineIterator = this.$lineIterator(session, options); - - return { - forEach: function(_callback) { - callback = _callback; - lineIterator.forEach(matchIterator); - } - }; - }; - - this.$assembleRegExp = function(options, $disableFakeMultiline) { - 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 = addWordBoundary(needle, options); - - var modifier = options.caseSensitive ? "gm" : "gmi"; - - options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle); - if (options.$isMultiLine) - return options.re = this.$assembleMultilineRegExp(needle, modifier); - - try { - var re = new RegExp(needle, modifier); - } catch(e) { - 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 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 lastRow = range ? range.end.row : session.getLength() - 1; - - var forEach = backwards ? 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; - } : 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; - }; - - return {forEach: forEach}; - }; - -}).call(Search.prototype); - -function addWordBoundary(needle, options) { - function wordBoundary(c) { - if (/\w/.test(c) || options.regExp) return "\\b"; - return ""; - } - return wordBoundary(needle[0]) + needle - + wordBoundary(needle[needle.length - 1]); -} - -exports.Search = Search; -}); - -ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) { -"use strict"; - -var keyUtil = acequire("../lib/keys"); -var useragent = acequire("../lib/useragent"); -var KEY_MODS = keyUtil.KEY_MODS; - -function HashHandler(config, platform) { - this.platform = platform || (useragent.isMac ? "mac" : "win"); - this.commands = {}; - this.commandKeyBinding = {}; - this.addCommands(config); - this.$singleCommand = true; -} - -function MultiHashHandler(config, platform) { - HashHandler.call(this, config, platform); - this.$singleCommand = false; -} - -MultiHashHandler.prototype = HashHandler.prototype; - -(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, keepCommand) { - var name = command && (typeof command === 'string' ? command : command.name); - command = this.commands[name]; - if (!keepCommand) - delete this.commands[name]; - var ckb = this.commandKeyBinding; - for (var keyId in ckb) { - var cmdGroup = ckb[keyId]; - if (cmdGroup == command) { - delete ckb[keyId]; - } else if (Array.isArray(cmdGroup)) { - var i = cmdGroup.indexOf(command); - if (i != -1) { - cmdGroup.splice(i, 1); - if (cmdGroup.length == 1) - ckb[keyId] = cmdGroup[0]; - } - } - } - }; - - this.bindKey = function(key, command, position) { - if (typeof key == "object" && key) { - if (position == undefined) - position = key.position; - key = key[this.platform]; - } - if (!key) - return; - if (typeof command == "function") - return this.addCommand({exec: command, bindKey: key, name: command.name || key}); - - key.split("|").forEach(function(keyPart) { - var chain = ""; - if (keyPart.indexOf(" ") != -1) { - var parts = keyPart.split(/\s+/); - keyPart = parts.pop(); - parts.forEach(function(keyPart) { - var binding = this.parseKeys(keyPart); - var id = KEY_MODS[binding.hashId] + binding.key; - chain += (chain ? " " : "") + id; - this._addCommandToBinding(chain, "chainKeys"); - }, this); - chain += " "; - } - var binding = this.parseKeys(keyPart); - var id = KEY_MODS[binding.hashId] + binding.key; - this._addCommandToBinding(chain + id, command, position); - }, this); - }; - - function getPosition(command) { - return typeof command == "object" && command.bindKey - && command.bindKey.position || 0; - } - this._addCommandToBinding = function(keyId, command, position) { - var ckb = this.commandKeyBinding, i; - if (!command) { - delete ckb[keyId]; - } else if (!ckb[keyId] || this.$singleCommand) { - ckb[keyId] = command; - } else { - if (!Array.isArray(ckb[keyId])) { - ckb[keyId] = [ckb[keyId]]; - } else if ((i = ckb[keyId].indexOf(command)) != -1) { - ckb[keyId].splice(i, 1); - } - - if (typeof position != "number") { - if (position || command.isDefault) - position = -100; - else - position = getPosition(command); - } - var commands = ckb[keyId]; - for (i = 0; i < commands.length; i++) { - var other = commands[i]; - var otherPos = getPosition(other); - if (otherPos > position) - break; - } - commands.splice(i, 0, command); - } - }; - - this.addCommands = function(commands) { - commands && Object.keys(commands).forEach(function(name) { - var command = commands[name]; - if (!command) - return; - - if (typeof command === "string") - return this.bindKey(command, name); - - if (typeof command === "function") - command = { exec: command }; - - if (typeof command !== "object") - return; - - 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) { - this.bindKey(command.bindKey, command); - }; - this.parseKeys = function(keys) { - var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x}); - var key = parts.pop(); - - var keyCode = keyUtil[key]; - if (keyUtil.FUNCTION_KEYS[keyCode]) - key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase(); - else if (!parts.length) - return {key: key, hashId: -1}; - else if (parts.length == 1 && parts[0] == "shift") - return {key: key.toUpperCase(), hashId: -1}; - - var hashId = 0; - for (var i = parts.length; i--;) { - var modifier = keyUtil.KEY_MODS[parts[i]]; - if (modifier == null) { - if (typeof console != "undefined") - console.error("invalid modifier " + parts[i] + " in " + keys); - return false; - } - hashId |= modifier; - } - return {key: key, hashId: hashId}; - }; - - this.findKeyCommand = function findKeyCommand(hashId, keyString) { - var key = KEY_MODS[hashId] + keyString; - return this.commandKeyBinding[key]; - }; - - this.handleKeyboard = function(data, hashId, keyString, keyCode) { - if (keyCode < 0) return; - var key = KEY_MODS[hashId] + keyString; - var command = this.commandKeyBinding[key]; - if (data.$keyChain) { - data.$keyChain += " " + key; - command = this.commandKeyBinding[data.$keyChain] || command; - } - - if (command) { - if (command == "chainKeys" || command[command.length - 1] == "chainKeys") { - data.$keyChain = data.$keyChain || key; - return {command: "null"}; - } - } - - if (data.$keyChain) { - if ((!hashId || hashId == 4) && keyString.length == 1) - data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input - else if (hashId == -1 || keyCode > 0) - data.$keyChain = ""; // reset keyChain - } - return {command: command}; - }; - - this.getStatusText = function(editor, data) { - return data.$keyChain || ""; - }; - -}).call(HashHandler.prototype); - -exports.HashHandler = HashHandler; -exports.MultiHashHandler = MultiHashHandler; -}); - -ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var MultiHashHandler = acequire("../keyboard/hash_handler").MultiHashHandler; -var EventEmitter = acequire("../lib/event_emitter").EventEmitter; - -var CommandManager = function(platform, commands) { - MultiHashHandler.call(this, commands, platform); - this.byName = this.commands; - this.setDefaultHandler("exec", function(e) { - return e.command.exec(e.editor, e.args || {}); - }); -}; - -oop.inherits(CommandManager, MultiHashHandler); - -(function() { - - oop.implement(this, EventEmitter); - - this.exec = function(command, editor, args) { - if (Array.isArray(command)) { - for (var i = command.length; i--; ) { - if (this.exec(command[i], editor, args)) return true; - } - return false; - } - - if (typeof command === "string") - command = this.commands[command]; - - if (!command) - return false; - - if (editor && editor.$readOnly && !command.readOnly) - return false; - - var e = {editor: editor, command: command, args: args}; - e.returnValue = this._emit("exec", e); - this._signal("afterExec", e); - - return e.returnValue === false ? false : true; - }; - - this.toggleRecording = function(editor) { - if (this.$inReplay) - return; - - editor && editor._emit("changeStatus"); - if (this.recording) { - this.macro.pop(); - this.removeEventListener("exec", this.$addCommandToMacro); - - if (!this.macro.length) - this.macro = this.oldMacro; - - return this.recording = false; - } - if (!this.$addCommandToMacro) { - this.$addCommandToMacro = function(e) { - this.macro.push([e.command, e.args]); - }.bind(this); - } - - this.oldMacro = this.macro; - this.macro = []; - this.on("exec", this.$addCommandToMacro); - return this.recording = true; - }; - - this.replay = function(editor) { - if (this.$inReplay || !this.macro) - return; - - if (this.recording) - return this.toggleRecording(editor); - - try { - this.$inReplay = true; - this.macro.forEach(function(x) { - if (typeof x == "string") - this.exec(x, editor); - else - this.exec(x[0], editor, x[1]); - }, this); - } finally { - this.$inReplay = false; - } - }; - - this.trimMacro = function(m) { - return m.map(function(x){ - if (typeof x[0] != "string") - x[0] = x[0].name; - if (!x[1]) - x = x[0]; - return x; - }); - }; - -}).call(CommandManager.prototype); - -exports.CommandManager = CommandManager; - -}); - -ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(acequire, exports, module) { -"use strict"; - -var lang = acequire("../lib/lang"); -var config = acequire("../config"); -var Range = acequire("../range").Range; - -function bindKey(win, mac) { - return {win: win, mac: mac}; -} -exports.commands = [{ - name: "showSettingsMenu", - bindKey: bindKey("Ctrl-,", "Command-,"), - exec: function(editor) { - config.loadModule("ace/ext/settings_menu", function(module) { - module.init(editor); - editor.showSettingsMenu(); - }); - }, - readOnly: true -}, { - name: "goToNextError", - bindKey: bindKey("Alt-E", "F4"), - exec: function(editor) { - config.loadModule("ace/ext/error_marker", function(module) { - module.showErrorMarker(editor, 1); - }); - }, - scrollIntoView: "animate", - readOnly: true -}, { - name: "goToPreviousError", - bindKey: bindKey("Alt-Shift-E", "Shift-F4"), - exec: function(editor) { - config.loadModule("ace/ext/error_marker", function(module) { - module.showErrorMarker(editor, -1); - }); - }, - scrollIntoView: "animate", - readOnly: true -}, { - 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|Ctrl-F1", "Command-Alt-L|Command-F1"), - exec: function(editor) { editor.session.toggleFold(false); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "unfold", - bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"), - exec: function(editor) { editor.session.toggleFold(true); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "toggleFoldWidget", - bindKey: bindKey("F2", "F2"), - exec: function(editor) { editor.session.toggleFoldWidget(); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "toggleParentFoldWidget", - bindKey: bindKey("Alt-F2", "Alt-F2"), - exec: function(editor) { editor.session.toggleFoldWidget(true); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "foldall", - bindKey: bindKey(null, "Ctrl-Command-Option-0"), - exec: function(editor) { editor.session.foldAll(); }, - scrollIntoView: "center", - readOnly: true -}, { - name: "foldOther", - bindKey: bindKey("Alt-0", "Command-Option-0"), - exec: function(editor) { - editor.session.foldAll(); - editor.session.unfold(editor.selection.getAllRanges()); - }, - scrollIntoView: "center", - readOnly: true -}, { - name: "unfoldall", - bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"), - exec: function(editor) { editor.session.unfold(); }, - scrollIntoView: "center", - readOnly: true -}, { - name: "findnext", - bindKey: bindKey("Ctrl-K", "Command-G"), - exec: function(editor) { editor.findNext(); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "findprevious", - bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"), - exec: function(editor) { editor.findPrevious(); }, - multiSelectAction: "forEach", - scrollIntoView: "center", - readOnly: true -}, { - name: "selectOrFindNext", - bindKey: bindKey("Alt-K", "Ctrl-G"), - exec: function(editor) { - if (editor.selection.isEmpty()) - editor.selection.selectWord(); - else - editor.findNext(); - }, - readOnly: true -}, { - name: "selectOrFindPrevious", - bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"), - exec: function(editor) { - if (editor.selection.isEmpty()) - editor.selection.selectWord(); - else - editor.findPrevious(); - }, - readOnly: true -}, { - name: "find", - bindKey: bindKey("Ctrl-F", "Command-F"), - exec: function(editor) { - config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor)}); - }, - readOnly: true -}, { - name: "overwrite", - bindKey: "Insert", - exec: function(editor) { editor.toggleOverwrite(); }, - readOnly: true -}, { - name: "selecttostart", - bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Home|Command-Shift-Up"), - exec: function(editor) { editor.getSelection().selectFileStart(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "gotostart", - bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"), - exec: function(editor) { editor.navigateFileStart(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "selectup", - bindKey: bindKey("Shift-Up", "Shift-Up|Ctrl-Shift-P"), - exec: function(editor) { editor.getSelection().selectUp(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "golineup", - bindKey: bindKey("Up", "Up|Ctrl-P"), - exec: function(editor, args) { editor.navigateUp(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selecttoend", - bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-End|Command-Shift-Down"), - exec: function(editor) { editor.getSelection().selectFileEnd(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "gotoend", - bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"), - exec: function(editor) { editor.navigateFileEnd(); }, - multiSelectAction: "forEach", - readOnly: true, - scrollIntoView: "animate", - aceCommandGroup: "fileJump" -}, { - name: "selectdown", - bindKey: bindKey("Shift-Down", "Shift-Down|Ctrl-Shift-N"), - exec: function(editor) { editor.getSelection().selectDown(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "golinedown", - bindKey: bindKey("Down", "Down|Ctrl-N"), - exec: function(editor, args) { editor.navigateDown(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectwordleft", - bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"), - exec: function(editor) { editor.getSelection().selectWordLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotowordleft", - bindKey: bindKey("Ctrl-Left", "Option-Left"), - exec: function(editor) { editor.navigateWordLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selecttolinestart", - bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left|Ctrl-Shift-A"), - exec: function(editor) { editor.getSelection().selectLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotolinestart", - bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"), - exec: function(editor) { editor.navigateLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectleft", - bindKey: bindKey("Shift-Left", "Shift-Left|Ctrl-Shift-B"), - exec: function(editor) { editor.getSelection().selectLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotoleft", - bindKey: bindKey("Left", "Left|Ctrl-B"), - exec: function(editor, args) { editor.navigateLeft(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectwordright", - bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"), - exec: function(editor) { editor.getSelection().selectWordRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotowordright", - bindKey: bindKey("Ctrl-Right", "Option-Right"), - exec: function(editor) { editor.navigateWordRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selecttolineend", - bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right|Shift-End|Ctrl-Shift-E"), - exec: function(editor) { editor.getSelection().selectLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotolineend", - bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"), - exec: function(editor) { editor.navigateLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectright", - bindKey: bindKey("Shift-Right", "Shift-Right"), - exec: function(editor) { editor.getSelection().selectRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "gotoright", - bindKey: bindKey("Right", "Right|Ctrl-F"), - exec: function(editor, args) { editor.navigateRight(args.times); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectpagedown", - bindKey: "Shift-PageDown", - exec: function(editor) { editor.selectPageDown(); }, - readOnly: true -}, { - name: "pagedown", - bindKey: bindKey(null, "Option-PageDown"), - exec: function(editor) { editor.scrollPageDown(); }, - readOnly: true -}, { - name: "gotopagedown", - bindKey: bindKey("PageDown", "PageDown|Ctrl-V"), - exec: function(editor) { editor.gotoPageDown(); }, - readOnly: true -}, { - name: "selectpageup", - bindKey: "Shift-PageUp", - exec: function(editor) { editor.selectPageUp(); }, - readOnly: true -}, { - name: "pageup", - bindKey: bindKey(null, "Option-PageUp"), - exec: function(editor) { editor.scrollPageUp(); }, - readOnly: true -}, { - name: "gotopageup", - bindKey: "PageUp", - exec: function(editor) { editor.gotoPageUp(); }, - readOnly: true -}, { - name: "scrollup", - bindKey: bindKey("Ctrl-Up", null), - exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); }, - readOnly: true -}, { - name: "scrolldown", - bindKey: bindKey("Ctrl-Down", null), - exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); }, - readOnly: true -}, { - name: "selectlinestart", - bindKey: "Shift-Home", - exec: function(editor) { editor.getSelection().selectLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectlineend", - bindKey: "Shift-End", - exec: function(editor) { editor.getSelection().selectLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "togglerecording", - bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"), - exec: function(editor) { editor.commands.toggleRecording(editor); }, - 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-P", "Ctrl-P"), - exec: function(editor) { editor.jumpToMatching(); }, - multiSelectAction: "forEach", - scrollIntoView: "animate", - readOnly: true -}, { - name: "selecttomatching", - bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"), - exec: function(editor) { editor.jumpToMatching(true); }, - multiSelectAction: "forEach", - scrollIntoView: "animate", - readOnly: true -}, { - name: "expandToMatching", - bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"), - exec: function(editor) { editor.jumpToMatching(true, true); }, - multiSelectAction: "forEach", - scrollIntoView: "animate", - readOnly: true -}, { - name: "passKeysToBrowser", - bindKey: bindKey(null, null), - exec: function() {}, - passEvent: true, - readOnly: true -}, { - name: "copy", - exec: function(editor) { - }, - readOnly: true -}, -{ - name: "cut", - exec: function(editor) { - var range = editor.getSelectionRange(); - editor._emit("cut", range); - - if (!editor.selection.isEmpty()) { - editor.session.remove(range); - editor.clearSelection(); - } - }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "paste", - exec: function(editor, args) { - editor.$handlePaste(args); - }, - scrollIntoView: "cursor" -}, { - name: "removeline", - bindKey: bindKey("Ctrl-D", "Command-D"), - exec: function(editor) { editor.removeLines(); }, - scrollIntoView: "cursor", - multiSelectAction: "forEachLine" -}, { - name: "duplicateSelection", - bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"), - exec: function(editor) { editor.duplicateSelection(); }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "sortlines", - bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"), - exec: function(editor) { editor.sortLines(); }, - scrollIntoView: "selection", - multiSelectAction: "forEachLine" -}, { - name: "togglecomment", - bindKey: bindKey("Ctrl-/", "Command-/"), - exec: function(editor) { editor.toggleCommentLines(); }, - multiSelectAction: "forEachLine", - scrollIntoView: "selectionPart" -}, { - name: "toggleBlockComment", - bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"), - exec: function(editor) { editor.toggleBlockComment(); }, - multiSelectAction: "forEach", - scrollIntoView: "selectionPart" -}, { - name: "modifyNumberUp", - bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"), - exec: function(editor) { editor.modifyNumber(1); }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "modifyNumberDown", - bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"), - exec: function(editor) { editor.modifyNumber(-1); }, - scrollIntoView: "cursor", - multiSelectAction: "forEach" -}, { - name: "replace", - bindKey: bindKey("Ctrl-H", "Command-Option-F"), - exec: function(editor) { - config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true)}); - } -}, { - 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("Alt-Shift-Up", "Command-Option-Up"), - exec: function(editor) { editor.copyLinesUp(); }, - scrollIntoView: "cursor" -}, { - name: "movelinesup", - bindKey: bindKey("Alt-Up", "Option-Up"), - exec: function(editor) { editor.moveLinesUp(); }, - scrollIntoView: "cursor" -}, { - name: "copylinesdown", - bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"), - exec: function(editor) { editor.copyLinesDown(); }, - scrollIntoView: "cursor" -}, { - name: "movelinesdown", - bindKey: bindKey("Alt-Down", "Option-Down"), - exec: function(editor) { editor.moveLinesDown(); }, - scrollIntoView: "cursor" -}, { - name: "del", - bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"), - exec: function(editor) { editor.remove("right"); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "backspace", - bindKey: bindKey( - "Shift-Backspace|Backspace", - "Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H" - ), - exec: function(editor) { editor.remove("left"); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "cut_or_delete", - bindKey: bindKey("Shift-Delete", null), - exec: function(editor) { - if (editor.selection.isEmpty()) { - editor.remove("left"); - } else { - return false; - } - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolinestart", - bindKey: bindKey("Alt-Backspace", "Command-Backspace"), - exec: function(editor) { editor.removeToLineStart(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removetolineend", - bindKey: bindKey("Alt-Delete", "Ctrl-K"), - exec: function(editor) { editor.removeToLineEnd(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removewordleft", - bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"), - exec: function(editor) { editor.removeWordLeft(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "removewordright", - bindKey: bindKey("Ctrl-Delete", "Alt-Delete"), - exec: function(editor) { editor.removeWordRight(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "outdent", - bindKey: bindKey("Shift-Tab", "Shift-Tab"), - exec: function(editor) { editor.blockOutdent(); }, - multiSelectAction: "forEach", - scrollIntoView: "selectionPart" -}, { - name: "indent", - bindKey: bindKey("Tab", "Tab"), - exec: function(editor) { editor.indent(); }, - multiSelectAction: "forEach", - scrollIntoView: "selectionPart" -}, { - name: "blockoutdent", - bindKey: bindKey("Ctrl-[", "Ctrl-["), - exec: function(editor) { editor.blockOutdent(); }, - multiSelectAction: "forEachLine", - scrollIntoView: "selectionPart" -}, { - name: "blockindent", - bindKey: bindKey("Ctrl-]", "Ctrl-]"), - exec: function(editor) { editor.blockIndent(); }, - multiSelectAction: "forEachLine", - scrollIntoView: "selectionPart" -}, { - name: "insertstring", - exec: function(editor, str) { editor.insert(str); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "inserttext", - exec: function(editor, args) { - editor.insert(lang.stringRepeat(args.text || "", args.times || 1)); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "splitline", - bindKey: bindKey(null, "Ctrl-O"), - exec: function(editor) { editor.splitLine(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "transposeletters", - bindKey: bindKey("Ctrl-T", "Ctrl-T"), - exec: function(editor) { editor.transposeLetters(); }, - multiSelectAction: function(editor) {editor.transposeSelections(1); }, - scrollIntoView: "cursor" -}, { - name: "touppercase", - bindKey: bindKey("Ctrl-U", "Ctrl-U"), - exec: function(editor) { editor.toUpperCase(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "tolowercase", - bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"), - exec: function(editor) { editor.toLowerCase(); }, - multiSelectAction: "forEach", - scrollIntoView: "cursor" -}, { - name: "expandtoline", - bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"), - exec: function(editor) { - var range = editor.selection.getRange(); - - range.start.column = range.end.column = 0; - range.end.row++; - editor.selection.setRange(range, false); - }, - multiSelectAction: "forEach", - scrollIntoView: "cursor", - readOnly: true -}, { - name: "joinlines", - bindKey: bindKey(null, null), - exec: function(editor) { - var isBackwards = editor.selection.isBackwards(); - var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor(); - var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead(); - var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length; - var selectedText = editor.session.doc.getTextRange(editor.selection.getRange()); - var selectedCount = selectedText.replace(/\n\s*/, " ").length; - var insertLine = editor.session.doc.getLine(selectionStart.row); - - for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) { - var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i))); - if (curLine.length !== 0) { - curLine = " " + curLine; - } - insertLine += curLine; - } - - if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) { - insertLine += editor.session.doc.getNewLineCharacter(); - } - - editor.clearSelection(); - editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine); - - if (selectedCount > 0) { - editor.selection.moveCursorTo(selectionStart.row, selectionStart.column); - editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount); - } else { - firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol; - editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol); - } - }, - multiSelectAction: "forEach", - readOnly: true -}, { - name: "invertSelection", - bindKey: bindKey(null, null), - exec: function(editor) { - var endRow = editor.session.doc.getLength() - 1; - var endCol = editor.session.doc.getLine(endRow).length; - var ranges = editor.selection.rangeList.ranges; - var newRanges = []; - if (ranges.length < 1) { - ranges = [editor.selection.getRange()]; - } - - for (var i = 0; i < ranges.length; i++) { - if (i == (ranges.length - 1)) { - if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) { - newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol)); - } - } - - if (i === 0) { - if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) { - newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column)); - } - } else { - newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column)); - } - } - - editor.exitMultiSelectMode(); - editor.clearSelection(); - - for(var i = 0; i < newRanges.length; i++) { - editor.selection.addRange(newRanges[i], false); - } - }, - readOnly: true, - scrollIntoView: "none" -}]; - -}); - -ace.define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","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","ace/config","ace/token_iterator"], function(acequire, exports, module) { -"use strict"; - -acequire("./lib/fixoldbrowsers"); - -var oop = acequire("./lib/oop"); -var dom = acequire("./lib/dom"); -var lang = acequire("./lib/lang"); -var useragent = acequire("./lib/useragent"); -var TextInput = acequire("./keyboard/textinput").TextInput; -var MouseHandler = acequire("./mouse/mouse_handler").MouseHandler; -var FoldHandler = acequire("./mouse/fold_handler").FoldHandler; -var KeyBinding = acequire("./keyboard/keybinding").KeyBinding; -var EditSession = acequire("./edit_session").EditSession; -var Search = acequire("./search").Search; -var Range = acequire("./range").Range; -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var CommandManager = acequire("./commands/command_manager").CommandManager; -var defaultCommands = acequire("./commands/default_commands").commands; -var config = acequire("./config"); -var TokenIterator = acequire("./token_iterator").TokenIterator; -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); - this.$mouseHandler = new MouseHandler(this); - new FoldHandler(this); - - this.$blockScrolling = 0; - this.$search = new Search().set({ - wrap: true - }); - - this.$historyTracker = this.$historyTracker.bind(this); - this.commands.on("exec", this.$historyTracker); - - this.$initOperationListeners(); - - this._$emitInputEvent = lang.delayedCall(function() { - this._signal("input", {}); - if (this.session && this.session.bgTokenizer) - this.session.bgTokenizer.scheduleStart(); - }.bind(this)); - - this.on("change", function(_, _self) { - _self._$emitInputEvent.schedule(31); - }); - - this.setSession(session || new EditSession("")); - config.resetOptions(this); - config._signal("editor", this); -}; - -(function(){ - - oop.implement(this, EventEmitter); - - this.$initOperationListeners = function() { - function last(a) {return a[a.length - 1]} - - this.selections = []; - this.commands.on("exec", this.startOperation.bind(this), true); - this.commands.on("afterExec", this.endOperation.bind(this), true); - - this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this)); - - this.on("change", function() { - this.curOp || this.startOperation(); - this.curOp.docChanged = true; - }.bind(this), true); - - this.on("changeSelection", function() { - this.curOp || this.startOperation(); - this.curOp.selectionChanged = true; - }.bind(this), true); - }; - - this.curOp = null; - this.prevOp = {}; - this.startOperation = function(commadEvent) { - if (this.curOp) { - if (!commadEvent || this.curOp.command) - return; - this.prevOp = this.curOp; - } - if (!commadEvent) { - this.previousCommand = null; - commadEvent = {}; - } - - this.$opResetTimer.schedule(); - this.curOp = { - command: commadEvent.command || {}, - args: commadEvent.args, - scrollTop: this.renderer.scrollTop - }; - if (this.curOp.command.name && this.curOp.command.scrollIntoView !== undefined) - this.$blockScrolling++; - }; - - this.endOperation = function(e) { - if (this.curOp) { - if (e && e.returnValue === false) - return this.curOp = null; - this._signal("beforeEndOperation"); - var command = this.curOp.command; - if (command.name && this.$blockScrolling > 0) - this.$blockScrolling--; - var scrollIntoView = command && command.scrollIntoView; - if (scrollIntoView) { - switch (scrollIntoView) { - case "center-animate": - scrollIntoView = "animate"; - case "center": - this.renderer.scrollCursorIntoView(null, 0.5); - break; - case "animate": - case "cursor": - this.renderer.scrollCursorIntoView(); - break; - case "selectionPart": - var range = this.selection.getRange(); - var config = this.renderer.layerConfig; - if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) { - this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead); - } - break; - default: - break; - } - if (scrollIntoView == "animate") - this.renderer.animateScrolling(this.curOp.scrollTop); - } - - this.prevOp = this.curOp; - this.curOp = null; - } - }; - this.$mergeableCommands = ["backspace", "del", "insertstring"]; - this.$historyTracker = function(e) { - if (!this.$mergeUndoDeltas) - return; - - var prev = this.prevOp; - var mergeableCommands = this.$mergeableCommands; - var shouldMerge = prev.command && (e.command.name == prev.command.name); - if (e.command.name == "insertstring") { - var text = e.args; - if (this.mergeNextCommand === undefined) - this.mergeNextCommand = true; - - shouldMerge = shouldMerge - && this.mergeNextCommand // previous command allows to coalesce with - && (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type - - this.mergeNextCommand = true; - } else { - shouldMerge = shouldMerge - && mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable - } - - if ( - this.$mergeUndoDeltas != "always" - && Date.now() - this.sequenceStartTime > 2000 - ) { - shouldMerge = false; // the sequence is too long - } - - if (shouldMerge) - this.session.mergeUndoDeltas = true; - else if (mergeableCommands.indexOf(e.command.name) !== -1) - this.sequenceStartTime = Date.now(); - }; - this.setKeyboardHandler = function(keyboardHandler, cb) { - if (keyboardHandler && typeof keyboardHandler === "string") { - this.$keybindingId = keyboardHandler; - var _self = this; - config.loadModule(["keybinding", keyboardHandler], function(module) { - if (_self.$keybindingId == keyboardHandler) - _self.keyBinding.setKeyboardHandler(module && module.handler); - cb && cb(); - }); - } else { - this.$keybindingId = null; - this.keyBinding.setKeyboardHandler(keyboardHandler); - cb && cb(); - } - }; - this.getKeyboardHandler = function() { - return this.keyBinding.getKeyboardHandler(); - }; - this.setSession = function(session) { - if (this.session == session) - return; - if (this.curOp) this.endOperation(); - this.curOp = {}; - - var oldSession = this.session; - if (oldSession) { - this.session.off("change", this.$onDocumentChange); - this.session.off("changeMode", this.$onChangeMode); - this.session.off("tokenizerUpdate", this.$onTokenizerUpdate); - this.session.off("changeTabSize", this.$onChangeTabSize); - this.session.off("changeWrapLimit", this.$onChangeWrapLimit); - this.session.off("changeWrapMode", this.$onChangeWrapMode); - this.session.off("changeFold", this.$onChangeFold); - this.session.off("changeFrontMarker", this.$onChangeFrontMarker); - this.session.off("changeBackMarker", this.$onChangeBackMarker); - this.session.off("changeBreakpoint", this.$onChangeBreakpoint); - this.session.off("changeAnnotation", this.$onChangeAnnotation); - this.session.off("changeOverwrite", this.$onCursorChange); - this.session.off("changeScrollTop", this.$onScrollTopChange); - this.session.off("changeScrollLeft", this.$onScrollLeftChange); - - var selection = this.session.getSelection(); - selection.off("changeCursor", this.$onCursorChange); - selection.off("changeSelection", this.$onSelectionChange); - } - - this.session = session; - if (session) { - this.$onDocumentChange = this.onDocumentChange.bind(this); - session.on("change", this.$onDocumentChange); - this.renderer.setSession(session); - - this.$onChangeMode = this.onChangeMode.bind(this); - session.on("changeMode", this.$onChangeMode); - - this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this); - session.on("tokenizerUpdate", this.$onTokenizerUpdate); - - this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer); - session.on("changeTabSize", this.$onChangeTabSize); - - this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this); - session.on("changeWrapLimit", this.$onChangeWrapLimit); - - this.$onChangeWrapMode = this.onChangeWrapMode.bind(this); - session.on("changeWrapMode", this.$onChangeWrapMode); - - this.$onChangeFold = this.onChangeFold.bind(this); - session.on("changeFold", this.$onChangeFold); - - this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this); - this.session.on("changeFrontMarker", this.$onChangeFrontMarker); - - this.$onChangeBackMarker = this.onChangeBackMarker.bind(this); - this.session.on("changeBackMarker", this.$onChangeBackMarker); - - this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this); - this.session.on("changeBreakpoint", this.$onChangeBreakpoint); - - this.$onChangeAnnotation = this.onChangeAnnotation.bind(this); - this.session.on("changeAnnotation", this.$onChangeAnnotation); - - this.$onCursorChange = this.onCursorChange.bind(this); - this.session.on("changeOverwrite", this.$onCursorChange); - - this.$onScrollTopChange = this.onScrollTopChange.bind(this); - this.session.on("changeScrollTop", this.$onScrollTopChange); - - this.$onScrollLeftChange = this.onScrollLeftChange.bind(this); - this.session.on("changeScrollLeft", this.$onScrollLeftChange); - - this.selection = session.getSelection(); - this.selection.on("changeCursor", this.$onCursorChange); - - this.$onSelectionChange = this.onSelectionChange.bind(this); - this.selection.on("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(); - } else { - this.selection = null; - this.renderer.setSession(session); - } - - this._signal("changeSession", { - session: session, - oldSession: oldSession - }); - - this.curOp = null; - - oldSession && oldSession._signal("changeEditor", {oldEditor: this}); - session && session._signal("changeEditor", {editor: this}); - }; - 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, cb) { - this.renderer.setTheme(theme, cb); - }; - this.getTheme = function() { - return this.renderer.getTheme(); - }; - this.setStyle = function(style) { - this.renderer.setStyle(style); - }; - this.unsetStyle = function(style) { - this.renderer.unsetStyle(style); - }; - this.getFontSize = function () { - return this.getOption("fontSize") || - dom.computedStyle(this.container, "fontSize"); - }; - this.setFontSize = function(size) { - this.setOption("fontSize", size); - }; - - this.$highlightBrackets = function() { - if (this.session.$bracketHighlight) { - this.session.removeMarker(this.session.$bracketHighlight); - this.session.$bracketHighlight = null; - } - - if (this.$highlightPending) { - return; - } - var self = this; - this.$highlightPending = true; - setTimeout(function() { - self.$highlightPending = false; - var session = self.session; - if (!session || !session.bgTokenizer) return; - var pos = session.findMatchingBracket(self.getCursorPosition()); - if (pos) { - var range = new Range(pos.row, pos.column, pos.row, pos.column + 1); - } else if (session.$mode.getMatching) { - var range = session.$mode.getMatching(self.session); - } - if (range) - session.$bracketHighlight = session.addMarker(range, "ace_bracket", "text"); - }, 50); - }; - this.$highlightTags = function() { - if (this.$highlightTagPending) - return; - var self = this; - this.$highlightTagPending = true; - setTimeout(function() { - self.$highlightTagPending = false; - - var session = self.session; - if (!session || !session.bgTokenizer) return; - - var pos = self.getCursorPosition(); - var iterator = new TokenIterator(self.session, pos.row, pos.column); - var token = iterator.getCurrentToken(); - - if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) { - session.removeMarker(session.$tagHighlight); - session.$tagHighlight = null; - return; - } - - if (token.type.indexOf("tag-open") != -1) { - token = iterator.stepForward(); - if (!token) - return; - } - - var tag = token.value; - var depth = 0; - var prevToken = iterator.stepBackward(); - - if (prevToken.value == '<'){ - do { - prevToken = token; - token = iterator.stepForward(); - - if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { - if (prevToken.value === '<'){ - depth++; - } else if (prevToken.value === '= 0); - } else { - do { - token = prevToken; - prevToken = iterator.stepBackward(); - - if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) { - if (prevToken.value === '<') { - depth++; - } else if (prevToken.value === ' 1)) - highlight = false; - } - - if (session.$highlightLineMarker && !highlight) { - session.removeMarker(session.$highlightLineMarker.id); - session.$highlightLineMarker = null; - } else if (!session.$highlightLineMarker && highlight) { - var range = new Range(highlight.row, highlight.column, highlight.row, Infinity); - range.id = session.addMarker(range, "ace_active-line", "screenLine"); - session.$highlightLineMarker = range; - } else if (highlight) { - session.$highlightLineMarker.start.row = highlight.row; - session.$highlightLineMarker.end.row = highlight.row; - session.$highlightLineMarker.start.column = highlight.column; - session._signal("changeBackMarker"); - } - }; - - 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._signal("changeSelection"); - }; - - 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)); - 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(e) { - this.renderer.updateText(); - this._emit("changeMode", e); - }; - - - this.onChangeWrapLimit = function() { - this.renderer.updateFull(); - }; - - this.onChangeWrapMode = function() { - this.renderer.onResize(true); - }; - - - this.onChangeFold = function() { - this.$updateHighlightActiveLine(); - this.renderer.updateFull(); - }; - this.getSelectedText = function() { - return this.session.getTextRange(this.getSelectionRange()); - }; - this.getCopyText = function() { - var text = this.getSelectedText(); - this._signal("copy", text); - return text; - }; - this.onCopy = function() { - this.commands.exec("copy", this); - }; - this.onCut = function() { - this.commands.exec("cut", this); - }; - this.onPaste = function(text, event) { - var e = {text: text, event: event}; - this.commands.exec("paste", this, e); - }; - - this.$handlePaste = function(e) { - if (typeof e == "string") - e = {text: e}; - this._signal("paste", e); - var text = e.text; - if (!this.inMultiSelectMode || this.inVirtualSelectionMode) { - this.insert(text); - } else { - 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.execCommand = function(command, args) { - return this.commands.exec(command, this, args); - }; - this.insert = function(text, pasted) { - var session = this.session; - var mode = session.getMode(); - var cursor = this.getCursorPosition(); - - if (this.getBehavioursEnabled() && !pasted) { - var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text); - if (transform) { - if (text !== transform.text) { - this.session.mergeUndoDeltas = false; - this.$mergeNextCommand = false; - } - text = transform.text; - - } - } - - if (text == "\t") - text = this.session.getTabString(); - if (!this.selection.isEmpty()) { - var range = this.getSelectionRange(); - cursor = this.session.remove(range); - this.clearSelection(); - } - else if (this.session.getOverwrite()) { - var range = new Range.fromPoints(cursor, cursor); - range.end.column += text.length; - this.session.remove(range); - } - - if (text == "\n" || text == "\r\n") { - var line = session.getLine(cursor.row); - if (cursor.column > line.search(/\S|$/)) { - var d = line.substr(cursor.column).search(/\S|$/); - session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d); - } - } - this.clearSelection(); - - var start = cursor.column; - var lineState = session.getState(cursor.row); - var line = session.getLine(cursor.row); - var shouldOutdent = mode.checkOutdent(lineState, line, text); - 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])); - } - } - - if (session.getDocument().isNewLine(text)) { - var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString()); - - session.insert({row: cursor.row+1, column: 0}, 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.setOption("scrollSpeed", speed); - }; - this.getScrollSpeed = function() { - return this.getOption("scrollSpeed"); - }; - this.setDragDelay = function(dragDelay) { - this.setOption("dragDelay", dragDelay); - }; - this.getDragDelay = function() { - return this.getOption("dragDelay"); - }; - this.setSelectionStyle = function(val) { - this.setOption("selectionStyle", val); - }; - this.getSelectionStyle = function() { - return this.getOption("selectionStyle"); - }; - this.setHighlightActiveLine = function(shouldHighlight) { - this.setOption("highlightActiveLine", shouldHighlight); - }; - this.getHighlightActiveLine = function() { - return this.getOption("highlightActiveLine"); - }; - this.setHighlightGutterLine = function(shouldHighlight) { - this.setOption("highlightGutterLine", shouldHighlight); - }; - - this.getHighlightGutterLine = function() { - return this.getOption("highlightGutterLine"); - }; - this.setHighlightSelectedWord = function(shouldHighlight) { - this.setOption("highlightSelectedWord", shouldHighlight); - }; - 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) { - this.renderer.setShowInvisibles(showInvisibles); - }; - this.getShowInvisibles = function() { - return this.renderer.getShowInvisibles(); - }; - - this.setDisplayIndentGuides = function(display) { - this.renderer.setDisplayIndentGuides(display); - }; - - this.getDisplayIndentGuides = function() { - return this.renderer.getDisplayIndentGuides(); - }; - 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.setReadOnly = function(readOnly) { - this.setOption("readOnly", readOnly); - }; - this.getReadOnly = function() { - return this.getOption("readOnly"); - }; - this.setBehavioursEnabled = function (enabled) { - this.setOption("behavioursEnabled", enabled); - }; - this.getBehavioursEnabled = function () { - return this.getOption("behavioursEnabled"); - }; - this.setWrapBehavioursEnabled = function (enabled) { - this.setOption("wrapBehavioursEnabled", enabled); - }; - this.getWrapBehavioursEnabled = function () { - return this.getOption("wrapBehavioursEnabled"); - }; - this.setShowFoldWidgets = function(show) { - this.setOption("showFoldWidgets", show); - - }; - this.getShowFoldWidgets = function() { - return this.getOption("showFoldWidgets"); - }; - - this.setFadeFoldWidgets = function(fade) { - this.setOption("fadeFoldWidgets", fade); - }; - - this.getFadeFoldWidgets = function() { - return this.getOption("fadeFoldWidgets"); - }; - 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 (range.end.column === 0) { - var text = session.getTextRange(range); - if (text[text.length - 1] == "\n") { - var line = session.getLine(range.end.row); - if (/^\s+$/.test(line)) { - range.end.column = line.length; - } - } - } - 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) { - var rows = this.$getSelectedRows(); - session.indentRows(rows.first, rows.last, "\t"); - return; - } else if (range.start.column < range.end.column) { - var text = session.getTextRange(range); - if (!/^\s+$/.test(text)) { - var rows = this.$getSelectedRows(); - session.indentRows(rows.first, rows.last, "\t"); - return; - } - } - - var line = session.getLine(range.start.row); - var position = range.start; - var size = session.getTabSize(); - var column = session.documentToScreenColumn(position.row, position.column); - - if (this.session.getUseSoftTabs()) { - var count = (size - column % size); - var indentString = lang.stringRepeat(" ", count); - } else { - var count = column % size; - while (line[range.start.column - 1] == " " && count) { - range.start.column--; - count--; - } - this.selection.setSelectionRange(range); - indentString = "\t"; - } - return this.insert(indentString); - }; - this.blockIndent = function() { - var rows = this.$getSelectedRows(); - this.session.indentRows(rows.first, rows.last, "\t"); - }; - this.blockOutdent = function() { - var selection = this.session.getSelection(); - this.session.outdentRows(selection.getRange()); - }; - this.sortLines = function() { - var rows = this.$getSelectedRows(); - var session = this.session; - - var lines = []; - for (i = rows.first; i <= rows.last; i++) - lines.push(session.getLine(i)); - - lines.sort(function(a, b) { - if (a.toLowerCase() < b.toLowerCase()) return -1; - if (a.toLowerCase() > b.toLowerCase()) return 1; - return 0; - }); - - var deleteRange = new Range(0, 0, 0, 0); - for (var i = rows.first; i <= rows.last; i++) { - var line = session.getLine(i); - deleteRange.start.row = i; - deleteRange.end.row = i; - deleteRange.end.column = line.length; - session.replace(deleteRange, lines[i-rows.first]); - } - }; - 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.toggleBlockComment = function() { - var cursor = this.getCursorPosition(); - var state = this.session.getState(cursor.row); - var range = this.getSelectionRange(); - this.session.getMode().toggleBlockComment(state, this.session, range, cursor); - }; - this.getNumberAt = function(row, column) { - var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g; - _numberRx.lastIndex = 0; - - var s = this.session.getLine(row); - while (_numberRx.lastIndex < column) { - var m = _numberRx.exec(s); - if(m.index <= column && m.index+m[0].length >= column){ - var number = { - value: m[0], - start: m.index, - end: m.index+m[0].length - }; - return number; - } - } - return null; - }; - this.modifyNumber = function(amount) { - var row = this.selection.getCursor().row; - var column = this.selection.getCursor().column; - var charRange = new Range(row, column-1, row, column); - - var c = this.session.getTextRange(charRange); - if (!isNaN(parseFloat(c)) && isFinite(c)) { - var nr = this.getNumberAt(row, column); - if (nr) { - var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end; - var decimals = nr.start + nr.value.length - fp; - - var t = parseFloat(nr.value); - t *= Math.pow(10, decimals); - - - if(fp !== nr.end && column < fp){ - amount *= Math.pow(10, nr.end - column - 1); - } else { - amount *= Math.pow(10, nr.end - column); - } - - t += amount; - t /= Math.pow(10, decimals); - var nnr = t.toFixed(decimals); - var replaceRange = new Range(row, nr.start, row, nr.end); - this.session.replace(replaceRange, nnr); - this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length)); - - } - } - }; - this.removeLines = function() { - var rows = this.$getSelectedRows(); - this.session.removeFullLines(rows.first, rows.last); - this.clearSelection(); - }; - - this.duplicateSelection = function() { - var sel = this.selection; - var doc = this.session; - var range = sel.getRange(); - var reverse = sel.isBackwards(); - if (range.isEmpty()) { - var row = range.start.row; - doc.duplicateLines(row, row); - } else { - var point = reverse ? range.start : range.end; - var endPoint = doc.insert(point, doc.getTextRange(range), false); - range.start = point; - range.end = endPoint; - - sel.setSelectionRange(range, reverse); - } - }; - this.moveLinesDown = function() { - this.$moveLines(1, false); - }; - this.moveLinesUp = function() { - this.$moveLines(-1, false); - }; - this.moveText = function(range, toPosition, copy) { - return this.session.moveText(range, toPosition, copy); - }; - this.copyLinesUp = function() { - this.$moveLines(-1, true); - }; - this.copyLinesDown = function() { - this.$moveLines(1, true); - }; - this.$moveLines = function(dir, copy) { - var rows, moved; - var selection = this.selection; - if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) { - var range = selection.toOrientedRange(); - rows = this.$getSelectedRows(range); - moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir); - if (copy && dir == -1) moved = 0; - range.moveBy(moved, 0); - selection.fromOrientedRange(range); - } else { - var ranges = selection.rangeList.ranges; - selection.rangeList.detach(this.session); - this.inVirtualSelectionMode = true; - - var diff = 0; - var totalDiff = 0; - var l = ranges.length; - for (var i = 0; i < l; i++) { - var rangeIndex = i; - ranges[i].moveBy(diff, 0); - rows = this.$getSelectedRows(ranges[i]); - var first = rows.first; - var last = rows.last; - while (++i < l) { - if (totalDiff) ranges[i].moveBy(totalDiff, 0); - var subRows = this.$getSelectedRows(ranges[i]); - if (copy && subRows.first != last) - break; - else if (!copy && subRows.first > last + 1) - break; - last = subRows.last; - } - i--; - diff = this.session.$moveLines(first, last, copy ? 0 : dir); - if (copy && dir == -1) rangeIndex = i + 1; - while (rangeIndex <= i) { - ranges[rangeIndex].moveBy(diff, 0); - rangeIndex++; - } - if (!copy) diff = 0; - totalDiff += diff; - } - - selection.fromOrientedRange(selection.ranges[0]); - selection.rangeList.attach(this.session); - this.inVirtualSelectionMode = false; - } - }; - this.$getSelectedRows = function(range) { - range = (range || this.getSelectionRange()).collapseRows(); - - return { - first: this.session.getRowFoldStart(range.start.row), - last: this.session.getRowFoldEnd(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 pos = { - row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2), - column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2) - }; - this.renderer.alignCursor(pos, 0.5); - }; - 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(select, expand) { - var cursor = this.getCursorPosition(); - var iterator = new TokenIterator(this.session, cursor.row, cursor.column); - var prevToken = iterator.getCurrentToken(); - var token = prevToken || iterator.stepForward(); - - if (!token) return; - var matchType; - var found = false; - var depth = {}; - var i = cursor.column - token.start; - var bracketType; - var brackets = { - ")": "(", - "(": "(", - "]": "[", - "[": "[", - "{": "{", - "}": "{" - }; - - do { - if (token.value.match(/[{}()\[\]]/g)) { - for (; i < token.value.length && !found; i++) { - if (!brackets[token.value[i]]) { - continue; - } - - bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen"); - - if (isNaN(depth[bracketType])) { - depth[bracketType] = 0; - } - - switch (token.value[i]) { - case '(': - case '[': - case '{': - depth[bracketType]++; - break; - case ')': - case ']': - case '}': - depth[bracketType]--; - - if (depth[bracketType] === -1) { - matchType = 'bracket'; - found = true; - } - break; - } - } - } - else if (token && token.type.indexOf('tag-name') !== -1) { - if (isNaN(depth[token.value])) { - depth[token.value] = 0; - } - - if (prevToken.value === '<') { - depth[token.value]++; - } - else if (prevToken.value === '= 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; - } - 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(); - this._signal("destroy", this); - if (this.session) { - this.session.destroy(); - } - }; - this.setAutoScrollEditorIntoView = function(enable) { - if (!enable) - return; - var rect; - var self = this; - var shouldScroll = false; - if (!this.$scrollAnchor) - this.$scrollAnchor = document.createElement("div"); - var scrollAnchor = this.$scrollAnchor; - scrollAnchor.style.cssText = "position:absolute"; - this.container.insertBefore(scrollAnchor, this.container.firstChild); - var onChangeSelection = this.on("changeSelection", function() { - shouldScroll = true; - }); - var onBeforeRender = this.renderer.on("beforeRender", function() { - if (shouldScroll) - rect = self.renderer.container.getBoundingClientRect(); - }); - var onAfterRender = this.renderer.on("afterRender", function() { - if (shouldScroll && rect && (self.isFocused() - || self.searchBox && self.searchBox.isFocused()) - ) { - var renderer = self.renderer; - var pos = renderer.$cursorLayer.$pixelPos; - var config = renderer.layerConfig; - var top = pos.top - config.offset; - if (pos.top >= 0 && top + rect.top < 0) { - shouldScroll = true; - } else if (pos.top < config.height && - pos.top + rect.top + config.lineHeight > window.innerHeight) { - shouldScroll = false; - } else { - shouldScroll = null; - } - if (shouldScroll != null) { - scrollAnchor.style.top = top + "px"; - scrollAnchor.style.left = pos.left + "px"; - scrollAnchor.style.height = config.lineHeight + "px"; - scrollAnchor.scrollIntoView(shouldScroll); - } - shouldScroll = rect = null; - } - }); - this.setAutoScrollEditorIntoView = function(enable) { - if (enable) - return; - delete this.setAutoScrollEditorIntoView; - this.off("changeSelection", onChangeSelection); - this.renderer.off("afterRender", onAfterRender); - this.renderer.off("beforeRender", onBeforeRender); - }; - }; - - - this.$resetCursorStyle = function() { - var style = this.$cursorStyle || "ace"; - var cursorLayer = this.renderer.$cursorLayer; - if (!cursorLayer) - return; - cursorLayer.setSmoothBlinking(/smooth/.test(style)); - cursorLayer.isBlinking = !this.$readOnly && style != "wide"; - dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style)); - }; - -}).call(Editor.prototype); - - - -config.defineOptions(Editor.prototype, "editor", { - selectionStyle: { - set: function(style) { - this.onSelectionChange(); - this._signal("changeSelectionStyle", {data: style}); - }, - initialValue: "line" - }, - highlightActiveLine: { - set: function() {this.$updateHighlightActiveLine();}, - initialValue: true - }, - highlightSelectedWord: { - set: function(shouldHighlight) {this.$onSelectionChange();}, - initialValue: true - }, - readOnly: { - set: function(readOnly) { - this.$resetCursorStyle(); - }, - initialValue: false - }, - cursorStyle: { - set: function(val) { this.$resetCursorStyle(); }, - values: ["ace", "slim", "smooth", "wide"], - initialValue: "ace" - }, - mergeUndoDeltas: { - values: [false, true, "always"], - initialValue: true - }, - behavioursEnabled: {initialValue: true}, - wrapBehavioursEnabled: {initialValue: true}, - autoScrollEditorIntoView: { - set: function(val) {this.setAutoScrollEditorIntoView(val)} - }, - keyboardHandler: { - set: function(val) { this.setKeyboardHandler(val); }, - get: function() { return this.keybindingId; }, - handlesSet: true - }, - - hScrollBarAlwaysVisible: "renderer", - vScrollBarAlwaysVisible: "renderer", - highlightGutterLine: "renderer", - animatedScroll: "renderer", - showInvisibles: "renderer", - showPrintMargin: "renderer", - printMarginColumn: "renderer", - printMargin: "renderer", - fadeFoldWidgets: "renderer", - showFoldWidgets: "renderer", - showLineNumbers: "renderer", - showGutter: "renderer", - displayIndentGuides: "renderer", - fontSize: "renderer", - fontFamily: "renderer", - maxLines: "renderer", - minLines: "renderer", - scrollPastEnd: "renderer", - fixedWidthGutter: "renderer", - theme: "renderer", - - scrollSpeed: "$mouseHandler", - dragDelay: "$mouseHandler", - dragEnabled: "$mouseHandler", - focusTimout: "$mouseHandler", - tooltipFollowsMouse: "$mouseHandler", - - firstLineNumber: "session", - overwrite: "session", - newLineMode: "session", - useWorker: "session", - useSoftTabs: "session", - tabSize: "session", - wrap: "session", - indentedSoftWrap: "session", - foldStyle: "session", - mode: "session" -}); - -exports.Editor = Editor; -}); - -ace.define("ace/undomanager",["require","exports","module"], function(acequire, exports, module) { -"use strict"; -var UndoManager = function() { - this.reset(); -}; - -(function() { - this.execute = function(options) { - var deltaSets = options.args[0]; - this.$doc = options.args[1]; - if (options.merge && this.hasUndo()){ - this.dirtyCounter--; - deltaSets = this.$undoStack.pop().concat(deltaSets); - } - this.$undoStack.push(deltaSets); - this.$redoStack = []; - if (this.dirtyCounter < 0) { - this.dirtyCounter = NaN; - } - this.dirtyCounter++; - }; - this.undo = function(dontSelect) { - var deltaSets = this.$undoStack.pop(); - var undoSelectionRange = null; - if (deltaSets) { - undoSelectionRange = this.$doc.undoChanges(deltaSets, dontSelect); - this.$redoStack.push(deltaSets); - this.dirtyCounter--; - } - - return undoSelectionRange; - }; - this.redo = function(dontSelect) { - var deltaSets = this.$redoStack.pop(); - var redoSelectionRange = null; - if (deltaSets) { - redoSelectionRange = - this.$doc.redoChanges(this.$deserializeDeltas(deltaSets), dontSelect); - this.$undoStack.push(deltaSets); - this.dirtyCounter++; - } - return redoSelectionRange; - }; - this.reset = function() { - this.$undoStack = []; - this.$redoStack = []; - this.dirtyCounter = 0; - }; - this.hasUndo = function() { - return this.$undoStack.length > 0; - }; - this.hasRedo = function() { - return this.$redoStack.length > 0; - }; - this.markClean = function() { - this.dirtyCounter = 0; - }; - this.isClean = function() { - return this.dirtyCounter === 0; - }; - this.$serializeDeltas = function(deltaSets) { - return cloneDeltaSetsObj(deltaSets, $serializeDelta); - }; - this.$deserializeDeltas = function(deltaSets) { - return cloneDeltaSetsObj(deltaSets, $deserializeDelta); - }; - - function $serializeDelta(delta){ - return { - action: delta.action, - start: delta.start, - end: delta.end, - lines: delta.lines.length == 1 ? null : delta.lines, - text: delta.lines.length == 1 ? delta.lines[0] : null - }; - } - - function $deserializeDelta(delta) { - return { - action: delta.action, - start: delta.start, - end: delta.end, - lines: delta.lines || [delta.text] - }; - } - - function cloneDeltaSetsObj(deltaSets_old, fnGetModifiedDelta) { - var deltaSets_new = new Array(deltaSets_old.length); - for (var i = 0; i < deltaSets_old.length; i++) { - var deltaSet_old = deltaSets_old[i]; - var deltaSet_new = { group: deltaSet_old.group, deltas: new Array(deltaSet_old.length)}; - - for (var j = 0; j < deltaSet_old.deltas.length; j++) { - var delta_old = deltaSet_old.deltas[j]; - deltaSet_new.deltas[j] = fnGetModifiedDelta(delta_old); - } - - deltaSets_new[i] = deltaSet_new; - } - return deltaSets_new; - } - -}).call(UndoManager.prototype); - -exports.UndoManager = UndoManager; -}); - -ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"], function(acequire, exports, module) { -"use strict"; - -var dom = acequire("../lib/dom"); -var oop = acequire("../lib/oop"); -var lang = acequire("../lib/lang"); -var EventEmitter = acequire("../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.$annotations = []; - this.$updateAnnotations = this.$updateAnnotations.bind(this); - - this.$cells = []; -}; - -(function() { - - oop.implement(this, EventEmitter); - - this.setSession = function(session) { - if (this.session) - this.session.removeEventListener("change", this.$updateAnnotations); - this.session = session; - if (session) - session.on("change", this.$updateAnnotations); - }; - - this.addGutterDecoration = function(row, className){ - if (window.console) - console.warn && console.warn("deprecated use session.addGutterDecoration"); - this.session.addGutterDecoration(row, className); - }; - - this.removeGutterDecoration = function(row, className){ - if (window.console) - console.warn && console.warn("deprecated use session.removeGutterDecoration"); - this.session.removeGutterDecoration(row, className); - }; - - this.setAnnotations = function(annotations) { - this.$annotations = []; - for (var i = 0; i < annotations.length; i++) { - var annotation = annotations[i]; - var row = annotation.row; - var rowInfo = this.$annotations[row]; - if (!rowInfo) - rowInfo = this.$annotations[row] = {text: []}; - - var annoText = annotation.text; - annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || ""; - - if (rowInfo.text.indexOf(annoText) === -1) - rowInfo.text.push(annoText); - - var type = annotation.type; - if (type == "error") - rowInfo.className = " ace_error"; - else if (type == "warning" && rowInfo.className != " ace_error") - rowInfo.className = " ace_warning"; - else if (type == "info" && (!rowInfo.className)) - rowInfo.className = " ace_info"; - } - }; - - this.$updateAnnotations = function (delta) { - if (!this.$annotations.length) - return; - var firstRow = delta.start.row; - var len = delta.end.row - firstRow; - if (len === 0) { - } else if (delta.action == 'remove') { - this.$annotations.splice(firstRow, len + 1, null); - } else { - var args = new Array(len + 1); - args.unshift(firstRow, 1); - this.$annotations.splice.apply(this.$annotations, args); - } - }; - - this.update = function(config) { - var session = this.session; - var firstRow = config.firstRow; - var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar - session.getLength() - 1); - var fold = session.getNextFoldLine(firstRow); - var foldStart = fold ? fold.start.row : Infinity; - var foldWidgets = this.$showFoldWidgets && session.foldWidgets; - var breakpoints = session.$breakpoints; - var decorations = session.$decorations; - var firstLineNumber = session.$firstLineNumber; - var lastLineNumber = 0; - - var gutterRenderer = session.gutterRenderer || this.$renderer; - - var cell = null; - var index = -1; - var row = firstRow; - while (true) { - if (row > foldStart) { - row = fold.end.row + 1; - fold = session.getNextFoldLine(row, fold); - foldStart = fold ? fold.start.row : Infinity; - } - if (row > lastRow) { - while (this.$cells.length > index + 1) { - cell = this.$cells.pop(); - this.element.removeChild(cell.element); - } - break; - } - - cell = this.$cells[++index]; - if (!cell) { - cell = {element: null, textNode: null, foldWidget: null}; - cell.element = dom.createElement("div"); - cell.textNode = document.createTextNode(''); - cell.element.appendChild(cell.textNode); - this.element.appendChild(cell.element); - this.$cells[index] = cell; - } - - var className = "ace_gutter-cell "; - if (breakpoints[row]) - className += breakpoints[row]; - if (decorations[row]) - className += decorations[row]; - if (this.$annotations[row]) - className += this.$annotations[row].className; - if (cell.element.className != className) - cell.element.className = className; - - var height = session.getRowLength(row) * config.lineHeight + "px"; - if (height != cell.element.style.height) - cell.element.style.height = height; - - if (foldWidgets) { - var c = foldWidgets[row]; - if (c == null) - c = foldWidgets[row] = session.getFoldWidget(row); - } - - if (c) { - if (!cell.foldWidget) { - cell.foldWidget = dom.createElement("span"); - cell.element.appendChild(cell.foldWidget); - } - var className = "ace_fold-widget ace_" + c; - if (c == "start" && row == foldStart && row < fold.end.row) - className += " ace_closed"; - else - className += " ace_open"; - if (cell.foldWidget.className != className) - cell.foldWidget.className = className; - - var height = config.lineHeight + "px"; - if (cell.foldWidget.style.height != height) - cell.foldWidget.style.height = height; - } else { - if (cell.foldWidget) { - cell.element.removeChild(cell.foldWidget); - cell.foldWidget = null; - } - } - - var text = lastLineNumber = gutterRenderer - ? gutterRenderer.getText(session, row) - : row + firstLineNumber; - if (text != cell.textNode.data) - cell.textNode.data = text; - - row++; - } - - this.element.style.height = config.minHeight + "px"; - - if (this.$fixedWidth || session.$useWrapMode) - lastLineNumber = session.getLength() + firstLineNumber; - - var gutterWidth = gutterRenderer - ? gutterRenderer.getWidth(session, lastLineNumber, config) - : lastLineNumber.toString().length * config.characterWidth; - - var padding = this.$padding || this.$computePadding(); - gutterWidth += padding.left + padding.right; - if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) { - this.gutterWidth = gutterWidth; - this.element.style.width = Math.ceil(this.gutterWidth) + "px"; - this._emit("changeGutterWidth", gutterWidth); - } - }; - - this.$fixedWidth = false; - - this.$showLineNumbers = true; - this.$renderer = ""; - this.setShowLineNumbers = function(show) { - this.$renderer = !show && { - getWidth: function() {return ""}, - getText: function() {return ""} - }; - }; - - this.getShowLineNumbers = function() { - return this.$showLineNumbers; - }; - - this.$showFoldWidgets = true; - this.setShowFoldWidgets = function(show) { - if (show) - dom.addCssClass(this.element, "ace_folding-enabled"); - else - dom.removeCssClass(this.element, "ace_folding-enabled"); - - this.$showFoldWidgets = show; - this.$padding = null; - }; - - this.getShowFoldWidgets = function() { - return this.$showFoldWidgets; - }; - - this.$computePadding = function() { - if (!this.element.firstChild) - return {left: 0, right: 0}; - var style = dom.computedStyle(this.element.firstChild); - this.$padding = {}; - this.$padding.left = parseInt(style.paddingLeft) + 1 || 0; - this.$padding.right = parseInt(style.paddingRight) || 0; - return this.$padding; - }; - - this.getRegion = function(point) { - var padding = this.$padding || this.$computePadding(); - var rect = this.element.getBoundingClientRect(); - if (point.x < padding.left + rect.left) - return "markers"; - if (this.$showFoldWidgets && point.x > rect.right - padding.right) - return "foldWidgets"; - }; - -}).call(Gutter.prototype); - -exports.Gutter = Gutter; - -}); - -ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("../range").Range; -var dom = acequire("../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 = this.$padding + range.start.column * config.characterWidth; - marker.renderer(html, range, left, top, config); - } else if (marker.type == "fullLine") { - this.drawFullLineMarker(html, range, marker.clazz, config); - } else if (marker.type == "screenLine") { - this.drawScreenLineMarker(html, range, marker.clazz, config); - } else if (range.isMultiLine()) { - if (marker.type == "text") - this.drawTextMarker(html, range, marker.clazz, config); - else - this.drawMultiLineMarker(html, range, marker.clazz, config); - } else { - this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config); - } - } - this.element.innerHTML = html.join(""); - }; - - this.$getTop = function(row, layerConfig) { - return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight; - }; - - function getBorderClass(tl, tr, br, bl) { - return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0); - } - this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) { - var session = this.session; - var start = range.start.row; - var end = range.end.row; - var row = start; - var prev = 0; - var curr = 0; - var next = session.getScreenLastRowColumn(row); - var lineRange = new Range(row, range.start.column, row, curr); - for (; row <= end; row++) { - lineRange.start.row = lineRange.end.row = row; - lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row); - lineRange.end.column = next; - prev = curr; - curr = next; - next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column; - this.drawSingleLineMarker(stringBuilder, lineRange, - clazz + (row == start ? " ace_start" : "") + " ace_br" - + getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end), - layerConfig, row == end ? 0 : 1, extraStyle); - } - }; - this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var padding = this.$padding; - var height = config.lineHeight; - var top = this.$getTop(range.start.row, config); - var left = padding + range.start.column * config.characterWidth; - extraStyle = extraStyle || ""; - - stringBuilder.push( - "
" - ); - top = this.$getTop(range.end.row, config); - var width = range.end.column * config.characterWidth; - - stringBuilder.push( - "
" - ); - height = (range.end.row - range.start.row - 1) * config.lineHeight; - if (height <= 0) - return; - top = this.$getTop(range.start.row + 1, config); - - var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8); - - stringBuilder.push( - "
" - ); - }; - this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) { - var height = config.lineHeight; - var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth; - - var top = this.$getTop(range.start.row, config); - var left = this.$padding + range.start.column * config.characterWidth; - - stringBuilder.push( - "
" - ); - }; - - this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var top = this.$getTop(range.start.row, config); - var height = config.lineHeight; - if (range.start.row != range.end.row) - height += this.$getTop(range.end.row, config) - top; - - stringBuilder.push( - "
" - ); - }; - - this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) { - var top = this.$getTop(range.start.row, config); - var height = config.lineHeight; - - stringBuilder.push( - "
" - ); - }; - -}).call(Marker.prototype); - -exports.Marker = Marker; - -}); - -ace.define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var dom = acequire("../lib/dom"); -var lang = acequire("../lib/lang"); -var useragent = acequire("../lib/useragent"); -var EventEmitter = acequire("../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.$updateEolChar = this.$updateEolChar.bind(this); -}; - -(function() { - - oop.implement(this, EventEmitter); - - this.EOF_CHAR = "\xB6"; - this.EOL_CHAR_LF = "\xAC"; - this.EOL_CHAR_CRLF = "\xa4"; - this.EOL_CHAR = this.EOL_CHAR_LF; - this.TAB_CHAR = "\u2014"; //"\u21E5"; - this.SPACE_CHAR = "\xB7"; - this.$padding = 0; - - this.$updateEolChar = function() { - var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n" - ? this.EOL_CHAR_LF - : this.EOL_CHAR_CRLF; - if (this.EOL_CHAR != EOL_CHAR) { - this.EOL_CHAR = EOL_CHAR; - return true; - } - } - - this.setPadding = function(padding) { - this.$padding = padding; - this.element.style.padding = "0 " + padding + "px"; - }; - - this.getLineHeight = function() { - return this.$fontMetrics.$characterSize.height || 0; - }; - - this.getCharacterWidth = function() { - return this.$fontMetrics.$characterSize.width || 0; - }; - - this.$setFontMetrics = function(measure) { - this.$fontMetrics = measure; - this.$fontMetrics.on("changeCharacterSize", function(e) { - this._signal("changeCharacterSize", e); - }.bind(this)); - this.$pollSizeChanges(); - } - - this.checkForSizeChanges = function() { - this.$fontMetrics.checkForSizeChanges(); - }; - this.$pollSizeChanges = function() { - return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges(); - }; - this.setSession = function(session) { - this.session = session; - if (session) - this.$computeTabString(); - }; - - this.showInvisibles = false; - this.setShowInvisibles = function(showInvisibles) { - if (this.showInvisibles == showInvisibles) - return false; - - this.showInvisibles = showInvisibles; - this.$computeTabString(); - return true; - }; - - this.displayIndentGuides = true; - this.setDisplayIndentGuides = function(display) { - if (this.displayIndentGuides == display) - return false; - - this.displayIndentGuides = display; - this.$computeTabString(); - return true; - }; - - this.$tabStrings = []; - this.onChangeTabSize = - this.$computeTabString = function() { - var tabSize = this.session.getTabSize(); - this.tabSize = tabSize; - var tabStr = this.$tabStrings = [0]; - for (var i = 1; i < tabSize + 1; i++) { - if (this.showInvisibles) { - tabStr.push("" - + lang.stringRepeat(this.TAB_CHAR, i) - + ""); - } else { - tabStr.push(lang.stringRepeat(" ", i)); - } - } - if (this.displayIndentGuides) { - this.$indentGuideRe = /\s\S| \t|\t |\s$/; - var className = "ace_indent-guide"; - var spaceClass = ""; - var tabClass = ""; - if (this.showInvisibles) { - className += " ace_invisible"; - spaceClass = " ace_invisible_space"; - tabClass = " ace_invisible_tab"; - var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize); - var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize); - } else{ - var spaceContent = lang.stringRepeat(" ", this.tabSize); - var tabContent = spaceContent; - } - - this.$tabStrings[" "] = "" + spaceContent + ""; - this.$tabStrings["\t"] = "" + tabContent + ""; - } - }; - - this.updateLines = function(config, firstRow, lastRow) { - if (this.config.lastRow != config.lastRow || - this.config.firstRow != config.firstRow) { - this.scrollLines(config); - } - this.config = config; - - var first = Math.max(firstRow, config.firstRow); - var last = Math.min(lastRow, config.lastRow); - - var lineElements = this.element.childNodes; - var lineElementsIdx = 0; - - for (var row = config.firstRow; row < first; row++) { - var foldLine = this.session.getFoldLine(row); - if (foldLine) { - if (foldLine.containsRow(first)) { - first = foldLine.start.row; - break; - } else { - row = foldLine.end.row; - } - } - lineElementsIdx ++; - } - - var row = first; - var foldLine = this.session.getNextFoldLine(row); - var foldStart = foldLine ? foldLine.start.row : Infinity; - - while (true) { - if (row > foldStart) { - row = foldLine.end.row+1; - foldLine = this.session.getNextFoldLine(row, foldLine); - foldStart = foldLine ? foldLine.start.row :Infinity; - } - if (row > last) - break; - - var lineElement = lineElements[lineElementsIdx++]; - if (lineElement) { - var html = []; - this.$renderLine( - html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false - ); - lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; - lineElement.innerHTML = html.join(""); - } - row++; - } - }; - - this.scrollLines = function(config) { - var oldConfig = this.config; - this.config = config; - - if (!oldConfig || oldConfig.lastRow < config.firstRow) - return this.update(config); - - if (config.lastRow < oldConfig.firstRow) - return this.update(config); - - var el = this.element; - if (oldConfig.firstRow < config.firstRow) - for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--) - el.removeChild(el.firstChild); - - if (oldConfig.lastRow > config.lastRow) - for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--) - el.removeChild(el.lastChild); - - if (config.firstRow < oldConfig.firstRow) { - var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1); - if (el.firstChild) - el.insertBefore(fragment, el.firstChild); - else - el.appendChild(fragment); - } - - if (config.lastRow > oldConfig.lastRow) { - var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow); - el.appendChild(fragment); - } - }; - - this.$renderLinesFragment = function(config, firstRow, lastRow) { - var fragment = this.element.ownerDocument.createDocumentFragment(); - var row = firstRow; - var foldLine = this.session.getNextFoldLine(row); - var foldStart = foldLine ? foldLine.start.row : Infinity; - - while (true) { - if (row > foldStart) { - row = foldLine.end.row+1; - foldLine = this.session.getNextFoldLine(row, foldLine); - foldStart = foldLine ? foldLine.start.row : Infinity; - } - if (row > lastRow) - break; - - var container = dom.createElement("div"); - - var html = []; - this.$renderLine(html, row, false, row == foldStart ? foldLine : false); - container.innerHTML = html.join(""); - if (this.$useLineGroups()) { - container.className = 'ace_line_group'; - fragment.appendChild(container); - container.style.height = config.lineHeight * this.session.getRowLength(row) + "px"; - - } else { - while(container.firstChild) - fragment.appendChild(container.firstChild); - } - - row++; - } - return fragment; - }; - - this.update = function(config) { - this.config = config; - - var html = []; - var firstRow = config.firstRow, lastRow = config.lastRow; - - var row = firstRow; - var foldLine = this.session.getNextFoldLine(row); - var foldStart = foldLine ? foldLine.start.row : Infinity; - - while (true) { - if (row > foldStart) { - row = foldLine.end.row+1; - foldLine = this.session.getNextFoldLine(row, foldLine); - foldStart = foldLine ? foldLine.start.row :Infinity; - } - if (row > lastRow) - break; - - if (this.$useLineGroups()) - html.push("
") - - this.$renderLine(html, row, false, row == foldStart ? foldLine : false); - - if (this.$useLineGroups()) - html.push("
"); // end the line group - - row++; - } - this.element.innerHTML = html.join(""); - }; - - this.$textToken = { - "text": true, - "rparen": true, - "lparen": true - }; - - this.$renderToken = function(stringBuilder, screenColumn, token, value) { - var self = this; - var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g; - var replaceFunc = function(c, a, b, tabIdx, idx4) { - if (a) { - return self.showInvisibles - ? "" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "" - : c; - } else if (c == "&") { - return "&"; - } else if (c == "<") { - return "<"; - } else if (c == ">") { - return ">"; - } else if (c == "\t") { - var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx); - screenColumn += tabSize - 1; - return self.$tabStrings[tabSize]; - } else if (c == "\u3000") { - var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk"; - var space = self.showInvisibles ? self.SPACE_CHAR : ""; - screenColumn += 1; - return "" + space + ""; - } else if (b) { - return "" + self.SPACE_CHAR + ""; - } else { - screenColumn += 1; - return "" + c + ""; - } - }; - - 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("", output, ""); - } - else { - stringBuilder.push(output); - } - return screenColumn + value.length; - }; - - this.renderIndentGuide = function(stringBuilder, value, max) { - var cols = value.search(this.$indentGuideRe); - if (cols <= 0 || cols >= max) - return value; - if (value[0] == " ") { - cols -= cols % this.tabSize; - stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize)); - return value.substr(cols); - } else if (value[0] == "\t") { - stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols)); - return value.substr(cols); - } - return value; - }; - - this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) { - var chars = 0; - var split = 0; - var splitChars = splits[0]; - var screenColumn = 0; - - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i]; - var value = token.value; - if (i == 0 && this.displayIndentGuides) { - chars = value.length; - value = this.renderIndentGuide(stringBuilder, value, splitChars); - if (!value) - continue; - chars -= value.length; - } - - if (chars + value.length < splitChars) { - screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); - chars += value.length; - } else { - while (chars + value.length >= splitChars) { - screenColumn = this.$renderToken( - stringBuilder, screenColumn, - token, value.substring(0, splitChars - chars) - ); - value = value.substring(splitChars - chars); - chars = splitChars; - - if (!onlyContents) { - stringBuilder.push("
", - "
" - ); - } - - stringBuilder.push(lang.stringRepeat("\xa0", splits.indent)); - - split ++; - screenColumn = 0; - splitChars = splits[split] || Number.MAX_VALUE; - } - if (value.length != 0) { - chars += value.length; - screenColumn = this.$renderToken( - stringBuilder, screenColumn, token, value - ); - } - } - } - }; - - this.$renderSimpleLine = function(stringBuilder, tokens) { - var screenColumn = 0; - var token = tokens[0]; - var value = token.value; - if (this.displayIndentGuides) - value = this.renderIndentGuide(stringBuilder, value); - if (value) - screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); - for (var i = 1; i < tokens.length; i++) { - token = tokens[i]; - value = token.value; - screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value); - } - }; - this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) { - if (!foldLine && foldLine != false) - foldLine = this.session.getFoldLine(row); - - if (foldLine) - var tokens = this.$getFoldLineTokens(row, foldLine); - else - var tokens = this.session.getTokens(row); - - - if (!onlyContents) { - stringBuilder.push( - "
" - ); - } - - if (tokens.length) { - var splits = this.session.getRowSplitData(row); - if (splits && splits.length) - this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents); - else - this.$renderSimpleLine(stringBuilder, tokens); - } - - if (this.showInvisibles) { - if (foldLine) - row = foldLine.end.row - - stringBuilder.push( - "", - row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR, - "" - ); - } - if (!onlyContents) - stringBuilder.push("
"); - }; - - this.$getFoldLineTokens = function(row, foldLine) { - var session = this.session; - var renderTokens = []; - - function addTokens(tokens, from, to) { - var idx = 0, col = 0; - while ((col + tokens[idx].value.length) < from) { - col += tokens[idx].value.length; - idx++; - - if (idx == tokens.length) - return; - } - if (col != from) { - var value = tokens[idx].value.substring(from - col); - if (value.length > (to - from)) - value = value.substring(0, to - from); - - renderTokens.push({ - type: tokens[idx].type, - value: value - }); - - col = from + value.length; - idx += 1; - } - - while (col < to && idx < tokens.length) { - var value = tokens[idx].value; - if (value.length + col > to) { - renderTokens.push({ - type: tokens[idx].type, - value: value.substring(0, to - col) - }); - } else - renderTokens.push(tokens[idx]); - col += value.length; - idx += 1; - } - } - - var tokens = session.getTokens(row); - foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) { - if (placeholder != null) { - renderTokens.push({ - type: "fold", - value: placeholder - }); - } else { - if (isNewRow) - tokens = session.getTokens(row); - - if (tokens.length) - addTokens(tokens, lastColumn, column); - } - }, foldLine.end.row, this.session.getLine(foldLine.end.row).length); - - return renderTokens; - }; - - this.$useLineGroups = function() { - return this.session.getUseWrapMode(); - }; - - this.destroy = function() { - clearInterval(this.$pollSizeChangesTimer); - if (this.$measureNode) - this.$measureNode.parentNode.removeChild(this.$measureNode); - delete this.$measureNode; - }; - -}).call(Text.prototype); - -exports.Text = Text; - -}); - -ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -var dom = acequire("../lib/dom"); -var isIE8; - -var Cursor = function(parentEl) { - this.element = dom.createElement("div"); - this.element.className = "ace_layer ace_cursor-layer"; - parentEl.appendChild(this.element); - - if (isIE8 === undefined) - isIE8 = !("opacity" in this.element.style); - - this.isVisible = false; - this.isBlinking = true; - this.blinkInterval = 1000; - this.smoothBlinking = false; - - this.cursors = []; - this.cursor = this.addCursor(); - dom.addCssClass(this.element, "ace_hidden-cursors"); - this.$updateCursors = (isIE8 - ? this.$updateVisibility - : this.$updateOpacity).bind(this); -}; - -(function() { - - this.$updateVisibility = function(val) { - var cursors = this.cursors; - for (var i = cursors.length; i--; ) - cursors[i].style.visibility = val ? "" : "hidden"; - }; - this.$updateOpacity = function(val) { - var cursors = this.cursors; - for (var i = cursors.length; i--; ) - cursors[i].style.opacity = val ? "" : "0"; - }; - - - this.$padding = 0; - this.setPadding = function(padding) { - this.$padding = padding; - }; - - this.setSession = function(session) { - this.session = session; - }; - - this.setBlinking = function(blinking) { - if (blinking != this.isBlinking){ - this.isBlinking = blinking; - this.restartTimer(); - } - }; - - this.setBlinkInterval = function(blinkInterval) { - if (blinkInterval != this.blinkInterval){ - this.blinkInterval = blinkInterval; - this.restartTimer(); - } - }; - - this.setSmoothBlinking = function(smoothBlinking) { - if (smoothBlinking != this.smoothBlinking && !isIE8) { - this.smoothBlinking = smoothBlinking; - dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking); - this.$updateCursors(true); - this.$updateCursors = (this.$updateOpacity).bind(this); - this.restartTimer(); - } - }; - - this.addCursor = function() { - var el = dom.createElement("div"); - el.className = "ace_cursor"; - 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; - dom.addCssClass(this.element, "ace_hidden-cursors"); - this.restartTimer(); - }; - - this.showCursor = function() { - this.isVisible = true; - dom.removeCssClass(this.element, "ace_hidden-cursors"); - this.restartTimer(); - }; - - this.restartTimer = function() { - var update = this.$updateCursors; - clearInterval(this.intervalId); - clearTimeout(this.timeoutId); - if (this.smoothBlinking) { - dom.removeCssClass(this.element, "ace_smooth-blinking"); - } - - update(true); - - if (!this.isBlinking || !this.blinkInterval || !this.isVisible) - return; - - if (this.smoothBlinking) { - setTimeout(function(){ - dom.addCssClass(this.element, "ace_smooth-blinking"); - }.bind(this)); - } - - var blink = function(){ - this.timeoutId = setTimeout(function() { - update(false); - }, 0.6 * this.blinkInterval); - }.bind(this); - - this.intervalId = setInterval(function() { - update(true); - blink(); - }, this.blinkInterval); - - blink(); - }; - - 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 = 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; - - var selections = this.session.$selectionMarkers; - var i = 0, cursorIndex = 0; - - if (selections === undefined || selections.length === 0){ - selections = [{cursor: null}]; - } - - for (var i = 0, n = selections.length; i < n; i++) { - var pixelPos = this.getPixelPosition(selections[i].cursor, true); - if ((pixelPos.top > config.height + config.offset || - pixelPos.top < 0) && i > 1) { - continue; - } - - var style = (this.cursors[cursorIndex++] || this.addCursor()).style; - - if (!this.drawCursor) { - style.left = pixelPos.left + "px"; - style.top = pixelPos.top + "px"; - style.width = config.characterWidth + "px"; - style.height = config.lineHeight + "px"; - } else { - this.drawCursor(style, pixelPos, config, selections[i], this.session); - } - } - while (this.cursors.length > cursorIndex) - this.removeCursor(); - - var overwrite = this.session.getOverwrite(); - this.$setOverwrite(overwrite); - this.$pixelPos = pixelPos; - this.restartTimer(); - }; - - this.drawCursor = null; - - this.$setOverwrite = function(overwrite) { - if (overwrite != this.overwrite) { - this.overwrite = overwrite; - if (overwrite) - dom.addCssClass(this.element, "ace_overwrite-cursors"); - else - dom.removeCssClass(this.element, "ace_overwrite-cursors"); - } - }; - - this.destroy = function() { - clearInterval(this.intervalId); - clearTimeout(this.timeoutId); - }; - -}).call(Cursor.prototype); - -exports.Cursor = Cursor; - -}); - -ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var dom = acequire("./lib/dom"); -var event = acequire("./lib/event"); -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var MAX_SCROLL_H = 0x8000; -var ScrollBar = function(parent) { - this.element = dom.createElement("div"); - this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix; - - this.inner = dom.createElement("div"); - this.inner.className = "ace_scrollbar-inner"; - this.element.appendChild(this.inner); - - parent.appendChild(this.element); - - this.setVisible(false); - this.skipEvent = false; - - event.addListener(this.element, "scroll", this.onScroll.bind(this)); - event.addListener(this.element, "mousedown", event.preventDefault); -}; - -(function() { - oop.implement(this, EventEmitter); - - this.setVisible = function(isVisible) { - this.element.style.display = isVisible ? "" : "none"; - this.isVisible = isVisible; - this.coeff = 1; - }; -}).call(ScrollBar.prototype); -var VScrollBar = function(parent, renderer) { - ScrollBar.call(this, parent); - this.scrollTop = 0; - this.scrollHeight = 0; - renderer.$scrollbarWidth = - this.width = dom.scrollbarWidth(parent.ownerDocument); - this.inner.style.width = - this.element.style.width = (this.width || 15) + 5 + "px"; -}; - -oop.inherits(VScrollBar, ScrollBar); - -(function() { - - this.classSuffix = '-v'; - this.onScroll = function() { - if (!this.skipEvent) { - this.scrollTop = this.element.scrollTop; - if (this.coeff != 1) { - var h = this.element.clientHeight / this.scrollHeight; - this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h); - } - this._emit("scroll", {data: this.scrollTop}); - } - this.skipEvent = false; - }; - this.getWidth = function() { - return this.isVisible ? this.width : 0; - }; - this.setHeight = function(height) { - this.element.style.height = height + "px"; - }; - this.setInnerHeight = - this.setScrollHeight = function(height) { - this.scrollHeight = height; - if (height > MAX_SCROLL_H) { - this.coeff = MAX_SCROLL_H / height; - height = MAX_SCROLL_H; - } else if (this.coeff != 1) { - this.coeff = 1 - } - this.inner.style.height = height + "px"; - }; - this.setScrollTop = function(scrollTop) { - if (this.scrollTop != scrollTop) { - this.skipEvent = true; - this.scrollTop = scrollTop; - this.element.scrollTop = scrollTop * this.coeff; - } - }; - -}).call(VScrollBar.prototype); -var HScrollBar = function(parent, renderer) { - ScrollBar.call(this, parent); - this.scrollLeft = 0; - this.height = renderer.$scrollbarWidth; - this.inner.style.height = - this.element.style.height = (this.height || 15) + 5 + "px"; -}; - -oop.inherits(HScrollBar, ScrollBar); - -(function() { - - this.classSuffix = '-h'; - this.onScroll = function() { - if (!this.skipEvent) { - this.scrollLeft = this.element.scrollLeft; - this._emit("scroll", {data: this.scrollLeft}); - } - this.skipEvent = false; - }; - this.getHeight = function() { - return this.isVisible ? this.height : 0; - }; - this.setWidth = function(width) { - this.element.style.width = width + "px"; - }; - this.setInnerWidth = function(width) { - this.inner.style.width = width + "px"; - }; - this.setScrollWidth = function(width) { - this.inner.style.width = width + "px"; - }; - this.setScrollLeft = function(scrollLeft) { - if (this.scrollLeft != scrollLeft) { - this.skipEvent = true; - this.scrollLeft = this.element.scrollLeft = scrollLeft; - } - }; - -}).call(HScrollBar.prototype); - - -exports.ScrollBar = VScrollBar; // backward compatibility -exports.ScrollBarV = VScrollBar; // backward compatibility -exports.ScrollBarH = HScrollBar; // backward compatibility - -exports.VScrollBar = VScrollBar; -exports.HScrollBar = HScrollBar; -}); - -ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(acequire, exports, module) { -"use strict"; - -var event = acequire("./lib/event"); - - -var RenderLoop = function(onRender, win) { - this.onRender = onRender; - this.pending = false; - this.changes = 0; - this.window = win || window; -}; - -(function() { - - - this.schedule = function(change) { - this.changes = this.changes | change; - if (!this.pending && this.changes) { - this.pending = true; - var _self = this; - event.nextFrame(function() { - _self.pending = false; - var changes; - while (changes = _self.changes) { - _self.changes = 0; - _self.onRender(changes); - } - }, this.window); - } - }; - -}).call(RenderLoop.prototype); - -exports.RenderLoop = RenderLoop; -}); - -ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) { - -var oop = acequire("../lib/oop"); -var dom = acequire("../lib/dom"); -var lang = acequire("../lib/lang"); -var useragent = acequire("../lib/useragent"); -var EventEmitter = acequire("../lib/event_emitter").EventEmitter; - -var CHAR_COUNT = 0; - -var FontMetrics = exports.FontMetrics = function(parentEl) { - this.el = dom.createElement("div"); - this.$setMeasureNodeStyles(this.el.style, true); - - this.$main = dom.createElement("div"); - this.$setMeasureNodeStyles(this.$main.style); - - this.$measureNode = dom.createElement("div"); - this.$setMeasureNodeStyles(this.$measureNode.style); - - - this.el.appendChild(this.$main); - this.el.appendChild(this.$measureNode); - parentEl.appendChild(this.el); - - if (!CHAR_COUNT) - this.$testFractionalRect(); - this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT); - - this.$characterSize = {width: 0, height: 0}; - this.checkForSizeChanges(); -}; - -(function() { - - oop.implement(this, EventEmitter); - - this.$characterSize = {width: 0, height: 0}; - - this.$testFractionalRect = function() { - var el = dom.createElement("div"); - this.$setMeasureNodeStyles(el.style); - el.style.width = "0.2px"; - document.documentElement.appendChild(el); - var w = el.getBoundingClientRect().width; - if (w > 0 && w < 1) - CHAR_COUNT = 50; - else - CHAR_COUNT = 100; - el.parentNode.removeChild(el); - }; - - this.$setMeasureNodeStyles = function(style, isRoot) { - style.width = style.height = "auto"; - style.left = style.top = "0px"; - style.visibility = "hidden"; - style.position = "absolute"; - style.whiteSpace = "pre"; - - if (useragent.isIE < 8) { - style["font-family"] = "inherit"; - } else { - style.font = "inherit"; - } - style.overflow = isRoot ? "hidden" : "visible"; - }; - - this.checkForSizeChanges = function() { - var size = this.$measureSizes(); - if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) { - this.$measureNode.style.fontWeight = "bold"; - var boldSize = this.$measureSizes(); - this.$measureNode.style.fontWeight = ""; - this.$characterSize = size; - this.charSizes = Object.create(null); - this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height; - this._emit("changeCharacterSize", {data: size}); - } - }; - - this.$pollSizeChanges = function() { - if (this.$pollSizeChangesTimer) - return this.$pollSizeChangesTimer; - var self = this; - return this.$pollSizeChangesTimer = setInterval(function() { - self.checkForSizeChanges(); - }, 500); - }; - - this.setPolling = function(val) { - if (val) { - this.$pollSizeChanges(); - } else if (this.$pollSizeChangesTimer) { - clearInterval(this.$pollSizeChangesTimer); - this.$pollSizeChangesTimer = 0; - } - }; - - this.$measureSizes = function() { - if (CHAR_COUNT === 50) { - var rect = null; - try { - rect = this.$measureNode.getBoundingClientRect(); - } catch(e) { - rect = {width: 0, height:0 }; - } - var size = { - height: rect.height, - width: rect.width / CHAR_COUNT - }; - } else { - var size = { - height: this.$measureNode.clientHeight, - width: this.$measureNode.clientWidth / CHAR_COUNT - }; - } - if (size.width === 0 || size.height === 0) - return null; - return size; - }; - - this.$measureCharWidth = function(ch) { - this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT); - var rect = this.$main.getBoundingClientRect(); - return rect.width / CHAR_COUNT; - }; - - this.getCharacterWidth = function(ch) { - var w = this.charSizes[ch]; - if (w === undefined) { - w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width; - } - return w; - }; - - this.destroy = function() { - clearInterval(this.$pollSizeChangesTimer); - if (this.el && this.el.parentNode) - this.el.parentNode.removeChild(this.el); - }; - -}).call(FontMetrics.prototype); - -}); - -ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var dom = acequire("./lib/dom"); -var config = acequire("./config"); -var useragent = acequire("./lib/useragent"); -var GutterLayer = acequire("./layer/gutter").Gutter; -var MarkerLayer = acequire("./layer/marker").Marker; -var TextLayer = acequire("./layer/text").Text; -var CursorLayer = acequire("./layer/cursor").Cursor; -var HScrollBar = acequire("./scrollbar").HScrollBar; -var VScrollBar = acequire("./scrollbar").VScrollBar; -var RenderLoop = acequire("./renderloop").RenderLoop; -var FontMetrics = acequire("./layer/font_metrics").FontMetrics; -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var editorCss = ".ace_editor {\ -position: relative;\ -overflow: hidden;\ -font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\ -direction: ltr;\ -text-align: left;\ -}\ -.ace_scroller {\ -position: absolute;\ -overflow: hidden;\ -top: 0;\ -bottom: 0;\ -background-color: inherit;\ --ms-user-select: none;\ --moz-user-select: none;\ --webkit-user-select: none;\ -user-select: none;\ -cursor: text;\ -}\ -.ace_content {\ -position: absolute;\ --moz-box-sizing: border-box;\ --webkit-box-sizing: border-box;\ -box-sizing: border-box;\ -min-width: 100%;\ -}\ -.ace_dragging .ace_scroller:before{\ -position: absolute;\ -top: 0;\ -left: 0;\ -right: 0;\ -bottom: 0;\ -content: '';\ -background: rgba(250, 250, 250, 0.01);\ -z-index: 1000;\ -}\ -.ace_dragging.ace_dark .ace_scroller:before{\ -background: rgba(0, 0, 0, 0.01);\ -}\ -.ace_selecting, .ace_selecting * {\ -cursor: text !important;\ -}\ -.ace_gutter {\ -position: absolute;\ -overflow : hidden;\ -width: auto;\ -top: 0;\ -bottom: 0;\ -left: 0;\ -cursor: default;\ -z-index: 4;\ --ms-user-select: none;\ --moz-user-select: none;\ --webkit-user-select: none;\ -user-select: none;\ -}\ -.ace_gutter-active-line {\ -position: absolute;\ -left: 0;\ -right: 0;\ -}\ -.ace_scroller.ace_scroll-left {\ -box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\ -}\ -.ace_gutter-cell {\ -padding-left: 19px;\ -padding-right: 6px;\ -background-repeat: no-repeat;\ -}\ -.ace_gutter-cell.ace_error {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\ -background-repeat: no-repeat;\ -background-position: 2px center;\ -}\ -.ace_gutter-cell.ace_warning {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\ -background-position: 2px center;\ -}\ -.ace_gutter-cell.ace_info {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\ -background-position: 2px center;\ -}\ -.ace_dark .ace_gutter-cell.ace_info {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\ -}\ -.ace_scrollbar {\ -position: absolute;\ -right: 0;\ -bottom: 0;\ -z-index: 6;\ -}\ -.ace_scrollbar-inner {\ -position: absolute;\ -cursor: text;\ -left: 0;\ -top: 0;\ -}\ -.ace_scrollbar-v{\ -overflow-x: hidden;\ -overflow-y: scroll;\ -top: 0;\ -}\ -.ace_scrollbar-h {\ -overflow-x: scroll;\ -overflow-y: hidden;\ -left: 0;\ -}\ -.ace_print-margin {\ -position: absolute;\ -height: 100%;\ -}\ -.ace_text-input {\ -position: absolute;\ -z-index: 0;\ -width: 0.5em;\ -height: 1em;\ -opacity: 0;\ -background: transparent;\ --moz-appearance: none;\ -appearance: none;\ -border: none;\ -resize: none;\ -outline: none;\ -overflow: hidden;\ -font: inherit;\ -padding: 0 1px;\ -margin: 0 -1px;\ -text-indent: -1em;\ --ms-user-select: text;\ --moz-user-select: text;\ --webkit-user-select: text;\ -user-select: text;\ -white-space: pre!important;\ -}\ -.ace_text-input.ace_composition {\ -background: inherit;\ -color: inherit;\ -z-index: 1000;\ -opacity: 1;\ -text-indent: 0;\ -}\ -.ace_layer {\ -z-index: 1;\ -position: absolute;\ -overflow: hidden;\ -word-wrap: normal;\ -white-space: pre;\ -height: 100%;\ -width: 100%;\ --moz-box-sizing: border-box;\ --webkit-box-sizing: border-box;\ -box-sizing: border-box;\ -pointer-events: none;\ -}\ -.ace_gutter-layer {\ -position: relative;\ -width: auto;\ -text-align: right;\ -pointer-events: auto;\ -}\ -.ace_text-layer {\ -font: inherit !important;\ -}\ -.ace_cjk {\ -display: inline-block;\ -text-align: center;\ -}\ -.ace_cursor-layer {\ -z-index: 4;\ -}\ -.ace_cursor {\ -z-index: 4;\ -position: absolute;\ --moz-box-sizing: border-box;\ --webkit-box-sizing: border-box;\ -box-sizing: border-box;\ -border-left: 2px solid;\ -transform: translatez(0);\ -}\ -.ace_slim-cursors .ace_cursor {\ -border-left-width: 1px;\ -}\ -.ace_overwrite-cursors .ace_cursor {\ -border-left-width: 0;\ -border-bottom: 1px solid;\ -}\ -.ace_hidden-cursors .ace_cursor {\ -opacity: 0.2;\ -}\ -.ace_smooth-blinking .ace_cursor {\ --webkit-transition: opacity 0.18s;\ -transition: opacity 0.18s;\ -}\ -.ace_editor.ace_multiselect .ace_cursor {\ -border-left-width: 1px;\ -}\ -.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\ -position: absolute;\ -z-index: 3;\ -}\ -.ace_marker-layer .ace_selection {\ -position: absolute;\ -z-index: 5;\ -}\ -.ace_marker-layer .ace_bracket {\ -position: absolute;\ -z-index: 6;\ -}\ -.ace_marker-layer .ace_active-line {\ -position: absolute;\ -z-index: 2;\ -}\ -.ace_marker-layer .ace_selected-word {\ -position: absolute;\ -z-index: 4;\ --moz-box-sizing: border-box;\ --webkit-box-sizing: border-box;\ -box-sizing: border-box;\ -}\ -.ace_line .ace_fold {\ --moz-box-sizing: border-box;\ --webkit-box-sizing: border-box;\ -box-sizing: border-box;\ -display: inline-block;\ -height: 11px;\ -margin-top: -2px;\ -vertical-align: middle;\ -background-image:\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\ -background-repeat: no-repeat, repeat-x;\ -background-position: center center, top left;\ -color: transparent;\ -border: 1px solid black;\ -border-radius: 2px;\ -cursor: pointer;\ -pointer-events: auto;\ -}\ -.ace_dark .ace_fold {\ -}\ -.ace_fold:hover{\ -background-image:\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\ -url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\ -}\ -.ace_tooltip {\ -background-color: #FFF;\ -background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\ -background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\ -border: 1px solid gray;\ -border-radius: 1px;\ -box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\ -color: black;\ -max-width: 100%;\ -padding: 3px 4px;\ -position: fixed;\ -z-index: 999999;\ --moz-box-sizing: border-box;\ --webkit-box-sizing: border-box;\ -box-sizing: border-box;\ -cursor: default;\ -white-space: pre;\ -word-wrap: break-word;\ -line-height: normal;\ -font-style: normal;\ -font-weight: normal;\ -letter-spacing: normal;\ -pointer-events: none;\ -}\ -.ace_folding-enabled > .ace_gutter-cell {\ -padding-right: 13px;\ -}\ -.ace_fold-widget {\ --moz-box-sizing: border-box;\ --webkit-box-sizing: border-box;\ -box-sizing: border-box;\ -margin: 0 -12px 0 1px;\ -display: none;\ -width: 11px;\ -vertical-align: top;\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\ -background-repeat: no-repeat;\ -background-position: center;\ -border-radius: 3px;\ -border: 1px solid transparent;\ -cursor: pointer;\ -}\ -.ace_folding-enabled .ace_fold-widget {\ -display: inline-block; \ -}\ -.ace_fold-widget.ace_end {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\ -}\ -.ace_fold-widget.ace_closed {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\ -}\ -.ace_fold-widget:hover {\ -border: 1px solid rgba(0, 0, 0, 0.3);\ -background-color: rgba(255, 255, 255, 0.2);\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\ -}\ -.ace_fold-widget:active {\ -border: 1px solid rgba(0, 0, 0, 0.4);\ -background-color: rgba(0, 0, 0, 0.05);\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\ -}\ -.ace_dark .ace_fold-widget {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\ -}\ -.ace_dark .ace_fold-widget.ace_end {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\ -}\ -.ace_dark .ace_fold-widget.ace_closed {\ -background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\ -}\ -.ace_dark .ace_fold-widget:hover {\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ -background-color: rgba(255, 255, 255, 0.1);\ -}\ -.ace_dark .ace_fold-widget:active {\ -box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\ -}\ -.ace_fold-widget.ace_invalid {\ -background-color: #FFB4B4;\ -border-color: #DE5555;\ -}\ -.ace_fade-fold-widgets .ace_fold-widget {\ --webkit-transition: opacity 0.4s ease 0.05s;\ -transition: opacity 0.4s ease 0.05s;\ -opacity: 0;\ -}\ -.ace_fade-fold-widgets:hover .ace_fold-widget {\ --webkit-transition: opacity 0.05s ease 0.05s;\ -transition: opacity 0.05s ease 0.05s;\ -opacity:1;\ -}\ -.ace_underline {\ -text-decoration: underline;\ -}\ -.ace_bold {\ -font-weight: bold;\ -}\ -.ace_nobold .ace_bold {\ -font-weight: normal;\ -}\ -.ace_italic {\ -font-style: italic;\ -}\ -.ace_error-marker {\ -background-color: rgba(255, 0, 0,0.2);\ -position: absolute;\ -z-index: 9;\ -}\ -.ace_highlight-marker {\ -background-color: rgba(255, 255, 0,0.2);\ -position: absolute;\ -z-index: 8;\ -}\ -.ace_br1 {border-top-left-radius : 3px;}\ -.ace_br2 {border-top-right-radius : 3px;}\ -.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\ -.ace_br4 {border-bottom-right-radius: 3px;}\ -.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\ -.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\ -.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\ -.ace_br8 {border-bottom-left-radius : 3px;}\ -.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\ -.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\ -.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\ -"; - -dom.importCssString(editorCss, "ace_editor.css"); - -var VirtualRenderer = function(container, theme) { - var _self = this; - - this.container = container || dom.createElement("div"); - this.$keepTextAreaAtCursor = !useragent.isOldIE; - - dom.addCssClass(this.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.onGutterResize.bind(this)); - - 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.$cursorLayer = new CursorLayer(this.content); - this.$horizScroll = false; - this.$vScroll = false; - - this.scrollBar = - this.scrollBarV = new VScrollBar(this.container, this); - this.scrollBarH = new HScrollBar(this.container, this); - this.scrollBarV.addEventListener("scroll", function(e) { - if (!_self.$scrollAnimation) - _self.session.setScrollTop(e.data - _self.scrollMargin.top); - }); - this.scrollBarH.addEventListener("scroll", function(e) { - if (!_self.$scrollAnimation) - _self.session.setScrollLeft(e.data - _self.scrollMargin.left); - }); - - this.scrollTop = 0; - this.scrollLeft = 0; - - this.cursorPos = { - row : 0, - column : 0 - }; - - this.$fontMetrics = new FontMetrics(this.container); - this.$textLayer.$setFontMetrics(this.$fontMetrics); - this.$textLayer.addEventListener("changeCharacterSize", function(e) { - _self.updateCharacterSize(); - _self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height); - _self._signal("changeCharacterSize", e); - }); - - this.$size = { - width: 0, - height: 0, - scrollerHeight: 0, - scrollerWidth: 0, - $dirty: true - }; - - this.layerConfig = { - width : 1, - padding : 0, - firstRow : 0, - firstRowScreen: 0, - lastRow : 0, - lineHeight : 0, - characterWidth : 0, - minHeight : 1, - maxHeight : 1, - offset : 0, - height : 1, - gutterOffset: 1 - }; - - this.scrollMargin = { - left: 0, - right: 0, - top: 0, - bottom: 0, - v: 0, - h: 0 - }; - - this.$loop = new RenderLoop( - this.$renderChanges.bind(this), - this.container.ownerDocument.defaultView - ); - this.$loop.schedule(this.CHANGE_FULL); - - this.updateCharacterSize(); - this.setPadding(4); - config.resetOptions(this); - config._emit("renderer", this); -}; - -(function() { - - 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.updateCharacterSize = function() { - if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) { - this.$allowBoldFonts = this.$textLayer.allowBoldFonts; - this.setStyle("ace_nobold", !this.$allowBoldFonts); - } - - this.layerConfig.characterWidth = - this.characterWidth = this.$textLayer.getCharacterWidth(); - this.layerConfig.lineHeight = - this.lineHeight = this.$textLayer.getLineHeight(); - this.$updatePrintMargin(); - }; - this.setSession = function(session) { - if (this.session) - this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode); - - this.session = session; - if (session && this.scrollMargin.top && session.getScrollTop() <= 0) - session.setScrollTop(-this.scrollMargin.top); - - this.$cursorLayer.setSession(session); - this.$markerBack.setSession(session); - this.$markerFront.setSession(session); - this.$gutterLayer.setSession(session); - this.$textLayer.setSession(session); - if (!session) - return; - - this.$loop.schedule(this.CHANGE_FULL); - this.session.$setFontMetrics(this.$fontMetrics); - this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null; - - this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this); - this.onChangeNewLineMode() - this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode); - }; - this.updateLines = function(firstRow, lastRow, force) { - 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; - } - if (this.$changedLines.lastRow < this.layerConfig.firstRow) { - if (force) - this.$changedLines.lastRow = this.layerConfig.lastRow; - else - return; - } - if (this.$changedLines.firstRow > this.layerConfig.lastRow) - return; - this.$loop.schedule(this.CHANGE_LINES); - }; - - this.onChangeNewLineMode = function() { - this.$loop.schedule(this.CHANGE_TEXT); - this.$textLayer.$updateEolChar(); - }; - - this.onChangeTabSize = function() { - this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER); - this.$textLayer.onChangeTabSize(); - }; - this.updateText = function() { - this.$loop.schedule(this.CHANGE_TEXT); - }; - this.updateFull = function(force) { - if (force) - this.$renderChanges(this.CHANGE_FULL, true); - else - this.$loop.schedule(this.CHANGE_FULL); - }; - this.updateFontSize = function() { - this.$textLayer.checkForSizeChanges(); - }; - - this.$changes = 0; - this.$updateSizeAsync = function() { - if (this.$loop.pending) - this.$size.$dirty = true; - else - this.onResize(); - }; - this.onResize = function(force, gutterWidth, width, height) { - if (this.resizing > 2) - return; - else if (this.resizing > 0) - this.resizing++; - else - this.resizing = force ? 1 : 0; - var el = this.container; - if (!height) - height = el.clientHeight || el.scrollHeight; - if (!width) - width = el.clientWidth || el.scrollWidth; - var changes = this.$updateCachedSize(force, gutterWidth, width, height); - - - if (!this.$size.scrollerHeight || (!width && !height)) - return this.resizing = 0; - - if (force) - this.$gutterLayer.$padding = null; - - if (force) - this.$renderChanges(changes | this.$changes, true); - else - this.$loop.schedule(changes | this.$changes); - - if (this.resizing) - this.resizing = 0; - this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null; - }; - - this.$updateCachedSize = function(force, gutterWidth, width, height) { - height -= (this.$extraHeight || 0); - var changes = 0; - var size = this.$size; - var oldSize = { - width: size.width, - height: size.height, - scrollerHeight: size.scrollerHeight, - scrollerWidth: size.scrollerWidth - }; - if (height && (force || size.height != height)) { - size.height = height; - changes |= this.CHANGE_SIZE; - - size.scrollerHeight = size.height; - if (this.$horizScroll) - size.scrollerHeight -= this.scrollBarH.getHeight(); - this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px"; - - changes = changes | this.CHANGE_SCROLL; - } - - if (width && (force || size.width != width)) { - changes |= this.CHANGE_SIZE; - size.width = width; - - if (gutterWidth == null) - gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; - - this.gutterWidth = gutterWidth; - - this.scrollBarH.element.style.left = - this.scroller.style.left = gutterWidth + "px"; - size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth()); - - this.scrollBarH.element.style.right = - this.scroller.style.right = this.scrollBarV.getWidth() + "px"; - this.scroller.style.bottom = this.scrollBarH.getHeight() + "px"; - - if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force) - changes |= this.CHANGE_FULL; - } - - size.$dirty = !width || !height; - - if (changes) - this._signal("resize", oldSize); - - return changes; - }; - - this.onGutterResize = function() { - var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0; - if (gutterWidth != this.gutterWidth) - this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height); - - if (this.session.getUseWrapMode() && this.adjustWrapLimit()) { - this.$loop.schedule(this.CHANGE_FULL); - } else if (this.$size.$dirty) { - this.$loop.schedule(this.CHANGE_FULL); - } else { - this.$computeLayerConfig(); - this.$loop.schedule(this.CHANGE_MARKER); - } - }; - this.adjustWrapLimit = function() { - var availableWidth = this.$size.scrollerWidth - this.$padding * 2; - var limit = Math.floor(availableWidth / this.characterWidth); - return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn); - }; - this.setAnimatedScroll = function(shouldAnimate){ - this.setOption("animatedScroll", shouldAnimate); - }; - this.getAnimatedScroll = function() { - return this.$animatedScroll; - }; - this.setShowInvisibles = function(showInvisibles) { - this.setOption("showInvisibles", showInvisibles); - }; - this.getShowInvisibles = function() { - return this.getOption("showInvisibles"); - }; - this.getDisplayIndentGuides = function() { - return this.getOption("displayIndentGuides"); - }; - - this.setDisplayIndentGuides = function(display) { - this.setOption("displayIndentGuides", display); - }; - this.setShowPrintMargin = function(showPrintMargin) { - this.setOption("showPrintMargin", showPrintMargin); - }; - this.getShowPrintMargin = function() { - return this.getOption("showPrintMargin"); - }; - this.setPrintMarginColumn = function(showPrintMargin) { - this.setOption("printMarginColumn", showPrintMargin); - }; - this.getPrintMarginColumn = function() { - return this.getOption("printMarginColumn"); - }; - this.getShowGutter = function(){ - return this.getOption("showGutter"); - }; - this.setShowGutter = function(show){ - return this.setOption("showGutter", show); - }; - - this.getFadeFoldWidgets = function(){ - return this.getOption("fadeFoldWidgets") - }; - - this.setFadeFoldWidgets = function(show) { - this.setOption("fadeFoldWidgets", show); - }; - - this.setHighlightGutterLine = function(shouldHighlight) { - this.setOption("highlightGutterLine", shouldHighlight); - }; - - this.getHighlightGutterLine = function() { - return this.getOption("highlightGutterLine"); - }; - - this.$updateGutterLineHighlight = function() { - var pos = this.$cursorLayer.$pixelPos; - var height = this.layerConfig.lineHeight; - if (this.session.getUseWrapMode()) { - var cursor = this.session.selection.getCursor(); - cursor.column = 0; - pos = this.$cursorLayer.getPixelPosition(cursor, true); - height *= this.session.getRowLength(cursor.row); - } - this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px"; - this.$gutterLineHighlight.style.height = height + "px"; - }; - - this.$updatePrintMargin = function() { - if (!this.$showPrintMargin && !this.$printMarginEl) - return; - - if (!this.$printMarginEl) { - var containerEl = dom.createElement("div"); - containerEl.className = "ace_layer ace_print-margin-layer"; - this.$printMarginEl = dom.createElement("div"); - this.$printMarginEl.className = "ace_print-margin"; - containerEl.appendChild(this.$printMarginEl); - this.content.insertBefore(containerEl, this.content.firstChild); - } - - var style = this.$printMarginEl.style; - style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px"; - style.visibility = this.$showPrintMargin ? "visible" : "hidden"; - - if (this.session && this.session.$wrap == -1) - this.adjustWrapLimit(); - }; - this.getContainerElement = function() { - return this.container; - }; - this.getMouseEventTarget = function() { - return this.scroller; - }; - this.getTextAreaContainer = function() { - return this.container; - }; - this.$moveTextAreaToCursor = function() { - if (!this.$keepTextAreaAtCursor) - return; - var config = this.layerConfig; - var posTop = this.$cursorLayer.$pixelPos.top; - var posLeft = this.$cursorLayer.$pixelPos.left; - posTop -= config.offset; - - var style = this.textarea.style; - var h = this.lineHeight; - if (posTop < 0 || posTop > config.height - h) { - style.top = style.left = "0"; - return; - } - - var w = this.characterWidth; - if (this.$composition) { - var val = this.textarea.value.replace(/^\x01+/, ""); - w *= (this.session.$getStringScreenWidth(val)[0]+2); - h += 2; - } - posLeft -= this.scrollLeft; - if (posLeft > this.$size.scrollerWidth - w) - posLeft = this.$size.scrollerWidth - w; - - posLeft += this.gutterWidth; - style.height = h + "px"; - style.width = w + "px"; - style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px"; - style.top = Math.min(posTop, this.$size.height - h) + "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 config = this.layerConfig; - var lastRow = config.lastRow - var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight; - if (top - this.session.getScrollTop() > config.height - config.lineHeight) - return lastRow - 1; - return lastRow; - }; - 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.setScrollMargin = function(top, bottom, left, right) { - var sm = this.scrollMargin; - sm.top = top|0; - sm.bottom = bottom|0; - sm.right = right|0; - sm.left = left|0; - sm.v = sm.top + sm.bottom; - sm.h = sm.left + sm.right; - if (sm.top && this.scrollTop <= 0 && this.session) - this.session.setScrollTop(-sm.top); - this.updateFull(); - }; - this.getHScrollBarAlwaysVisible = function() { - return this.$hScrollBarAlwaysVisible; - }; - this.setHScrollBarAlwaysVisible = function(alwaysVisible) { - this.setOption("hScrollBarAlwaysVisible", alwaysVisible); - }; - this.getVScrollBarAlwaysVisible = function() { - return this.$vScrollBarAlwaysVisible; - }; - this.setVScrollBarAlwaysVisible = function(alwaysVisible) { - this.setOption("vScrollBarAlwaysVisible", alwaysVisible); - }; - - this.$updateScrollBarV = function() { - var scrollHeight = this.layerConfig.maxHeight; - var scrollerHeight = this.$size.scrollerHeight; - if (!this.$maxLines && this.$scrollPastEnd) { - scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd; - if (this.scrollTop > scrollHeight - scrollerHeight) { - scrollHeight = this.scrollTop + scrollerHeight; - this.scrollBarV.scrollTop = null; - } - } - this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v); - this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top); - }; - this.$updateScrollBarH = function() { - this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h); - this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left); - }; - - this.$frozen = false; - this.freeze = function() { - this.$frozen = true; - }; - - this.unfreeze = function() { - this.$frozen = false; - }; - - this.$renderChanges = function(changes, force) { - if (this.$changes) { - changes |= this.$changes; - this.$changes = 0; - } - if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) { - this.$changes |= changes; - return; - } - if (this.$size.$dirty) { - this.$changes |= changes; - return this.onResize(true); - } - if (!this.lineHeight) { - this.$textLayer.checkForSizeChanges(); - } - - this._signal("beforeRender"); - var config = this.layerConfig; - if (changes & this.CHANGE_FULL || - changes & this.CHANGE_SIZE || - changes & this.CHANGE_TEXT || - changes & this.CHANGE_LINES || - changes & this.CHANGE_SCROLL || - changes & this.CHANGE_H_SCROLL - ) { - changes |= this.$computeLayerConfig(); - if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) { - var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight; - if (st > 0) { - this.scrollTop = st; - changes = changes | this.CHANGE_SCROLL; - changes |= this.$computeLayerConfig(); - } - } - config = this.layerConfig; - this.$updateScrollBarV(); - if (changes & this.CHANGE_H_SCROLL) - this.$updateScrollBarH(); - this.$gutterLayer.element.style.marginTop = (-config.offset) + "px"; - this.content.style.marginTop = (-config.offset) + "px"; - this.content.style.width = config.width + 2 * this.$padding + "px"; - this.content.style.height = config.minHeight + "px"; - } - if (changes & this.CHANGE_H_SCROLL) { - this.content.style.marginLeft = -this.scrollLeft + "px"; - this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left"; - } - if (changes & this.CHANGE_FULL) { - this.$textLayer.update(config); - if (this.$showGutter) - this.$gutterLayer.update(config); - this.$markerBack.update(config); - this.$markerFront.update(config); - this.$cursorLayer.update(config); - this.$moveTextAreaToCursor(); - this.$highlightGutterLine && this.$updateGutterLineHighlight(); - this._signal("afterRender"); - return; - } - if (changes & this.CHANGE_SCROLL) { - if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES) - this.$textLayer.update(config); - else - this.$textLayer.scrollLines(config); - - if (this.$showGutter) - this.$gutterLayer.update(config); - this.$markerBack.update(config); - this.$markerFront.update(config); - this.$cursorLayer.update(config); - this.$highlightGutterLine && this.$updateGutterLineHighlight(); - this.$moveTextAreaToCursor(); - this._signal("afterRender"); - return; - } - - if (changes & this.CHANGE_TEXT) { - this.$textLayer.update(config); - if (this.$showGutter) - this.$gutterLayer.update(config); - } - else if (changes & this.CHANGE_LINES) { - if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter) - this.$gutterLayer.update(config); - } - else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) { - if (this.$showGutter) - this.$gutterLayer.update(config); - } - - if (changes & this.CHANGE_CURSOR) { - this.$cursorLayer.update(config); - this.$moveTextAreaToCursor(); - this.$highlightGutterLine && this.$updateGutterLineHighlight(); - } - - if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) { - this.$markerFront.update(config); - } - - if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) { - this.$markerBack.update(config); - } - - this._signal("afterRender"); - }; - - - this.$autosize = function() { - var height = this.session.getScreenLength() * this.lineHeight; - var maxHeight = this.$maxLines * this.lineHeight; - var desiredHeight = Math.min(maxHeight, - Math.max((this.$minLines || 1) * this.lineHeight, height) - ) + this.scrollMargin.v + (this.$extraHeight || 0); - if (this.$horizScroll) - desiredHeight += this.scrollBarH.getHeight(); - if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight) - desiredHeight = this.$maxPixelHeight; - var vScroll = height > maxHeight; - - if (desiredHeight != this.desiredHeight || - this.$size.height != this.desiredHeight || vScroll != this.$vScroll) { - if (vScroll != this.$vScroll) { - this.$vScroll = vScroll; - this.scrollBarV.setVisible(vScroll); - } - - var w = this.container.clientWidth; - this.container.style.height = desiredHeight + "px"; - this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight); - this.desiredHeight = desiredHeight; - - this._signal("autosize"); - } - }; - - this.$computeLayerConfig = function() { - var session = this.session; - var size = this.$size; - - var hideScrollbars = size.height <= 2 * this.lineHeight; - var screenLines = this.session.getScreenLength(); - var maxHeight = screenLines * this.lineHeight; - - var longestLine = this.$getLongestLine(); - - var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible || - size.scrollerWidth - longestLine - 2 * this.$padding < 0); - - var hScrollChanged = this.$horizScroll !== horizScroll; - if (hScrollChanged) { - this.$horizScroll = horizScroll; - this.scrollBarH.setVisible(horizScroll); - } - var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine - if (this.$maxLines && this.lineHeight > 1) - this.$autosize(); - - var offset = this.scrollTop % this.lineHeight; - var minHeight = size.scrollerHeight + this.lineHeight; - - var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd - ? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd - : 0; - maxHeight += scrollPastEnd; - - var sm = this.scrollMargin; - this.session.setScrollTop(Math.max(-sm.top, - Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom))); - - this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft, - longestLine + 2 * this.$padding - size.scrollerWidth + sm.right))); - - var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible || - size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top); - var vScrollChanged = vScrollBefore !== vScroll; - if (vScrollChanged) { - this.$vScroll = vScroll; - this.scrollBarV.setVisible(vScroll); - } - - var lineCount = Math.ceil(minHeight / this.lineHeight) - 1; - var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight)); - var lastRow = firstRow + lineCount; - var firstRowScreen, firstRowHeight; - var lineHeight = this.lineHeight; - firstRow = session.screenToDocumentRow(firstRow, 0); - var foldLine = session.getFoldLine(firstRow); - if (foldLine) { - firstRow = foldLine.start.row; - } - - firstRowScreen = session.documentToScreenRow(firstRow, 0); - firstRowHeight = session.getRowLength(firstRow) * lineHeight; - - lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1); - minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight + - firstRowHeight; - - offset = this.scrollTop - firstRowScreen * lineHeight; - - var changes = 0; - if (this.layerConfig.width != longestLine) - changes = this.CHANGE_H_SCROLL; - if (hScrollChanged || vScrollChanged) { - changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height); - this._signal("scrollbarVisibilityChanged"); - if (vScrollChanged) - longestLine = this.$getLongestLine(); - } - - this.layerConfig = { - width : longestLine, - padding : this.$padding, - firstRow : firstRow, - firstRowScreen: firstRowScreen, - lastRow : lastRow, - lineHeight : lineHeight, - characterWidth : this.characterWidth, - minHeight : minHeight, - maxHeight : maxHeight, - offset : offset, - gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0, - height : this.$size.scrollerHeight - }; - - return changes; - }; - - 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 (lastRow === Infinity) { - if (this.$showGutter) - this.$gutterLayer.update(layerConfig); - this.$textLayer.update(layerConfig); - return; - } - this.$textLayer.updateLines(layerConfig, firstRow, lastRow); - return true; - }; - - this.$getLongestLine = function() { - var charCount = this.session.getScreenWidth(); - if (this.showInvisibles && !this.session.$useWrapMode) - 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.removeGutterDecoration = function(row, className){ - this.$gutterLayer.removeGutterDecoration(row, className); - }; - 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) { - this.scrollCursorIntoView(anchor, offset); - this.scrollCursorIntoView(lead, offset); - }; - this.scrollCursorIntoView = function(cursor, offset, $viewMargin) { - if (this.$size.scrollerHeight === 0) - return; - - var pos = this.$cursorLayer.getPixelPosition(cursor); - - var left = pos.left; - var top = pos.top; - - var topMargin = $viewMargin && $viewMargin.top || 0; - var bottomMargin = $viewMargin && $viewMargin.bottom || 0; - - var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop; - - if (scrollTop + topMargin > top) { - if (offset && scrollTop + topMargin > top + this.lineHeight) - top -= offset * this.$size.scrollerHeight; - if (top === 0) - top = -this.scrollMargin.top; - this.session.setScrollTop(top); - } else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) { - if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight) - 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 = -this.scrollMargin.left; - this.session.setScrollLeft(left); - } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) { - this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth)); - } else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) { - this.session.setScrollLeft(0); - } - }; - 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 h = this.$size.scrollerHeight - this.lineHeight; - var offset = pos.top - h * (alignment || 0); - - this.session.setScrollTop(offset); - return 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) - return; - var _self = this; - - if (fromValue == toValue) - return; - - if (this.$scrollAnimation) { - var oldSteps = this.$scrollAnimation.steps; - if (oldSteps.length) { - fromValue = oldSteps[0]; - if (fromValue == toValue) - return; - } - } - - var steps = _self.$calcSteps(fromValue, toValue); - this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps}; - - clearInterval(this.$timer); - - _self.session.setScrollTop(steps.shift()); - _self.session.$scrollTop = toValue; - this.$timer = setInterval(function() { - if (steps.length) { - _self.session.setScrollTop(steps.shift()); - _self.session.$scrollTop = toValue; - } else if (toValue != null) { - _self.session.$scrollTop = -1; - _self.session.setScrollTop(toValue); - toValue = null; - } else { - _self.$timer = clearInterval(_self.$timer); - _self.$scrollAnimation = null; - callback && callback(); - } - }, 10); - }; - this.scrollToY = function(scrollTop) { - if (this.scrollTop !== scrollTop) { - this.$loop.schedule(this.CHANGE_SCROLL); - this.scrollTop = scrollTop; - } - }; - this.scrollToX = function(scrollLeft) { - if (this.scrollLeft !== scrollLeft) - this.scrollLeft = scrollLeft; - this.$loop.schedule(this.CHANGE_H_SCROLL); - }; - this.scrollTo = function(x, y) { - this.session.setScrollTop(y); - this.session.setScrollLeft(y); - }; - 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() >= 1 - this.scrollMargin.top) - return true; - if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight - - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom) - return true; - if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left) - return true; - if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth - - this.layerConfig.width < -1 + this.scrollMargin.right) - return true; - }; - - 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 = (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.setTheme = function(theme, cb) { - var _self = this; - this.$themeId = theme; - _self._dispatchEvent('themeChange',{theme:theme}); - - if (!theme || typeof theme == "string") { - var moduleName = theme || this.$options.theme.initialValue; - config.loadModule(["theme", moduleName], afterLoad); - } else { - afterLoad(theme); - } - - function afterLoad(module) { - if (_self.$themeId != theme) - return cb && cb(); - if (!module || !module.cssClass) - throw new Error("couldn't load module " + theme + " or it didn't call define"); - dom.importCssString( - module.cssText, - module.cssClass, - _self.container.ownerDocument - ); - - if (_self.theme) - dom.removeCssClass(_self.container, _self.theme.cssClass); - - var padding = "padding" in module ? module.padding - : "padding" in (_self.theme || {}) ? 4 : _self.$padding; - if (_self.$padding && padding != _self.$padding) - _self.setPadding(padding); - _self.$theme = module.cssClass; - - _self.theme = module; - dom.addCssClass(_self.container, module.cssClass); - dom.setCssClass(_self.container, "ace_dark", module.isDark); - if (_self.$size) { - _self.$size.width = 0; - _self.$updateSizeAsync(); - } - - _self._dispatchEvent('themeLoaded', {theme:module}); - cb && cb(); - } - }; - this.getTheme = function() { - return this.$themeId; - }; - this.setStyle = function(style, include) { - dom.setCssClass(this.container, style, include !== false); - }; - this.unsetStyle = function(style) { - dom.removeCssClass(this.container, style); - }; - - this.setCursorStyle = function(style) { - if (this.scroller.style.cursor != style) - this.scroller.style.cursor = style; - }; - this.setMouseCursor = function(cursorStyle) { - this.scroller.style.cursor = cursorStyle; - }; - this.destroy = function() { - this.$textLayer.destroy(); - this.$cursorLayer.destroy(); - }; - -}).call(VirtualRenderer.prototype); - - -config.defineOptions(VirtualRenderer.prototype, "renderer", { - animatedScroll: {initialValue: false}, - showInvisibles: { - set: function(value) { - if (this.$textLayer.setShowInvisibles(value)) - this.$loop.schedule(this.CHANGE_TEXT); - }, - initialValue: false - }, - showPrintMargin: { - set: function() { this.$updatePrintMargin(); }, - initialValue: true - }, - printMarginColumn: { - set: function() { this.$updatePrintMargin(); }, - initialValue: 80 - }, - printMargin: { - set: function(val) { - if (typeof val == "number") - this.$printMarginColumn = val; - this.$showPrintMargin = !!val; - this.$updatePrintMargin(); - }, - get: function() { - return this.$showPrintMargin && this.$printMarginColumn; - } - }, - showGutter: { - set: function(show){ - this.$gutter.style.display = show ? "block" : "none"; - this.$loop.schedule(this.CHANGE_FULL); - this.onGutterResize(); - }, - initialValue: true - }, - fadeFoldWidgets: { - set: function(show) { - dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show); - }, - initialValue: false - }, - showFoldWidgets: { - set: function(show) {this.$gutterLayer.setShowFoldWidgets(show)}, - initialValue: true - }, - showLineNumbers: { - set: function(show) { - this.$gutterLayer.setShowLineNumbers(show); - this.$loop.schedule(this.CHANGE_GUTTER); - }, - initialValue: true - }, - displayIndentGuides: { - set: function(show) { - if (this.$textLayer.setDisplayIndentGuides(show)) - this.$loop.schedule(this.CHANGE_TEXT); - }, - initialValue: true - }, - highlightGutterLine: { - set: function(shouldHighlight) { - if (!this.$gutterLineHighlight) { - this.$gutterLineHighlight = dom.createElement("div"); - this.$gutterLineHighlight.className = "ace_gutter-active-line"; - this.$gutter.appendChild(this.$gutterLineHighlight); - return; - } - - this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none"; - if (this.$cursorLayer.$pixelPos) - this.$updateGutterLineHighlight(); - }, - initialValue: false, - value: true - }, - hScrollBarAlwaysVisible: { - set: function(val) { - if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll) - this.$loop.schedule(this.CHANGE_SCROLL); - }, - initialValue: false - }, - vScrollBarAlwaysVisible: { - set: function(val) { - if (!this.$vScrollBarAlwaysVisible || !this.$vScroll) - this.$loop.schedule(this.CHANGE_SCROLL); - }, - initialValue: false - }, - fontSize: { - set: function(size) { - if (typeof size == "number") - size = size + "px"; - this.container.style.fontSize = size; - this.updateFontSize(); - }, - initialValue: 12 - }, - fontFamily: { - set: function(name) { - this.container.style.fontFamily = name; - this.updateFontSize(); - } - }, - maxLines: { - set: function(val) { - this.updateFull(); - } - }, - minLines: { - set: function(val) { - this.updateFull(); - } - }, - maxPixelHeight: { - set: function(val) { - this.updateFull(); - }, - initialValue: 0 - }, - scrollPastEnd: { - set: function(val) { - val = +val || 0; - if (this.$scrollPastEnd == val) - return; - this.$scrollPastEnd = val; - this.$loop.schedule(this.CHANGE_SCROLL); - }, - initialValue: 0, - handlesSet: true - }, - fixedWidthGutter: { - set: function(val) { - this.$gutterLayer.$fixedWidth = !!val; - this.$loop.schedule(this.CHANGE_GUTTER); - } - }, - theme: { - set: function(val) { this.setTheme(val) }, - get: function() { return this.$themeId || this.theme; }, - initialValue: "./theme/textmate", - handlesSet: true - } -}); - -exports.VirtualRenderer = VirtualRenderer; -}); - -ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var net = acequire("../lib/net"); -var EventEmitter = acequire("../lib/event_emitter").EventEmitter; -var config = acequire("../config"); - -var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl) { - this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); - this.changeListener = this.changeListener.bind(this); - this.onMessage = this.onMessage.bind(this); - if (acequire.nameToUrl && !acequire.toUrl) - acequire.toUrl = acequire.nameToUrl; - - if (config.get("packaged") || !acequire.toUrl) { - workerUrl = workerUrl || config.moduleUrl(mod.id, "worker") - } else { - var normalizePath = this.$normalizePath; - workerUrl = workerUrl || normalizePath(acequire.toUrl("ace/worker/worker.js", null, "_")); - - var tlns = {}; - topLevelNamespaces.forEach(function(ns) { - tlns[ns] = normalizePath(acequire.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, "")); - }); - } - - try { - var workerSrc = mod.src; - var Blob = __webpack_require__(56); - var blob = new Blob([ workerSrc ], { type: 'application/javascript' }); - var blobUrl = (window.URL || window.webkitURL).createObjectURL(blob); - - this.$worker = new Worker(blobUrl); - - } catch(e) { - if (e instanceof window.DOMException) { - var blob = this.$workerBlob(workerUrl); - var URL = window.URL || window.webkitURL; - var blobURL = URL.createObjectURL(blob); - - this.$worker = new Worker(blobURL); - URL.revokeObjectURL(blobURL); - } else { - throw e; - } - } - this.$worker.postMessage({ - init : true, - tlns : tlns, - module : mod.id, - classname : classname - }); - - this.callbackId = 1; - this.callbacks = {}; - - this.$worker.onmessage = this.onMessage; -}; - -(function(){ - - oop.implement(this, EventEmitter); - - this.onMessage = function(e) { - var msg = e.data; - switch(msg.type) { - case "event": - this._signal(msg.name, {data: msg.data}); - break; - case "call": - var callback = this.callbacks[msg.id]; - if (callback) { - callback(msg.data); - delete this.callbacks[msg.id]; - } - break; - case "error": - this.reportError(msg.data); - break; - case "log": - window.console && console.log && console.log.apply(console, msg.data); - break; - } - }; - - this.reportError = function(err) { - window.console && console.error && console.error(err); - }; - - this.$normalizePath = function(path) { - return net.qualifyURL(path); - }; - - this.terminate = function() { - this._signal("terminate", {}); - this.deltaQueue = null; - this.$worker.terminate(); - this.$worker = null; - if (this.$doc) - this.$doc.off("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 { - this.$worker.postMessage({event: event, data: {data: data.data}}); - } - catch(ex) { - console.error(ex.stack); - } - }; - - 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(delta) { - if (!this.deltaQueue) { - this.deltaQueue = []; - setTimeout(this.$sendDeltaQueue, 0); - } - if (delta.action == "insert") - this.deltaQueue.push(delta.start, delta.lines); - else - this.deltaQueue.push(delta.start, delta.end); - }; - - this.$sendDeltaQueue = function() { - var q = this.deltaQueue; - if (!q) return; - this.deltaQueue = null; - if (q.length > 50 && q.length > this.$doc.getLength() >> 1) { - this.call("setValue", [this.$doc.getValue()]); - } else - this.emit("change", {data: q}); - }; - - this.$workerBlob = function(workerUrl) { - var script = "importScripts('" + net.qualifyURL(workerUrl) + "');"; - try { - return new Blob([script], {"type": "application/javascript"}); - } catch (e) { // Backwards-compatibility - var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder; - var blobBuilder = new BlobBuilder(); - blobBuilder.append(script); - return blobBuilder.getBlob("application/javascript"); - } - }; - -}).call(WorkerClient.prototype); - - -var UIWorkerClient = function(topLevelNamespaces, mod, classname) { - this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this); - this.changeListener = this.changeListener.bind(this); - this.callbackId = 1; - this.callbacks = {}; - this.messageBuffer = []; - - var main = null; - var emitSync = false; - var sender = Object.create(EventEmitter); - var _self = this; - - this.$worker = {}; - this.$worker.terminate = function() {}; - this.$worker.postMessage = function(e) { - _self.messageBuffer.push(e); - if (main) { - if (emitSync) - setTimeout(processNext); - else - processNext(); - } - }; - this.setEmitSync = function(val) { emitSync = val }; - - var processNext = function() { - var msg = _self.messageBuffer.shift(); - if (msg.command) - main[msg.command].apply(main, msg.args); - else if (msg.event) - sender._signal(msg.event, msg.data); - }; - - sender.postMessage = function(msg) { - _self.onMessage({data: msg}); - }; - sender.callback = function(data, callbackId) { - this.postMessage({type: "call", id: callbackId, data: data}); - }; - sender.emit = function(name, data) { - this.postMessage({type: "event", name: name, data: data}); - }; - - config.loadModule(["worker", mod], function(Main) { - main = new Main[classname](sender); - while (_self.messageBuffer.length) - processNext(); - }); -}; - -UIWorkerClient.prototype = WorkerClient.prototype; - -exports.UIWorkerClient = UIWorkerClient; -exports.WorkerClient = WorkerClient; - -}); - -ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("./range").Range; -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var oop = acequire("./lib/oop"); - -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; - 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; - - this.selectionBefore = session.selection.toJSON(); - if (session.selection.inMultiSelectMode) - session.selection.toSingleRange(); - - this.pos = doc.createAnchor(this.$pos.row, this.$pos.column); - var pos = this.pos; - pos.$insertRight = true; - pos.detach(); - pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false); - this.others = []; - this.$others.forEach(function(other) { - var anchor = doc.createAnchor(other.row, other.column); - anchor.$insertRight = true; - anchor.detach(); - _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); - }); - }; - this.hideOtherMarkers = function() { - if (!this.othersActive) return; - this.othersActive = false; - for (var i = 0; i < this.others.length; i++) { - this.session.removeMarker(this.others[i].markerId); - } - }; - this.onUpdate = function(delta) { - if (this.$updating) - return this.updateAnchors(delta); - - var range = delta; - if (range.start.row !== range.end.row) return; - if (range.start.row !== this.pos.row) return; - this.$updating = true; - var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column; - var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1; - var distanceFromStart = range.start.column - this.pos.column; - - this.updateAnchors(delta); - - if (inMainRange) - this.length += lengthDiff; - - if (inMainRange && !this.session.$fromUndo) { - if (delta.action === 'insert') { - for (var i = this.others.length - 1; i >= 0; i--) { - var otherPos = this.others[i]; - var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; - this.doc.insertMergedLines(newPos, delta.lines); - } - } else if (delta.action === 'remove') { - for (var i = this.others.length - 1; i >= 0; i--) { - var otherPos = this.others[i]; - var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart}; - this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff)); - } - } - } - - this.$updating = false; - this.updateMarkers(); - }; - - this.updateAnchors = function(delta) { - this.pos.onChange(delta); - for (var i = this.others.length; i--;) - this.others[i].onChange(delta); - this.updateMarkers(); - }; - - this.updateMarkers = function() { - if (this.$updating) - return; - var _self = this; - var session = this.session; - var updateMarker = function(pos, className) { - session.removeMarker(pos.markerId); - pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false); - }; - updateMarker(this.pos, this.mainClass); - for (var i = this.others.length; i--;) - updateMarker(this.others[i], this.othersClass); - }; - - this.onCursorChange = function(event) { - if (this.$updating || !this.session) return; - var pos = this.session.selection.getCursor(); - if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) { - this.showOtherMarkers(); - this._emit("cursorEnter", event); - } else { - this.hideOtherMarkers(); - this._emit("cursorLeave", event); - } - }; - this.detach = function() { - this.session.removeMarker(this.pos && this.pos.markerId); - this.hideOtherMarkers(); - this.doc.removeEventListener("change", this.$onUpdate); - this.session.selection.removeEventListener("changeCursor", this.$onCursorChange); - this.session.setUndoSelect(true); - this.session = null; - }; - this.cancel = function() { - if (this.$undoStackDepth === -1) - return; - var undoManager = this.session.getUndoManager(); - var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth; - for (var i = 0; i < undosRequired; i++) { - undoManager.undo(true); - } - if (this.selectionBefore) - this.session.selection.fromJSON(this.selectionBefore); - }; -}).call(PlaceHolder.prototype); - - -exports.PlaceHolder = PlaceHolder; -}); - -ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) { - -var event = acequire("../lib/event"); -var useragent = acequire("../lib/useragent"); -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 = ev.ctrlKey; - var accel = e.getAccelKey(); - var button = e.getButton(); - - if (ctrl && useragent.isMac) - button = ev.button; - - if (e.editor.inMultiSelectMode && button == 2) { - e.editor.textInput.onContextMenu(e.domEvent); - return; - } - - if (!ctrl && !alt && !accel) { - if (button === 0 && e.editor.inMultiSelectMode) - e.editor.exitMultiSelectMode(); - return; - } - - if (button !== 0) - 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 session = editor.session; - var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY); - var screenCursor = screenAnchor; - - var selectionMode; - if (editor.$mouseHandler.$enableJumpToDef) { - if (ctrl && alt || accel && alt) - selectionMode = shift ? "block" : "add"; - else if (alt && editor.$blockSelectEnabled) - selectionMode = "block"; - } else { - if (accel && !alt) { - selectionMode = "add"; - if (!isMultiSelect && shift) - return; - } else if (alt && editor.$blockSelectEnabled) { - selectionMode = "block"; - } - } - - if (selectionMode && useragent.isMac && ev.ctrlKey) { - editor.$mouseHandler.cancelContextMenu(); - } - - if (selectionMode == "add") { - if (!isMultiSelect && inSelection) - return; // dragging - - if (!isMultiSelect) { - var range = selection.toOrientedRange(); - editor.addSelectionMarker(range); - } - - var oldRange = selection.rangeList.rangeAtPoint(pos); - - - editor.$blockScrolling++; - editor.inVirtualSelectionMode = true; - - if (shift) { - oldRange = null; - range = selection.ranges[0] || range; - editor.removeSelectionMarker(range); - } - editor.once("mouseup", function() { - var tmpSel = selection.toOrientedRange(); - - if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor)) - selection.substractPoint(tmpSel.cursor); - else { - if (shift) { - selection.substractPoint(range.cursor); - } else if (range) { - editor.removeSelectionMarker(range); - selection.addRange(range); - } - selection.addRange(tmpSel); - } - editor.$blockScrolling--; - editor.inVirtualSelectionMode = false; - }); - - } else if (selectionMode == "block") { - e.stop(); - editor.inVirtualSelectionMode = true; - var initialRange; - var rectSel = []; - 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.lead)) - return; - screenCursor = newCursor; - - editor.$blockScrolling++; - editor.selection.moveToPosition(cursor); - editor.renderer.scrollCursorIntoView(); - - editor.removeSelectionMarkers(rectSel); - rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor); - if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty()) - rectSel[0] = editor.$mouseHandler.$clickSelection.clone(); - rectSel.forEach(editor.addSelectionMarker, editor); - editor.updateSelectionMarkers(); - editor.$blockScrolling--; - }; - editor.$blockScrolling++; - if (isMultiSelect && !accel) { - selection.toSingleRange(); - } else if (!isMultiSelect && accel) { - initialRange = selection.toOrientedRange(); - editor.addSelectionMarker(initialRange); - } - - if (shift) - screenAnchor = session.documentToScreenPosition(selection.lead); - else - selection.moveToPosition(pos); - editor.$blockScrolling--; - - screenCursor = {row: -1, column: -1}; - - var onMouseSelectionEnd = function(e) { - clearInterval(timerId); - editor.removeSelectionMarkers(rectSel); - if (!rectSel.length) - rectSel = [selection.toOrientedRange()]; - editor.$blockScrolling++; - if (initialRange) { - editor.removeSelectionMarker(initialRange); - selection.toSingleRange(initialRange); - } - for (var i = 0; i < rectSel.length; i++) - selection.addRange(rectSel[i]); - editor.inVirtualSelectionMode = false; - editor.$mouseHandler.$clickSelection = null; - editor.$blockScrolling--; - }; - - var onSelectionInterval = blockSelect; - - event.capture(editor.container, onMouseSelection, onMouseSelectionEnd); - var timerId = setInterval(function() {onSelectionInterval();}, 20); - - return e.preventDefault(); - } -} - - -exports.onMouseDown = onMouseDown; - -}); - -ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(acequire, exports, module) { -exports.defaultCommands = [{ - name: "addCursorAbove", - exec: function(editor) { editor.selectMoreLines(-1); }, - bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "addCursorBelow", - exec: function(editor) { editor.selectMoreLines(1); }, - bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "addCursorAboveSkipCurrent", - exec: function(editor) { editor.selectMoreLines(-1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "addCursorBelowSkipCurrent", - exec: function(editor) { editor.selectMoreLines(1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectMoreBefore", - exec: function(editor) { editor.selectMore(-1); }, - bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectMoreAfter", - exec: function(editor) { editor.selectMore(1); }, - bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectNextBefore", - exec: function(editor) { editor.selectMore(-1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "selectNextAfter", - exec: function(editor) { editor.selectMore(1, true); }, - bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"}, - scrollIntoView: "cursor", - readOnly: true -}, { - name: "splitIntoLines", - exec: function(editor) { editor.multiSelect.splitIntoLines(); }, - bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"}, - readOnly: true -}, { - name: "alignCursors", - exec: function(editor) { editor.alignCursors(); }, - bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"}, - scrollIntoView: "cursor" -}, { - name: "findAll", - exec: function(editor) { editor.findAll(); }, - bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"}, - scrollIntoView: "cursor", - readOnly: true -}]; -exports.multiSelectCommands = [{ - name: "singleSelection", - bindKey: "esc", - exec: function(editor) { editor.exitMultiSelectMode(); }, - scrollIntoView: "cursor", - readOnly: true, - isAvailable: function(editor) {return editor && editor.inMultiSelectMode} -}]; - -var HashHandler = acequire("../keyboard/hash_handler").HashHandler; -exports.keyboardHandler = new HashHandler(exports.multiSelectCommands); - -}); - -ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(acequire, exports, module) { - -var RangeList = acequire("./range_list").RangeList; -var Range = acequire("./range").Range; -var Selection = acequire("./selection").Selection; -var onMouseDown = acequire("./mouse/multi_select_handler").onMouseDown; -var event = acequire("./lib/event"); -var lang = acequire("./lib/lang"); -var commands = acequire("./commands/multi_select_commands"); -exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands); -var Search = acequire("./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); -} -var EditSession = acequire("./edit_session").EditSession; -(function() { - this.getSelectionMarkers = function() { - return this.$selectionMarkers; - }; -}).call(EditSession.prototype); -(function() { - this.ranges = null; - this.rangeList = null; - this.addRange = function(range, $blockChangeEvents) { - if (!range) - return; - - if (!this.inMultiSelectMode && this.rangeCount === 0) { - var oldRange = this.toOrientedRange(); - this.rangeList.add(oldRange); - this.rangeList.add(range); - if (this.rangeList.ranges.length != 2) { - this.rangeList.removeAll(); - return $blockChangeEvents || this.fromOrientedRange(range); - } - this.rangeList.removeAll(); - 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._signal("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._signal("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._signal("removeRange", {ranges: removed}); - - if (this.rangeCount === 0 && this.inMultiSelectMode) { - this.inMultiSelectMode = false; - this._signal("singleSelect"); - this.session.$undoSelect = true; - this.rangeList.detach(this.session); - } - - lastRange = lastRange || this.ranges[0]; - if (lastRange && !lastRange.isEqual(this.getRange())) - this.fromOrientedRange(lastRange); - }; - this.$initRangeList = function() { - if (this.rangeList) - return; - - this.rangeList = new RangeList(); - this.ranges = []; - this.rangeCount = 0; - }; - this.getAllRanges = function() { - return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()]; - }; - - 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 isBackwards = this.isBackwards(); - var startRow = range.start.row; - var endRow = range.end.row; - if (startRow == endRow) { - if (isBackwards) - var start = range.end, end = range.start; - else - var start = range.start, end = range.end; - - this.addRange(Range.fromPoints(end, end)); - this.addRange(Range.fromPoints(start, start)); - 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); -var Editor = acequire("./editor").Editor; -(function() { - 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("ace_multiselect"); - this.keyBinding.addKeyboardHandler(commands.keyboardHandler); - this.commands.setDefaultHandler("exec", this.$onMultiSelectExec); - - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - }; - - this.$onSingleSelect = function(e) { - if (this.session.multiSelect.inVirtualMode) - return; - this.inMultiSelectMode = false; - - this.unsetStyle("ace_multiselect"); - this.keyBinding.removeKeyboardHandler(commands.keyboardHandler); - - this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec); - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - this._emit("changeSelection"); - }; - - this.$onMultiSelectExec = function(e) { - var command = e.command; - var editor = e.editor; - if (!editor.multiSelect) - return; - if (!command.multiSelectAction) { - var result = command.exec(editor, e.args || {}); - editor.multiSelect.addRange(editor.multiSelect.toOrientedRange()); - editor.multiSelect.mergeOverlappingRanges(); - } else if (command.multiSelectAction == "forEach") { - result = editor.forEachSelection(command, e.args); - } else if (command.multiSelectAction == "forEachLine") { - result = editor.forEachSelection(command, e.args, true); - } else if (command.multiSelectAction == "single") { - editor.exitMultiSelectMode(); - result = command.exec(editor, e.args || {}); - } else { - result = command.multiSelectAction(editor, e.args || {}); - } - return result; - }; - this.forEachSelection = function(cmd, args, options) { - if (this.inVirtualSelectionMode) - return; - var keepOrder = options && options.keepOrder; - var $byLines = options == true || options && options.$byLines - var session = this.session; - var selection = this.selection; - var rangeList = selection.rangeList; - var ranges = (keepOrder ? selection : rangeList).ranges; - var result; - - if (!ranges.length) - return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); - - var reg = selection._eventRegistry; - selection._eventRegistry = {}; - - var tmpSel = new Selection(session); - this.inVirtualSelectionMode = true; - for (var i = ranges.length; i--;) { - if ($byLines) { - while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row) - i--; - } - tmpSel.fromOrientedRange(ranges[i]); - tmpSel.index = i; - this.selection = session.selection = tmpSel; - var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {}); - if (!result && cmdResult !== undefined) - result = cmdResult; - tmpSel.toOrientedRange(ranges[i]); - } - tmpSel.detach(); - - this.selection = session.selection = selection; - this.inVirtualSelectionMode = false; - selection._eventRegistry = reg; - selection.mergeOverlappingRanges(); - - var anim = this.renderer.$scrollAnimation; - this.onCursorChange(); - this.onSelectionChange(); - if (anim && anim.from == anim.to) - this.renderer.animateScrolling(anim.from); - - return result; - }; - this.exitMultiSelectMode = function() { - if (!this.inMultiSelectMode || this.inVirtualSelectionMode) - return; - this.multiSelect.toSingleRange(); - }; - - this.getSelectedText = function() { - var text = ""; - if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { - var ranges = this.multiSelect.rangeList.ranges; - var buf = []; - for (var i = 0; i < ranges.length; i++) { - buf.push(this.session.getTextRange(ranges[i])); - } - var nl = this.session.getDocument().getNewLineCharacter(); - text = buf.join(nl); - if (text.length == (buf.length - 1) * nl.length) - text = ""; - } else if (!this.selection.isEmpty()) { - text = this.session.getTextRange(this.getSelectionRange()); - } - return text; - }; - - this.$checkMultiselectChange = function(e, anchor) { - if (this.inMultiSelectMode && !this.inVirtualSelectionMode) { - var range = this.multiSelect.ranges[0]; - if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor) - return; - var pos = anchor == this.multiSelect.anchor - ? range.cursor == range.start ? range.end : range.start - : range.cursor; - if (pos.row != anchor.row - || this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column) - this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange()); - } - }; - this.findAll = function(needle, options, additive) { - options = options || {}; - options.needle = needle || options.needle; - if (options.needle == undefined) { - var range = this.selection.isEmpty() - ? this.selection.getWordRange() - : this.selection.getRange(); - options.needle = this.session.getTextRange(range); - } - 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); - if (range && selection.rangeList.rangeAtPoint(range.start)) - selection.addRange(range, true); - - this.$blockScrolling -= 1; - - return ranges.length; - }; - 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; - } - }; - this.selectMore = function(dir, skip, stopAtFirst) { - var session = this.session; - var sel = session.multiSelect; - - var range = sel.toOrientedRange(); - if (range.isEmpty()) { - range = session.getWordRange(range.start.row, range.start.column); - range.cursor = dir == -1 ? range.start : range.end; - this.multiSelect.addRange(range); - if (stopAtFirst) - return; - } - var needle = session.getTextRange(range); - - var newRange = find(session, needle, dir); - if (newRange) { - newRange.cursor = dir == -1 ? newRange.start : newRange.end; - this.$blockScrolling += 1; - this.session.unfold(newRange); - this.multiSelect.addRange(newRange); - this.$blockScrolling -= 1; - this.renderer.scrollCursorIntoView(null, 0.5); - } - if (skip) - this.multiSelect.substractPoint(range.cursor); - }; - this.alignCursors = function() { - var session = this.session; - var sel = session.multiSelect; - var ranges = sel.ranges; - var row = -1; - var sameRowRanges = ranges.filter(function(r) { - if (r.cursor.row == row) - return true; - row = r.cursor.row; - }); - - if (!ranges.length || sameRowRanges.length == ranges.length - 1) { - var range = this.selection.getRange(); - var fr = range.start.row, lr = range.end.row; - var guessRange = fr == lr; - if (guessRange) { - var max = this.session.getLength(); - var line; - do { - line = this.session.getLine(lr); - } while (/[=:]/.test(line) && ++lr < max); - do { - line = this.session.getLine(fr); - } while (/[=:]/.test(line) && --fr > 0); - - if (fr < 0) fr = 0; - if (lr >= max) lr = max - 1; - } - var lines = this.session.removeFullLines(fr, lr); - lines = this.$reAlignText(lines, guessRange); - this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n"); - if (!guessRange) { - range.start.column = 0; - range.end.column = lines[lines.length - 1].length; - } - this.selection.setRange(range); - } else { - sameRowRanges.forEach(function(r) { - sel.substractPoint(r.cursor); - }); - - var maxCol = 0; - var minSpace = Infinity; - var spaceOffsets = ranges.map(function(r) { - var p = r.cursor; - var line = session.getLine(p.row); - var spaceOffset = line.substr(p.column).search(/\S/g); - if (spaceOffset == -1) - spaceOffset = 0; - - if (p.column > maxCol) - maxCol = p.column; - if (spaceOffset < minSpace) - minSpace = spaceOffset; - return spaceOffset; - }); - ranges.forEach(function(r, i) { - var p = r.cursor; - var l = maxCol - p.column; - var d = spaceOffsets[i] - minSpace; - if (l > d) - session.insert(p, lang.stringRepeat(" ", l - d)); - else - session.remove(new Range(p.row, p.column, p.row, p.column - l + d)); - - r.start.column = r.end.column = maxCol; - r.start.row = r.end.row = p.row; - r.cursor = r.end; - }); - sel.fromOrientedRange(ranges[0]); - this.renderer.updateCursor(); - this.renderer.updateBackMarkers(); - } - }; - - this.$reAlignText = function(lines, forceLeft) { - var isLeftAligned = true, isRightAligned = true; - var startW, textW, endW; - - return lines.map(function(line) { - var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/); - if (!m) - return [line]; - - if (startW == null) { - startW = m[1].length; - textW = m[2].length; - endW = m[3].length; - return m; - } - - if (startW + textW + endW != m[1].length + m[2].length + m[3].length) - isRightAligned = false; - if (startW != m[1].length) - isLeftAligned = false; - - if (startW > m[1].length) - startW = m[1].length; - if (textW < m[2].length) - textW = m[2].length; - if (endW > m[3].length) - endW = m[3].length; - - return m; - }).map(forceLeft ? alignLeft : - isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign); - - function spaces(n) { - return lang.stringRepeat(" ", n); - } - - function alignLeft(m) { - return !m[2] ? m[0] : spaces(startW) + m[2] - + spaces(textW - m[2].length + endW) - + m[4].replace(/^([=:])\s+/, "$1 "); - } - function alignRight(m) { - return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2] - + spaces(endW, " ") - + m[4].replace(/^([=:])\s+/, "$1 "); - } - function unAlign(m) { - return !m[2] ? m[0] : spaces(startW) + m[2] - + spaces(endW) - + m[4].replace(/^([=:])\s+/, "$1 "); - } - }; -}).call(Editor.prototype); - - -function isSamePoint(p1, p2) { - return p1.row == p2.row && p1.column == p2.column; -} -exports.onSessionChange = function(e) { - var session = e.session; - if (session && !session.multiSelect) { - session.$selectionMarkers = []; - session.selection.$initRangeList(); - session.multiSelect = session.selection; - } - this.multiSelect = session && session.multiSelect; - - var oldSession = e.oldSession; - if (oldSession) { - oldSession.multiSelect.off("addRange", this.$onAddRange); - oldSession.multiSelect.off("removeRange", this.$onRemoveRange); - oldSession.multiSelect.off("multiSelect", this.$onMultiSelect); - oldSession.multiSelect.off("singleSelect", this.$onSingleSelect); - oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange); - oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange); - } - - if (session) { - session.multiSelect.on("addRange", this.$onAddRange); - session.multiSelect.on("removeRange", this.$onRemoveRange); - session.multiSelect.on("multiSelect", this.$onMultiSelect); - session.multiSelect.on("singleSelect", this.$onSingleSelect); - session.multiSelect.lead.on("change", this.$checkMultiselectChange); - session.multiSelect.anchor.on("change", this.$checkMultiselectChange); - } - - if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) { - if (session.selection.inMultiSelectMode) - this.$onMultiSelect(); - else - this.$onSingleSelect(); - } -}; -function MultiSelect(editor) { - if (editor.$multiselectOnSessionChange) - return; - editor.$onAddRange = editor.$onAddRange.bind(editor); - editor.$onRemoveRange = editor.$onRemoveRange.bind(editor); - editor.$onMultiSelect = editor.$onMultiSelect.bind(editor); - editor.$onSingleSelect = editor.$onSingleSelect.bind(editor); - editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor); - editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor); - - editor.$multiselectOnSessionChange(editor); - editor.on("changeSession", editor.$multiselectOnSessionChange); - - editor.on("mousedown", onMouseDown); - editor.commands.addCommands(commands.defaultCommands); - - addAltCursorListeners(editor); -} - -function addAltCursorListeners(editor){ - var el = editor.textInput.getElement(); - var altCursor = false; - event.addListener(el, "keydown", function(e) { - var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey); - if (editor.$blockSelectEnabled && altDown) { - if (!altCursor) { - editor.renderer.setMouseCursor("crosshair"); - altCursor = true; - } - } else if (altCursor) { - reset(); - } - }); - - event.addListener(el, "keyup", reset); - event.addListener(el, "blur", reset); - function reset(e) { - if (altCursor) { - editor.renderer.setMouseCursor(""); - altCursor = false; - } - } -} - -exports.MultiSelect = MultiSelect; - - -acequire("./config").defineOptions(Editor.prototype, "editor", { - enableMultiselect: { - set: function(val) { - MultiSelect(this); - if (val) { - this.on("changeSession", this.$multiselectOnSessionChange); - this.on("mousedown", onMouseDown); - } else { - this.off("changeSession", this.$multiselectOnSessionChange); - this.off("mousedown", onMouseDown); - } - }, - value: true - }, - enableBlockSelect: { - set: function(val) { - this.$blockSelectEnabled = val; - }, - value: true - } -}); - - - -}); - -ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("../../range").Range; - -var FoldMode = exports.FoldMode = function() {}; - -(function() { - - this.foldingStartMarker = null; - this.foldingStopMarker = null; - 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 line = session.getLine(row); - var startLevel = line.search(re); - if (startLevel == -1) - return; - - var startColumn = column || line.length; - var maxRow = session.getLength(); - var startRow = row; - var endRow = row; - - while (++row < maxRow) { - var level = session.getLine(row).search(re); - - if (level == -1) - 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) { - var start = {row: row, column: column + 1}; - var end = session.$findClosingBracket(bracket, start, typeRe); - if (!end) - return; - - var fw = session.foldWidgets[end.row]; - if (fw == null) - fw = session.getFoldWidget(end.row); - - if (fw == "start" && end.row > start.row) { - end.row --; - end.column = session.getLine(end.row).length; - } - return Range.fromPoints(start, end); - }; - - this.closingBracketBlock = function(session, bracket, row, column, typeRe) { - var end = {row: row, column: column}; - var start = session.$findOpeningBracket(bracket, end); - - if (!start) - return; - - start.column++; - end.column--; - - return Range.fromPoints(start, end); - }; -}).call(FoldMode.prototype); - -}); - -ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -exports.isDark = false; -exports.cssClass = "ace-tm"; -exports.cssText = ".ace-tm .ace_gutter {\ -background: #f0f0f0;\ -color: #333;\ -}\ -.ace-tm .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8;\ -}\ -.ace-tm .ace_fold {\ -background-color: #6B72E6;\ -}\ -.ace-tm {\ -background-color: #FFFFFF;\ -color: black;\ -}\ -.ace-tm .ace_cursor {\ -color: black;\ -}\ -.ace-tm .ace_invisible {\ -color: rgb(191, 191, 191);\ -}\ -.ace-tm .ace_storage,\ -.ace-tm .ace_keyword {\ -color: blue;\ -}\ -.ace-tm .ace_constant {\ -color: rgb(197, 6, 11);\ -}\ -.ace-tm .ace_constant.ace_buildin {\ -color: rgb(88, 72, 246);\ -}\ -.ace-tm .ace_constant.ace_language {\ -color: rgb(88, 92, 246);\ -}\ -.ace-tm .ace_constant.ace_library {\ -color: rgb(6, 150, 14);\ -}\ -.ace-tm .ace_invalid {\ -background-color: rgba(255, 0, 0, 0.1);\ -color: red;\ -}\ -.ace-tm .ace_support.ace_function {\ -color: rgb(60, 76, 114);\ -}\ -.ace-tm .ace_support.ace_constant {\ -color: rgb(6, 150, 14);\ -}\ -.ace-tm .ace_support.ace_type,\ -.ace-tm .ace_support.ace_class {\ -color: rgb(109, 121, 222);\ -}\ -.ace-tm .ace_keyword.ace_operator {\ -color: rgb(104, 118, 135);\ -}\ -.ace-tm .ace_string {\ -color: rgb(3, 106, 7);\ -}\ -.ace-tm .ace_comment {\ -color: rgb(76, 136, 107);\ -}\ -.ace-tm .ace_comment.ace_doc {\ -color: rgb(0, 102, 255);\ -}\ -.ace-tm .ace_comment.ace_doc.ace_tag {\ -color: rgb(128, 159, 191);\ -}\ -.ace-tm .ace_constant.ace_numeric {\ -color: rgb(0, 0, 205);\ -}\ -.ace-tm .ace_variable {\ -color: rgb(49, 132, 149);\ -}\ -.ace-tm .ace_xml-pe {\ -color: rgb(104, 104, 91);\ -}\ -.ace-tm .ace_entity.ace_name.ace_function {\ -color: #0000A2;\ -}\ -.ace-tm .ace_heading {\ -color: rgb(12, 7, 255);\ -}\ -.ace-tm .ace_list {\ -color:rgb(185, 6, 144);\ -}\ -.ace-tm .ace_meta.ace_tag {\ -color:rgb(0, 22, 142);\ -}\ -.ace-tm .ace_string.ace_regex {\ -color: rgb(255, 0, 0)\ -}\ -.ace-tm .ace_marker-layer .ace_selection {\ -background: rgb(181, 213, 255);\ -}\ -.ace-tm.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px white;\ -}\ -.ace-tm .ace_marker-layer .ace_step {\ -background: rgb(252, 255, 0);\ -}\ -.ace-tm .ace_marker-layer .ace_stack {\ -background: rgb(164, 229, 101);\ -}\ -.ace-tm .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgb(192, 192, 192);\ -}\ -.ace-tm .ace_marker-layer .ace_active-line {\ -background: rgba(0, 0, 0, 0.07);\ -}\ -.ace-tm .ace_gutter-active-line {\ -background-color : #dcdcdc;\ -}\ -.ace-tm .ace_marker-layer .ace_selected-word {\ -background: rgb(250, 250, 255);\ -border: 1px solid rgb(200, 200, 250);\ -}\ -.ace-tm .ace_indent-guide {\ -background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ -}\ -"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - -ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var dom = acequire("./lib/dom"); -var Range = acequire("./range").Range; - - -function LineWidgets(session) { - this.session = session; - this.session.widgetManager = this; - this.session.getRowLength = this.getRowLength; - this.session.$getWidgetScreenLength = this.$getWidgetScreenLength; - this.updateOnChange = this.updateOnChange.bind(this); - this.renderWidgets = this.renderWidgets.bind(this); - this.measureWidgets = this.measureWidgets.bind(this); - this.session._changedWidgets = []; - this.$onChangeEditor = this.$onChangeEditor.bind(this); - - this.session.on("change", this.updateOnChange); - this.session.on("changeFold", this.updateOnFold); - this.session.on("changeEditor", this.$onChangeEditor); -} - -(function() { - this.getRowLength = function(row) { - var h; - if (this.lineWidgets) - h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0; - else - h = 0; - if (!this.$useWrapMode || !this.$wrapData[row]) { - return 1 + h; - } else { - return this.$wrapData[row].length + 1 + h; - } - }; - - this.$getWidgetScreenLength = function() { - var screenRows = 0; - this.lineWidgets.forEach(function(w){ - if (w && w.rowCount && !w.hidden) - screenRows += w.rowCount; - }); - return screenRows; - }; - - this.$onChangeEditor = function(e) { - this.attach(e.editor); - }; - - this.attach = function(editor) { - if (editor && editor.widgetManager && editor.widgetManager != this) - editor.widgetManager.detach(); - - if (this.editor == editor) - return; - - this.detach(); - this.editor = editor; - - if (editor) { - editor.widgetManager = this; - editor.renderer.on("beforeRender", this.measureWidgets); - editor.renderer.on("afterRender", this.renderWidgets); - } - }; - this.detach = function(e) { - var editor = this.editor; - if (!editor) - return; - - this.editor = null; - editor.widgetManager = null; - - editor.renderer.off("beforeRender", this.measureWidgets); - editor.renderer.off("afterRender", this.renderWidgets); - var lineWidgets = this.session.lineWidgets; - lineWidgets && lineWidgets.forEach(function(w) { - if (w && w.el && w.el.parentNode) { - w._inDocument = false; - w.el.parentNode.removeChild(w.el); - } - }); - }; - - this.updateOnFold = function(e, session) { - var lineWidgets = session.lineWidgets; - if (!lineWidgets || !e.action) - return; - var fold = e.data; - var start = fold.start.row; - var end = fold.end.row; - var hide = e.action == "add"; - for (var i = start + 1; i < end; i++) { - if (lineWidgets[i]) - lineWidgets[i].hidden = hide; - } - if (lineWidgets[end]) { - if (hide) { - if (!lineWidgets[start]) - lineWidgets[start] = lineWidgets[end]; - else - lineWidgets[end].hidden = hide; - } else { - if (lineWidgets[start] == lineWidgets[end]) - lineWidgets[start] = undefined; - lineWidgets[end].hidden = hide; - } - } - }; - - this.updateOnChange = function(delta) { - var lineWidgets = this.session.lineWidgets; - if (!lineWidgets) return; - - var startRow = delta.start.row; - var len = delta.end.row - startRow; - - if (len === 0) { - } else if (delta.action == 'remove') { - var removed = lineWidgets.splice(startRow + 1, len); - removed.forEach(function(w) { - w && this.removeLineWidget(w); - }, this); - this.$updateRows(); - } else { - var args = new Array(len); - args.unshift(startRow, 0); - lineWidgets.splice.apply(lineWidgets, args); - this.$updateRows(); - } - }; - - this.$updateRows = function() { - var lineWidgets = this.session.lineWidgets; - if (!lineWidgets) return; - var noWidgets = true; - lineWidgets.forEach(function(w, i) { - if (w) { - noWidgets = false; - w.row = i; - while (w.$oldWidget) { - w.$oldWidget.row = i; - w = w.$oldWidget; - } - } - }); - if (noWidgets) - this.session.lineWidgets = null; - }; - - this.addLineWidget = function(w) { - if (!this.session.lineWidgets) - this.session.lineWidgets = new Array(this.session.getLength()); - - var old = this.session.lineWidgets[w.row]; - if (old) { - w.$oldWidget = old; - if (old.el && old.el.parentNode) { - old.el.parentNode.removeChild(old.el); - old._inDocument = false; - } - } - - this.session.lineWidgets[w.row] = w; - - w.session = this.session; - - var renderer = this.editor.renderer; - if (w.html && !w.el) { - w.el = dom.createElement("div"); - w.el.innerHTML = w.html; - } - if (w.el) { - dom.addCssClass(w.el, "ace_lineWidgetContainer"); - w.el.style.position = "absolute"; - w.el.style.zIndex = 5; - renderer.container.appendChild(w.el); - w._inDocument = true; - } - - if (!w.coverGutter) { - w.el.style.zIndex = 3; - } - if (w.pixelHeight == null) { - w.pixelHeight = w.el.offsetHeight; - } - if (w.rowCount == null) { - w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight; - } - - var fold = this.session.getFoldAt(w.row, 0); - w.$fold = fold; - if (fold) { - var lineWidgets = this.session.lineWidgets; - if (w.row == fold.end.row && !lineWidgets[fold.start.row]) - lineWidgets[fold.start.row] = w; - else - w.hidden = true; - } - - this.session._emit("changeFold", {data:{start:{row: w.row}}}); - - this.$updateRows(); - this.renderWidgets(null, renderer); - this.onWidgetChanged(w); - return w; - }; - - this.removeLineWidget = function(w) { - w._inDocument = false; - w.session = null; - if (w.el && w.el.parentNode) - w.el.parentNode.removeChild(w.el); - if (w.editor && w.editor.destroy) try { - w.editor.destroy(); - } catch(e){} - if (this.session.lineWidgets) { - var w1 = this.session.lineWidgets[w.row] - if (w1 == w) { - this.session.lineWidgets[w.row] = w.$oldWidget; - if (w.$oldWidget) - this.onWidgetChanged(w.$oldWidget); - } else { - while (w1) { - if (w1.$oldWidget == w) { - w1.$oldWidget = w.$oldWidget; - break; - } - w1 = w1.$oldWidget; - } - } - } - this.session._emit("changeFold", {data:{start:{row: w.row}}}); - this.$updateRows(); - }; - - this.getWidgetsAtRow = function(row) { - var lineWidgets = this.session.lineWidgets; - var w = lineWidgets && lineWidgets[row]; - var list = []; - while (w) { - list.push(w); - w = w.$oldWidget; - } - return list; - }; - - this.onWidgetChanged = function(w) { - this.session._changedWidgets.push(w); - this.editor && this.editor.renderer.updateFull(); - }; - - this.measureWidgets = function(e, renderer) { - var changedWidgets = this.session._changedWidgets; - var config = renderer.layerConfig; - - if (!changedWidgets || !changedWidgets.length) return; - var min = Infinity; - for (var i = 0; i < changedWidgets.length; i++) { - var w = changedWidgets[i]; - if (!w || !w.el) continue; - if (w.session != this.session) continue; - if (!w._inDocument) { - if (this.session.lineWidgets[w.row] != w) - continue; - w._inDocument = true; - renderer.container.appendChild(w.el); - } - - w.h = w.el.offsetHeight; - - if (!w.fixedWidth) { - w.w = w.el.offsetWidth; - w.screenWidth = Math.ceil(w.w / config.characterWidth); - } - - var rowCount = w.h / config.lineHeight; - if (w.coverLine) { - rowCount -= this.session.getRowLineCount(w.row); - if (rowCount < 0) - rowCount = 0; - } - if (w.rowCount != rowCount) { - w.rowCount = rowCount; - if (w.row < min) - min = w.row; - } - } - if (min != Infinity) { - this.session._emit("changeFold", {data:{start:{row: min}}}); - this.session.lineWidgetWidth = null; - } - this.session._changedWidgets = []; - }; - - this.renderWidgets = function(e, renderer) { - var config = renderer.layerConfig; - var lineWidgets = this.session.lineWidgets; - if (!lineWidgets) - return; - var first = Math.min(this.firstRow, config.firstRow); - var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length); - - while (first > 0 && !lineWidgets[first]) - first--; - - this.firstRow = config.firstRow; - this.lastRow = config.lastRow; - - renderer.$cursorLayer.config = config; - for (var i = first; i <= last; i++) { - var w = lineWidgets[i]; - if (!w || !w.el) continue; - if (w.hidden) { - w.el.style.top = -100 - (w.pixelHeight || 0) + "px"; - continue; - } - if (!w._inDocument) { - w._inDocument = true; - renderer.container.appendChild(w.el); - } - var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top; - if (!w.coverLine) - top += config.lineHeight * this.session.getRowLineCount(w.row); - w.el.style.top = top - config.offset + "px"; - - var left = w.coverGutter ? 0 : renderer.gutterWidth; - if (!w.fixedWidth) - left -= renderer.scrollLeft; - w.el.style.left = left + "px"; - - if (w.fullWidth && w.screenWidth) { - w.el.style.minWidth = config.width + 2 * config.padding + "px"; - } - - if (w.fixedWidth) { - w.el.style.right = renderer.scrollBar.getWidth() + "px"; - } else { - w.el.style.right = ""; - } - } - }; - -}).call(LineWidgets.prototype); - - -exports.LineWidgets = LineWidgets; - -}); - -ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(acequire, exports, module) { -"use strict"; -var LineWidgets = acequire("../line_widgets").LineWidgets; -var dom = acequire("../lib/dom"); -var Range = acequire("../range").Range; - -function binarySearch(array, needle, comparator) { - var first = 0; - var last = array.length - 1; - - while (first <= last) { - var mid = (first + last) >> 1; - var c = comparator(needle, array[mid]); - if (c > 0) - first = mid + 1; - else if (c < 0) - last = mid - 1; - else - return mid; - } - return -(first + 1); -} - -function findAnnotations(session, row, dir) { - var annotations = session.getAnnotations().sort(Range.comparePoints); - if (!annotations.length) - return; - - var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints); - if (i < 0) - i = -i - 1; - - if (i >= annotations.length) - i = dir > 0 ? 0 : annotations.length - 1; - else if (i === 0 && dir < 0) - i = annotations.length - 1; - - var annotation = annotations[i]; - if (!annotation || !dir) - return; - - if (annotation.row === row) { - do { - annotation = annotations[i += dir]; - } while (annotation && annotation.row === row); - if (!annotation) - return annotations.slice(); - } - - - var matched = []; - row = annotation.row; - do { - matched[dir < 0 ? "unshift" : "push"](annotation); - annotation = annotations[i += dir]; - } while (annotation && annotation.row == row); - return matched.length && matched; -} - -exports.showErrorMarker = function(editor, dir) { - var session = editor.session; - if (!session.widgetManager) { - session.widgetManager = new LineWidgets(session); - session.widgetManager.attach(editor); - } - - var pos = editor.getCursorPosition(); - var row = pos.row; - var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) { - return w.type == "errorMarker"; - })[0]; - if (oldWidget) { - oldWidget.destroy(); - } else { - row -= dir; - } - var annotations = findAnnotations(session, row, dir); - var gutterAnno; - if (annotations) { - var annotation = annotations[0]; - pos.column = (annotation.pos && typeof annotation.column != "number" - ? annotation.pos.sc - : annotation.column) || 0; - pos.row = annotation.row; - gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row]; - } else if (oldWidget) { - return; - } else { - gutterAnno = { - text: ["Looks good!"], - className: "ace_ok" - }; - } - editor.session.unfold(pos.row); - editor.selection.moveToPosition(pos); - - var w = { - row: pos.row, - fixedWidth: true, - coverGutter: true, - el: dom.createElement("div"), - type: "errorMarker" - }; - var el = w.el.appendChild(dom.createElement("div")); - var arrow = w.el.appendChild(dom.createElement("div")); - arrow.className = "error_widget_arrow " + gutterAnno.className; - - var left = editor.renderer.$cursorLayer - .getPixelPosition(pos).left; - arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px"; - - w.el.className = "error_widget_wrapper"; - el.className = "error_widget " + gutterAnno.className; - el.innerHTML = gutterAnno.text.join("
"); - - el.appendChild(dom.createElement("div")); - - var kb = function(_, hashId, keyString) { - if (hashId === 0 && (keyString === "esc" || keyString === "return")) { - w.destroy(); - return {command: "null"}; - } - }; - - w.destroy = function() { - if (editor.$mouseHandler.isMousePressed) - return; - editor.keyBinding.removeKeyboardHandler(kb); - session.widgetManager.removeLineWidget(w); - editor.off("changeSelection", w.destroy); - editor.off("changeSession", w.destroy); - editor.off("mouseup", w.destroy); - editor.off("change", w.destroy); - }; - - editor.keyBinding.addKeyboardHandler(kb); - editor.on("changeSelection", w.destroy); - editor.on("changeSession", w.destroy); - editor.on("mouseup", w.destroy); - editor.on("change", w.destroy); - - editor.session.widgetManager.addLineWidget(w); - - w.el.onmousedown = editor.focus.bind(editor); - - editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight}); -}; - - -dom.importCssString("\ - .error_widget_wrapper {\ - background: inherit;\ - color: inherit;\ - border:none\ - }\ - .error_widget {\ - border-top: solid 2px;\ - border-bottom: solid 2px;\ - margin: 5px 0;\ - padding: 10px 40px;\ - white-space: pre-wrap;\ - }\ - .error_widget.ace_error, .error_widget_arrow.ace_error{\ - border-color: #ff5a5a\ - }\ - .error_widget.ace_warning, .error_widget_arrow.ace_warning{\ - border-color: #F1D817\ - }\ - .error_widget.ace_info, .error_widget_arrow.ace_info{\ - border-color: #5a5a5a\ - }\ - .error_widget.ace_ok, .error_widget_arrow.ace_ok{\ - border-color: #5aaa5a\ - }\ - .error_widget_arrow {\ - position: absolute;\ - border: solid 5px;\ - border-top-color: transparent!important;\ - border-right-color: transparent!important;\ - border-left-color: transparent!important;\ - top: -5px;\ - }\ -", ""); - -}); - -ace.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/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(acequire, exports, module) { -"use strict"; - -acequire("./lib/fixoldbrowsers"); - -var dom = acequire("./lib/dom"); -var event = acequire("./lib/event"); - -var Editor = acequire("./editor").Editor; -var EditSession = acequire("./edit_session").EditSession; -var UndoManager = acequire("./undomanager").UndoManager; -var Renderer = acequire("./virtual_renderer").VirtualRenderer; -acequire("./worker/worker_client"); -acequire("./keyboard/hash_handler"); -acequire("./placeholder"); -acequire("./multi_select"); -acequire("./mode/folding/fold_mode"); -acequire("./theme/textmate"); -acequire("./ext/error_marker"); - -exports.config = acequire("./config"); -exports.acequire = acequire; - -if (true) - exports.define = __webpack_require__(42); -exports.edit = function(el) { - if (typeof el == "string") { - var _id = el; - el = document.getElementById(_id); - if (!el) - throw new Error("ace.edit can't find div #" + _id); - } - - if (el && el.env && el.env.editor instanceof Editor) - return el.env.editor; - - var value = ""; - if (el && /input|textarea/i.test(el.tagName)) { - var oldNode = el; - value = oldNode.value; - el = dom.createElement("pre"); - oldNode.parentNode.replaceChild(el, oldNode); - } else if (el) { - value = dom.getInnerText(el); - el.innerHTML = ""; - } - - var doc = exports.createEditSession(value); - - var editor = new Editor(new Renderer(el)); - editor.setSession(doc); - - var env = { - document: doc, - editor: editor, - onResize: editor.resize.bind(editor, null) - }; - if (oldNode) env.textarea = oldNode; - event.addListener(window, "resize", env.onResize); - editor.on("destroy", function() { - event.removeListener(window, "resize", env.onResize); - env.editor.container.env = null; // prevent memory leak on old ie - }); - editor.container.env = editor.env = env; - return editor; -}; -exports.createEditSession = function(text, mode) { - var doc = new EditSession(text, mode); - doc.setUndoManager(new UndoManager()); - return doc; -} -exports.EditSession = EditSession; -exports.UndoManager = UndoManager; -exports.version = "1.2.6"; -}); - (function() { - ace.acequire(["ace/ace"], function(a) { - if (a) { - a.config.init(true); - a.define = ace.define; - } - if (!window.ace) - window.ace = a; - for (var key in a) if (a.hasOwnProperty(key)) - window.ace[key] = a[key]; - }); - })(); - -module.exports = window.ace.acequire("ace/ace"); - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {module.exports = get_blob() - -function get_blob() { - if(global.Blob) { - try { - new Blob(['asdf'], {type: 'text/plain'}) - return Blob - } catch(err) {} - } - - var Builder = global.WebKitBlobBuilder || - global.MozBlobBuilder || - global.MSBlobBuilder - - return function(parts, bag) { - var builder = new Builder - , endings = bag.endings - , type = bag.type - - if(endings) for(var i = 0, len = parts.length; i < len; ++i) { - builder.append(parts[i], endings) - } else for(var i = 0, len = parts.length; i < len; ++i) { - builder.append(parts[i]) - } - - return type ? builder.getBlob(type) : builder.getBlob() - } -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33))) - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; - -var DocCommentHighlightRules = function() { - this.$rules = { - "start" : [ { - token : "comment.doc.tag", - regex : "@[\\w\\d_]+" // TODO: fix email addresses - }, - DocCommentHighlightRules.getTagRule(), - { - defaultToken : "comment.doc", - caseInsensitive: true - }] - }; -}; - -oop.inherits(DocCommentHighlightRules, TextHighlightRules); - -DocCommentHighlightRules.getTagRule = function(start) { - return { - token : "comment.doc.tag.storage.type", - regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" - }; -} - -DocCommentHighlightRules.getStartRule = function(start) { - return { - token : "comment.doc", // doc comment - regex : "\\/\\*(?=\\*)", - next : start - }; -}; - -DocCommentHighlightRules.getEndRule = function (start) { - return { - token : "comment.doc", // closing comment - regex : "\\*\\/", - next : start - }; -}; - - -exports.DocCommentHighlightRules = DocCommentHighlightRules; - -}); - -ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; -var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; -var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; - -var JavaScriptHighlightRules = function(options) { - var keywordMapper = this.createKeywordMapper({ - "variable.language": - "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors - "Namespace|QName|XML|XMLList|" + // E4X - "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + - "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + - "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors - "SyntaxError|TypeError|URIError|" + - "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions - "isNaN|parseFloat|parseInt|" + - "JSON|Math|" + // Other - "this|arguments|prototype|window|document" , // Pseudo - "keyword": - "const|yield|import|get|set|async|await|" + - "break|case|catch|continue|default|delete|do|else|finally|for|function|" + - "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + - "__parent__|__count__|escape|unescape|with|__proto__|" + - "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", - "storage.type": - "const|let|var|function", - "constant.language": - "null|Infinity|NaN|undefined", - "support.function": - "alert", - "constant.language.boolean": "true|false" - }, "identifier"); - var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; - - var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex - "u[0-9a-fA-F]{4}|" + // unicode - "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode - "[0-2][0-7]{0,2}|" + // oct - "3[0-7][0-7]?|" + // oct - "[4-7][0-7]?|" + //oct - ".)"; - - this.$rules = { - "no_regex" : [ - DocCommentHighlightRules.getStartRule("doc-start"), - comments("no_regex"), - { - token : "string", - regex : "'(?=.)", - next : "qstring" - }, { - token : "string", - regex : '"(?=.)', - next : "qqstring" - }, { - token : "constant.numeric", // hex - regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ - }, { - token : "constant.numeric", // float - regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ - }, { - token : [ - "storage.type", "punctuation.operator", "support.function", - "punctuation.operator", "entity.name.function", "text","keyword.operator" - ], - regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", - next: "function_arguments" - }, { - 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" - }, { - token : [ - "entity.name.function", "text", "keyword.operator", "text", "storage.type", - "text", "paren.lparen" - ], - regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "storage.type", "punctuation.operator", "entity.name.function", "text", - "keyword.operator", "text", - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "entity.name.function", "text", "punctuation.operator", - "text", "storage.type", "text", "paren.lparen" - ], - regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "text", "text", "storage.type", "text", "paren.lparen" - ], - regex : "(:)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token : "keyword", - regex : "(?:" + kwBeforeRe + ")\\b", - next : "start" - }, { - token : ["support.constant"], - regex : /that\b/ - }, { - token : ["storage.type", "punctuation.operator", "support.function.firebug"], - regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ - }, { - token : keywordMapper, - regex : identifierRe - }, { - token : "punctuation.operator", - regex : /[.](?![.])/, - next : "property" - }, { - token : "keyword.operator", - regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, - next : "start" - }, { - token : "punctuation.operator", - regex : /[?:,;.]/, - next : "start" - }, { - token : "paren.lparen", - regex : /[\[({]/, - next : "start" - }, { - token : "paren.rparen", - regex : /[\])}]/ - }, { - token: "comment", - regex: /^#!.*$/ - } - ], - property: [{ - token : "text", - regex : "\\s+" - }, { - token : [ - "storage.type", "punctuation.operator", "entity.name.function", "text", - "keyword.operator", "text", - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", - next: "function_arguments" - }, { - token : "punctuation.operator", - regex : /[.](?![.])/ - }, { - token : "support.function", - regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|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 : "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|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ - }, { - token : "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 : "identifier", - regex : identifierRe - }, { - regex: "", - token: "empty", - next: "no_regex" - } - ], - "start": [ - DocCommentHighlightRules.getStartRule("doc-start"), - comments("start"), - { - token: "string.regexp", - regex: "\\/", - next: "regex" - }, { - token : "text", - regex : "\\s+|^$", - next : "start" - }, { - token: "empty", - regex: "", - next: "no_regex" - } - ], - "regex": [ - { - token: "regexp.keyword.operator", - regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" - }, { - token: "string.regexp", - regex: "/[sxngimy]*", - next: "no_regex" - }, { - token : "invalid", - regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ - }, { - token : "constant.language.escape", - regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ - }, { - token : "constant.language.delimiter", - regex: /\|/ - }, { - token: "constant.language.escape", - regex: /\[\^?/, - next: "regex_character_class" - }, { - token: "empty", - regex: "$", - next: "no_regex" - }, { - defaultToken: "string.regexp" - } - ], - "regex_character_class": [ - { - token: "regexp.charclass.keyword.operator", - regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" - }, { - token: "constant.language.escape", - regex: "]", - next: "regex" - }, { - token: "constant.language.escape", - regex: "-" - }, { - token: "empty", - regex: "$", - next: "no_regex" - }, { - defaultToken: "string.regexp.charachterclass" - } - ], - "function_arguments": [ - { - token: "variable.parameter", - regex: identifierRe - }, { - token: "punctuation.operator", - regex: "[, ]+" - }, { - token: "punctuation.operator", - regex: "$" - }, { - token: "empty", - regex: "", - next: "no_regex" - } - ], - "qqstring" : [ - { - token : "constant.language.escape", - regex : escapedRe - }, { - token : "string", - regex : "\\\\$", - next : "qqstring" - }, { - token : "string", - regex : '"|$', - next : "no_regex" - }, { - defaultToken: "string" - } - ], - "qstring" : [ - { - token : "constant.language.escape", - regex : escapedRe - }, { - token : "string", - regex : "\\\\$", - next : "qstring" - }, { - token : "string", - regex : "'|$", - next : "no_regex" - }, { - defaultToken: "string" - } - ] - }; - - - if (!options || !options.noES6) { - this.$rules.no_regex.unshift({ - regex: "[{}]", onMatch: function(val, state, stack) { - this.next = val == "{" ? this.nextState : ""; - if (val == "{" && stack.length) { - stack.unshift("start", state); - } - else if (val == "}" && stack.length) { - stack.shift(); - this.next = stack.shift(); - if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) - return "paren.quasi.end"; - } - return val == "{" ? "paren.lparen" : "paren.rparen"; - }, - nextState: "start" - }, { - token : "string.quasi.start", - regex : /`/, - push : [{ - token : "constant.language.escape", - regex : escapedRe - }, { - token : "paren.quasi.start", - regex : /\${/, - push : "start" - }, { - token : "string.quasi.end", - regex : /`/, - next : "pop" - }, { - defaultToken: "string.quasi" - }] - }); - - if (!options || options.jsx != false) - JSX.call(this); - } - - this.embedRules(DocCommentHighlightRules, "doc-", - [ DocCommentHighlightRules.getEndRule("no_regex") ]); - - this.normalizeRules(); -}; - -oop.inherits(JavaScriptHighlightRules, TextHighlightRules); - -function JSX() { - var tagRegex = identifierRe.replace("\\d", "\\d\\-"); - var jsxTag = { - onMatch : function(val, state, stack) { - var offset = val.charAt(1) == "/" ? 2 : 1; - if (offset == 1) { - if (state != this.nextState) - stack.unshift(this.next, this.nextState, 0); - else - stack.unshift(this.next); - stack[2]++; - } else if (offset == 2) { - if (state == this.nextState) { - stack[1]--; - if (!stack[1] || stack[1] < 0) { - stack.shift(); - stack.shift(); - } - } - } - return [{ - type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", - value: val.slice(0, offset) - }, { - type: "meta.tag.tag-name.xml", - value: val.substr(offset) - }]; - }, - regex : "", - onMatch : function(value, currentState, stack) { - if (currentState == stack[0]) - stack.shift(); - if (value.length == 2) { - if (stack[0] == this.nextState) - stack[1]--; - if (!stack[1] || stack[1] < 0) { - stack.splice(0, 2); - } - } - this.next = stack[0] || "start"; - return [{type: this.token, value: value}]; - }, - nextState: "jsx" - }, - jsxJsRule, - comments("jsxAttributes"), - { - token : "entity.other.attribute-name.xml", - regex : tagRegex - }, { - token : "keyword.operator.attribute-equals.xml", - regex : "=" - }, { - token : "text.tag-whitespace.xml", - regex : "\\s+" - }, { - token : "string.attribute-value.xml", - regex : "'", - stateName : "jsx_attr_q", - push : [ - {token : "string.attribute-value.xml", regex: "'", next: "pop"}, - {include : "reference"}, - {defaultToken : "string.attribute-value.xml"} - ] - }, { - token : "string.attribute-value.xml", - regex : '"', - stateName : "jsx_attr_qq", - push : [ - {token : "string.attribute-value.xml", regex: '"', next: "pop"}, - {include : "reference"}, - {defaultToken : "string.attribute-value.xml"} - ] - }, - jsxTag - ]; - this.$rules.reference = [{ - token : "constant.language.escape.reference.xml", - regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" - }]; -} - -function comments(next) { - return [ - { - token : "comment", // multi line comment - regex : /\/\*/, - next: [ - DocCommentHighlightRules.getTagRule(), - {token : "comment", regex : "\\*\\/", next : next || "pop"}, - {defaultToken : "comment", caseInsensitive: true} - ] - }, { - token : "comment", - regex : "\\/\\/", - next: [ - DocCommentHighlightRules.getTagRule(), - {token : "comment", regex : "$|^", next : next || "pop"}, - {defaultToken : "comment", caseInsensitive: true} - ] - } - ]; -} -exports.JavaScriptHighlightRules = JavaScriptHighlightRules; -}); - -ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("../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) { - return line.match(/^\s*/)[0]; - }; - -}).call(MatchingBraceOutdent.prototype); - -exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); - -ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../../lib/oop"); -var Range = acequire("../../range").Range; -var BaseFoldMode = acequire("./fold_mode").FoldMode; - -var FoldMode = exports.FoldMode = function(commentRegex) { - if (commentRegex) { - this.foldingStartMarker = new RegExp( - this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) - ); - this.foldingStopMarker = new RegExp( - this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) - ); - } -}; -oop.inherits(FoldMode, BaseFoldMode); - -(function() { - - this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; - this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; - this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; - this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; - this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; - this._getFoldWidgetBase = this.getFoldWidget; - this.getFoldWidget = function(session, foldStyle, row) { - var line = session.getLine(row); - - if (this.singleLineBlockCommentRe.test(line)) { - if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) - return ""; - } - - var fw = this._getFoldWidgetBase(session, foldStyle, row); - - if (!fw && this.startRegionRe.test(line)) - return "start"; // lineCommentRegionStart - - return fw; - }; - - this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { - var line = session.getLine(row); - - if (this.startRegionRe.test(line)) - return this.getCommentRegionBlock(session, line, 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, 1); - - if (range && !range.isMultiLine()) { - if (forceMultiline) { - range = this.getSectionRange(session, row); - } else if (foldStyle != "all") - range = null; - } - - return range; - } - - if (foldStyle === "markbegin") - return; - - var match = line.match(this.foldingStopMarker); - if (match) { - var i = match.index + match[0].length; - - if (match[1]) - return this.closingBracketBlock(session, match[1], row, i); - - return session.getCommentFoldRange(row, i, -1); - } - }; - - this.getSectionRange = function(session, row) { - var line = session.getLine(row); - var startIndent = line.search(/\S/); - var startRow = row; - var startColumn = line.length; - row = row + 1; - var endRow = row; - var maxRow = session.getLength(); - while (++row < maxRow) { - line = session.getLine(row); - var indent = line.search(/\S/); - if (indent === -1) - continue; - if (startIndent > indent) - break; - var subRange = this.getFoldWidgetRange(session, "all", row); - - if (subRange) { - if (subRange.start.row <= startRow) { - break; - } else if (subRange.isMultiLine()) { - row = subRange.end.row; - } else if (startIndent == indent) { - break; - } - } - endRow = row; - } - - return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); - }; - this.getCommentRegionBlock = function(session, line, row) { - var startColumn = line.search(/\s*$/); - var maxRow = session.getLength(); - var startRow = row; - - var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; - var depth = 1; - while (++row < maxRow) { - line = session.getLine(row); - var m = re.exec(line); - if (!m) continue; - if (m[1]) depth--; - else depth++; - - if (!depth) break; - } - - var endRow = row; - if (endRow > startRow) { - return new Range(startRow, startColumn, endRow, line.length); - } - }; - -}).call(FoldMode.prototype); - -}); - -ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var TextMode = acequire("./text").Mode; -var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules; -var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; -var WorkerClient = acequire("../worker/worker_client").WorkerClient; -var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; -var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; - -var Mode = function() { - this.HighlightRules = JavaScriptHighlightRules; - - this.$outdent = new MatchingBraceOutdent(); - this.$behaviour = new CstyleBehaviour(); - this.foldingRules = new CStyleFoldMode(); -}; -oop.inherits(Mode, TextMode); - -(function() { - - this.lineCommentStart = "//"; - this.blockComment = {start: "/*", end: "*/"}; - - this.getNextLineIndent = function(state, line, tab) { - var indent = this.$getIndent(line); - - var tokenizedLine = this.getTokenizer().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 == "no_regex") { - var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); - if (match) { - indent += tab; - } - } else if (state == "doc-start") { - if (endState == "start" || endState == "no_regex") { - 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"], __webpack_require__(43), "JavaScriptWorker"); - worker.attachToDocument(session.getDocument()); - - worker.on("annotate", function(results) { - session.setAnnotations(results.data); - }); - - worker.on("terminate", function() { - session.clearAnnotations(); - }); - - return worker; - }; - - this.$id = "ace/mode/javascript"; -}).call(Mode.prototype); - -exports.Mode = Mode; -}); - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; - -var DocCommentHighlightRules = function() { - this.$rules = { - "start" : [ { - token : "comment.doc.tag", - regex : "@[\\w\\d_]+" // TODO: fix email addresses - }, - DocCommentHighlightRules.getTagRule(), - { - defaultToken : "comment.doc", - caseInsensitive: true - }] - }; -}; - -oop.inherits(DocCommentHighlightRules, TextHighlightRules); - -DocCommentHighlightRules.getTagRule = function(start) { - return { - token : "comment.doc.tag.storage.type", - regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" - }; -} - -DocCommentHighlightRules.getStartRule = function(start) { - return { - token : "comment.doc", // doc comment - regex : "\\/\\*(?=\\*)", - next : start - }; -}; - -DocCommentHighlightRules.getEndRule = function (start) { - return { - token : "comment.doc", // closing comment - regex : "\\*\\/", - next : start - }; -}; - - -exports.DocCommentHighlightRules = DocCommentHighlightRules; - -}); - -ace.define("ace/mode/netscript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules; -var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; -var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; - -var NetscriptHighlightRules = function(options) { - var keywordMapper = this.createKeywordMapper({ - "variable.language": - "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors - "Namespace|QName|XML|XMLList|" + // E4X - "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + - "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + - "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors - "SyntaxError|TypeError|URIError|" + - "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions - "isNaN|parseFloat|parseInt|" + - "hack|sleep|grow|weaken|print|tprint|scan|nuke|brutessh|ftpcrack|" + //Netscript functions - "relaysmtp|httpworm|sqlinject|run|exec|kill|killall|scp|ls|hasRootAccess|" + - "getIp|getHackingMultipliers|getBitNodeMultipliers|getStats|isBusy|" + - "getHostname|getHackingLevel|getServerMoneyAvailable|getServerMaxMoney|" + - "getServerGrowth|getServerSecurityLevel|getServerBaseSecurityLevel|" + - "getServerMinSecurityLevel|" + - "getServerRequiredHackingLevel|getServerNumPortsRequired|getServerRam|" + - "serverExists|fileExists|isRunning|getNextHacknetNodeCost|" + - "purchaseHacknetNode|deleteServer|getPurchasedServers|" + - "purchaseServer|round|write|read|scriptRunning|scriptKill|getScriptRam|" + - "getHackTime|getGrowTime|getWeakenTime|getScriptIncome|getScriptExpGain|" + - "getTimeSinceLastAug|" + - "universityCourse|" + - "gymWorkout|travelToCity|purchaseTor|purchaseProgram|upgradeHomeRam|" + - "getUpgradeHomeRamCost|workForCompany|applyToCompany|getCompanyRep|" + - "checkFactionInvitations|joinFaction|workForFaction|getFactionRep|" + - "createProgram|commitCrime|getCrimeChance|getOwnedAugmentations|" + - "getAugmentationsFromFaction|" + - "getAugmentationCost|purchaseAugmentation|" + - "installAugmentations|hacknetnodes|upgradeLevel|upgradeRam|upgradeCore|" + - "getLevelUpgradeCost|getRamUpgradeCost|getCoreUpgradeCost|" + - "getStockPrice|getStockPosition|buyStock|sellStock|" + - "JSON|Math|" + // Other - "this|arguments|prototype|window|document" , // Pseudo - "keyword": - "const|yield|import|get|set|async|await|" + - "break|case|catch|continue|default|delete|do|else|finally|for|function|" + - "if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + - "__parent__|__count__|escape|unescape|with|__proto__|" + - "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", - "storage.type": - "const|let|var|function", - "constant.language": - "null|Infinity|NaN|undefined", - "support.function": - "alert", - "constant.language.boolean": "true|false" - }, "identifier"); - var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; - - var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex - "u[0-9a-fA-F]{4}|" + // unicode - "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode - "[0-2][0-7]{0,2}|" + // oct - "3[0-7][0-7]?|" + // oct - "[4-7][0-7]?|" + //oct - ".)"; - - this.$rules = { - "no_regex" : [ - DocCommentHighlightRules.getStartRule("doc-start"), - comments("no_regex"), - { - token : "string", - regex : "'(?=.)", - next : "qstring" - }, { - token : "string", - regex : '"(?=.)', - next : "qqstring" - }, { - token : "constant.numeric", // hex - regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ - }, { - token : "constant.numeric", // float - regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ - }, { - token : [ - "storage.type", "punctuation.operator", "support.function", - "punctuation.operator", "entity.name.function", "text","keyword.operator" - ], - regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", - next: "function_arguments" - }, { - 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" - }, { - token : [ - "entity.name.function", "text", "keyword.operator", "text", "storage.type", - "text", "paren.lparen" - ], - regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "storage.type", "punctuation.operator", "entity.name.function", "text", - "keyword.operator", "text", - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "entity.name.function", "text", "punctuation.operator", - "text", "storage.type", "text", "paren.lparen" - ], - regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token : [ - "text", "text", "storage.type", "text", "paren.lparen" - ], - regex : "(:)(\\s*)(function)(\\s*)(\\()", - next: "function_arguments" - }, { - token : "keyword", - regex : "(?:" + kwBeforeRe + ")\\b", - next : "start" - }, { - token : ["support.constant"], - regex : /that\b/ - }, { - token : ["storage.type", "punctuation.operator", "support.function.firebug"], - regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ - }, { - token : keywordMapper, - regex : identifierRe - }, { - token : "punctuation.operator", - regex : /[.](?![.])/, - next : "property" - }, { - token : "keyword.operator", - regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, - next : "start" - }, { - token : "punctuation.operator", - regex : /[?:,;.]/, - next : "start" - }, { - token : "paren.lparen", - regex : /[\[({]/, - next : "start" - }, { - token : "paren.rparen", - regex : /[\])}]/ - }, { - token: "comment", - regex: /^#!.*$/ - } - ], - property: [{ - token : "text", - regex : "\\s+" - }, { - token : [ - "storage.type", "punctuation.operator", "entity.name.function", "text", - "keyword.operator", "text", - "storage.type", "text", "entity.name.function", "text", "paren.lparen" - ], - regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", - next: "function_arguments" - }, { - token : "punctuation.operator", - regex : /[.](?![.])/ - }, { - token : "support.function", - regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|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 : "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|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ - }, { - token : "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 : "identifier", - regex : identifierRe - }, { - regex: "", - token: "empty", - next: "no_regex" - } - ], - "start": [ - DocCommentHighlightRules.getStartRule("doc-start"), - comments("start"), - { - token: "string.regexp", - regex: "\\/", - next: "regex" - }, { - token : "text", - regex : "\\s+|^$", - next : "start" - }, { - token: "empty", - regex: "", - next: "no_regex" - } - ], - "regex": [ - { - token: "regexp.keyword.operator", - regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" - }, { - token: "string.regexp", - regex: "/[sxngimy]*", - next: "no_regex" - }, { - token : "invalid", - regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ - }, { - token : "constant.language.escape", - regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ - }, { - token : "constant.language.delimiter", - regex: /\|/ - }, { - token: "constant.language.escape", - regex: /\[\^?/, - next: "regex_character_class" - }, { - token: "empty", - regex: "$", - next: "no_regex" - }, { - defaultToken: "string.regexp" - } - ], - "regex_character_class": [ - { - token: "regexp.charclass.keyword.operator", - regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" - }, { - token: "constant.language.escape", - regex: "]", - next: "regex" - }, { - token: "constant.language.escape", - regex: "-" - }, { - token: "empty", - regex: "$", - next: "no_regex" - }, { - defaultToken: "string.regexp.charachterclass" - } - ], - "function_arguments": [ - { - token: "variable.parameter", - regex: identifierRe - }, { - token: "punctuation.operator", - regex: "[, ]+" - }, { - token: "punctuation.operator", - regex: "$" - }, { - token: "empty", - regex: "", - next: "no_regex" - } - ], - "qqstring" : [ - { - token : "constant.language.escape", - regex : escapedRe - }, { - token : "string", - regex : "\\\\$", - next : "qqstring" - }, { - token : "string", - regex : '"|$', - next : "no_regex" - }, { - defaultToken: "string" - } - ], - "qstring" : [ - { - token : "constant.language.escape", - regex : escapedRe - }, { - token : "string", - regex : "\\\\$", - next : "qstring" - }, { - token : "string", - regex : "'|$", - next : "no_regex" - }, { - defaultToken: "string" - } - ] - }; - - - if (!options || !options.noES6) { - this.$rules.no_regex.unshift({ - regex: "[{}]", onMatch: function(val, state, stack) { - this.next = val == "{" ? this.nextState : ""; - if (val == "{" && stack.length) { - stack.unshift("start", state); - } - else if (val == "}" && stack.length) { - stack.shift(); - this.next = stack.shift(); - if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) - return "paren.quasi.end"; - } - return val == "{" ? "paren.lparen" : "paren.rparen"; - }, - nextState: "start" - }, { - token : "string.quasi.start", - regex : /`/, - push : [{ - token : "constant.language.escape", - regex : escapedRe - }, { - token : "paren.quasi.start", - regex : /\${/, - push : "start" - }, { - token : "string.quasi.end", - regex : /`/, - next : "pop" - }, { - defaultToken: "string.quasi" - }] - }); - - if (!options || options.jsx != false) - JSX.call(this); - } - - this.embedRules(DocCommentHighlightRules, "doc-", - [ DocCommentHighlightRules.getEndRule("no_regex") ]); - - this.normalizeRules(); -}; - -oop.inherits(NetscriptHighlightRules, TextHighlightRules); - -function JSX() { - var tagRegex = identifierRe.replace("\\d", "\\d\\-"); - var jsxTag = { - onMatch : function(val, state, stack) { - var offset = val.charAt(1) == "/" ? 2 : 1; - if (offset == 1) { - if (state != this.nextState) - stack.unshift(this.next, this.nextState, 0); - else - stack.unshift(this.next); - stack[2]++; - } else if (offset == 2) { - if (state == this.nextState) { - stack[1]--; - if (!stack[1] || stack[1] < 0) { - stack.shift(); - stack.shift(); - } - } - } - return [{ - type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", - value: val.slice(0, offset) - }, { - type: "meta.tag.tag-name.xml", - value: val.substr(offset) - }]; - }, - regex : "", - onMatch : function(value, currentState, stack) { - if (currentState == stack[0]) - stack.shift(); - if (value.length == 2) { - if (stack[0] == this.nextState) - stack[1]--; - if (!stack[1] || stack[1] < 0) { - stack.splice(0, 2); - } - } - this.next = stack[0] || "start"; - return [{type: this.token, value: value}]; - }, - nextState: "jsx" - }, - jsxJsRule, - comments("jsxAttributes"), - { - token : "entity.other.attribute-name.xml", - regex : tagRegex - }, { - token : "keyword.operator.attribute-equals.xml", - regex : "=" - }, { - token : "text.tag-whitespace.xml", - regex : "\\s+" - }, { - token : "string.attribute-value.xml", - regex : "'", - stateName : "jsx_attr_q", - push : [ - {token : "string.attribute-value.xml", regex: "'", next: "pop"}, - {include : "reference"}, - {defaultToken : "string.attribute-value.xml"} - ] - }, { - token : "string.attribute-value.xml", - regex : '"', - stateName : "jsx_attr_qq", - push : [ - {token : "string.attribute-value.xml", regex: '"', next: "pop"}, - {include : "reference"}, - {defaultToken : "string.attribute-value.xml"} - ] - }, - jsxTag - ]; - this.$rules.reference = [{ - token : "constant.language.escape.reference.xml", - regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" - }]; -} - -function comments(next) { - return [ - { - token : "comment", // multi line comment - regex : /\/\*/, - next: [ - DocCommentHighlightRules.getTagRule(), - {token : "comment", regex : "\\*\\/", next : next || "pop"}, - {defaultToken : "comment", caseInsensitive: true} - ] - }, { - token : "comment", - regex : "\\/\\/", - next: [ - DocCommentHighlightRules.getTagRule(), - {token : "comment", regex : "$|^", next : next || "pop"}, - {defaultToken : "comment", caseInsensitive: true} - ] - } - ]; -} -exports.NetscriptHighlightRules = NetscriptHighlightRules; -}); - -ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { -"use strict"; - -var Range = acequire("../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) { - return line.match(/^\s*/)[0]; - }; - -}).call(MatchingBraceOutdent.prototype); - -exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); - -ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../../lib/oop"); -var Range = acequire("../../range").Range; -var BaseFoldMode = acequire("./fold_mode").FoldMode; - -var FoldMode = exports.FoldMode = function(commentRegex) { - if (commentRegex) { - this.foldingStartMarker = new RegExp( - this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) - ); - this.foldingStopMarker = new RegExp( - this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) - ); - } -}; -oop.inherits(FoldMode, BaseFoldMode); - -(function() { - - this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; - this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; - this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; - this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; - this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; - this._getFoldWidgetBase = this.getFoldWidget; - this.getFoldWidget = function(session, foldStyle, row) { - var line = session.getLine(row); - - if (this.singleLineBlockCommentRe.test(line)) { - if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) - return ""; - } - - var fw = this._getFoldWidgetBase(session, foldStyle, row); - - if (!fw && this.startRegionRe.test(line)) - return "start"; // lineCommentRegionStart - - return fw; - }; - - this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { - var line = session.getLine(row); - - if (this.startRegionRe.test(line)) - return this.getCommentRegionBlock(session, line, 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, 1); - - if (range && !range.isMultiLine()) { - if (forceMultiline) { - range = this.getSectionRange(session, row); - } else if (foldStyle != "all") - range = null; - } - - return range; - } - - if (foldStyle === "markbegin") - return; - - var match = line.match(this.foldingStopMarker); - if (match) { - var i = match.index + match[0].length; - - if (match[1]) - return this.closingBracketBlock(session, match[1], row, i); - - return session.getCommentFoldRange(row, i, -1); - } - }; - - this.getSectionRange = function(session, row) { - var line = session.getLine(row); - var startIndent = line.search(/\S/); - var startRow = row; - var startColumn = line.length; - row = row + 1; - var endRow = row; - var maxRow = session.getLength(); - while (++row < maxRow) { - line = session.getLine(row); - var indent = line.search(/\S/); - if (indent === -1) - continue; - if (startIndent > indent) - break; - var subRange = this.getFoldWidgetRange(session, "all", row); - - if (subRange) { - if (subRange.start.row <= startRow) { - break; - } else if (subRange.isMultiLine()) { - row = subRange.end.row; - } else if (startIndent == indent) { - break; - } - } - endRow = row; - } - - return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); - }; - this.getCommentRegionBlock = function(session, line, row) { - var startColumn = line.search(/\s*$/); - var maxRow = session.getLength(); - var startRow = row; - - var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; - var depth = 1; - while (++row < maxRow) { - line = session.getLine(row); - var m = re.exec(line); - if (!m) continue; - if (m[1]) depth--; - else depth++; - - if (!depth) break; - } - - var endRow = row; - if (endRow > startRow) { - return new Range(startRow, startColumn, endRow, line.length); - } - }; - -}).call(FoldMode.prototype); - -}); - -ace.define("ace/mode/netscript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/netscript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("../lib/oop"); -var TextMode = acequire("./text").Mode; -var NetscriptHighlightRules = acequire("./netscript_highlight_rules").NetscriptHighlightRules; -var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; -var WorkerClient = acequire("../worker/worker_client").WorkerClient; -var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour; -var CStyleFoldMode = acequire("./folding/cstyle").FoldMode; - -var Mode = function() { - this.HighlightRules = NetscriptHighlightRules; - - this.$outdent = new MatchingBraceOutdent(); - this.$behaviour = new CstyleBehaviour(); - this.foldingRules = new CStyleFoldMode(); -}; -oop.inherits(Mode, TextMode); - -(function() { - - this.lineCommentStart = "//"; - this.blockComment = {start: "/*", end: "*/"}; - - this.getNextLineIndent = function(state, line, tab) { - var indent = this.$getIndent(line); - - var tokenizedLine = this.getTokenizer().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 == "no_regex") { - var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); - if (match) { - indent += tab; - } - } else if (state == "doc-start") { - if (endState == "start" || endState == "no_regex") { - 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"], __webpack_require__(43), "JavaScriptWorker"); - worker.attachToDocument(session.getDocument()); - - worker.on("annotate", function(results) { - session.setAnnotations(results.data); - }); - - worker.on("terminate", function() { - session.clearAnnotations(); - }); - - return worker; - }; - - this.$id = "ace/mode/netscript"; -}).call(Mode.prototype); - -exports.Mode = Mode; -}); - - -/***/ }), -/* 59 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/chaos",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = true; -exports.cssClass = "ace-chaos"; -exports.cssText = ".ace-chaos .ace_gutter {\ -background: #141414;\ -color: #595959;\ -border-right: 1px solid #282828;\ -}\ -.ace-chaos .ace_gutter-cell.ace_warning {\ -background-image: none;\ -background: #FC0;\ -border-left: none;\ -padding-left: 0;\ -color: #000;\ -}\ -.ace-chaos .ace_gutter-cell.ace_error {\ -background-position: -6px center;\ -background-image: none;\ -background: #F10;\ -border-left: none;\ -padding-left: 0;\ -color: #000;\ -}\ -.ace-chaos .ace_print-margin {\ -border-left: 1px solid #555;\ -right: 0;\ -background: #1D1D1D;\ -}\ -.ace-chaos {\ -background-color: #161616;\ -color: #E6E1DC;\ -}\ -.ace-chaos .ace_cursor {\ -border-left: 2px solid #FFFFFF;\ -}\ -.ace-chaos .ace_cursor.ace_overwrite {\ -border-left: 0px;\ -border-bottom: 1px solid #FFFFFF;\ -}\ -.ace-chaos .ace_marker-layer .ace_selection {\ -background: #494836;\ -}\ -.ace-chaos .ace_marker-layer .ace_step {\ -background: rgb(198, 219, 174);\ -}\ -.ace-chaos .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid #FCE94F;\ -}\ -.ace-chaos .ace_marker-layer .ace_active-line {\ -background: #333;\ -}\ -.ace-chaos .ace_gutter-active-line {\ -background-color: #222;\ -}\ -.ace-chaos .ace_invisible {\ -color: #404040;\ -}\ -.ace-chaos .ace_keyword {\ -color:#00698F;\ -}\ -.ace-chaos .ace_keyword.ace_operator {\ -color:#FF308F;\ -}\ -.ace-chaos .ace_constant {\ -color:#1EDAFB;\ -}\ -.ace-chaos .ace_constant.ace_language {\ -color:#FDC251;\ -}\ -.ace-chaos .ace_constant.ace_library {\ -color:#8DFF0A;\ -}\ -.ace-chaos .ace_constant.ace_numeric {\ -color:#58C554;\ -}\ -.ace-chaos .ace_invalid {\ -color:#FFFFFF;\ -background-color:#990000;\ -}\ -.ace-chaos .ace_invalid.ace_deprecated {\ -color:#FFFFFF;\ -background-color:#990000;\ -}\ -.ace-chaos .ace_support {\ -color: #999;\ -}\ -.ace-chaos .ace_support.ace_function {\ -color:#00AEEF;\ -}\ -.ace-chaos .ace_function {\ -color:#00AEEF;\ -}\ -.ace-chaos .ace_string {\ -color:#58C554;\ -}\ -.ace-chaos .ace_comment {\ -color:#555;\ -font-style:italic;\ -padding-bottom: 0px;\ -}\ -.ace-chaos .ace_variable {\ -color:#997744;\ -}\ -.ace-chaos .ace_meta.ace_tag {\ -color:#BE53E6;\ -}\ -.ace-chaos .ace_entity.ace_other.ace_attribute-name {\ -color:#FFFF89;\ -}\ -.ace-chaos .ace_markup.ace_underline {\ -text-decoration: underline;\ -}\ -.ace-chaos .ace_fold-widget {\ -text-align: center;\ -}\ -.ace-chaos .ace_fold-widget:hover {\ -color: #777;\ -}\ -.ace-chaos .ace_fold-widget.ace_start,\ -.ace-chaos .ace_fold-widget.ace_end,\ -.ace-chaos .ace_fold-widget.ace_closed{\ -background: none;\ -border: none;\ -box-shadow: none;\ -}\ -.ace-chaos .ace_fold-widget.ace_start:after {\ -content: '▾'\ -}\ -.ace-chaos .ace_fold-widget.ace_end:after {\ -content: '▴'\ -}\ -.ace-chaos .ace_fold-widget.ace_closed:after {\ -content: '‣'\ -}\ -.ace-chaos .ace_indent-guide {\ -border-right:1px dotted #333;\ -margin-right:-1px;\ -}\ -.ace-chaos .ace_fold { \ -background: #222; \ -border-radius: 3px; \ -color: #7AF; \ -border: none; \ -}\ -.ace-chaos .ace_fold:hover {\ -background: #CCC; \ -color: #000;\ -}\ -"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); - -}); - - -/***/ }), -/* 60 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/chrome",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = false; -exports.cssClass = "ace-chrome"; -exports.cssText = ".ace-chrome .ace_gutter {\ -background: #ebebeb;\ -color: #333;\ -overflow : hidden;\ -}\ -.ace-chrome .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8;\ -}\ -.ace-chrome {\ -background-color: #FFFFFF;\ -color: black;\ -}\ -.ace-chrome .ace_cursor {\ -color: black;\ -}\ -.ace-chrome .ace_invisible {\ -color: rgb(191, 191, 191);\ -}\ -.ace-chrome .ace_constant.ace_buildin {\ -color: rgb(88, 72, 246);\ -}\ -.ace-chrome .ace_constant.ace_language {\ -color: rgb(88, 92, 246);\ -}\ -.ace-chrome .ace_constant.ace_library {\ -color: rgb(6, 150, 14);\ -}\ -.ace-chrome .ace_invalid {\ -background-color: rgb(153, 0, 0);\ -color: white;\ -}\ -.ace-chrome .ace_fold {\ -}\ -.ace-chrome .ace_support.ace_function {\ -color: rgb(60, 76, 114);\ -}\ -.ace-chrome .ace_support.ace_constant {\ -color: rgb(6, 150, 14);\ -}\ -.ace-chrome .ace_support.ace_type,\ -.ace-chrome .ace_support.ace_class\ -.ace-chrome .ace_support.ace_other {\ -color: rgb(109, 121, 222);\ -}\ -.ace-chrome .ace_variable.ace_parameter {\ -font-style:italic;\ -color:#FD971F;\ -}\ -.ace-chrome .ace_keyword.ace_operator {\ -color: rgb(104, 118, 135);\ -}\ -.ace-chrome .ace_comment {\ -color: #236e24;\ -}\ -.ace-chrome .ace_comment.ace_doc {\ -color: #236e24;\ -}\ -.ace-chrome .ace_comment.ace_doc.ace_tag {\ -color: #236e24;\ -}\ -.ace-chrome .ace_constant.ace_numeric {\ -color: rgb(0, 0, 205);\ -}\ -.ace-chrome .ace_variable {\ -color: rgb(49, 132, 149);\ -}\ -.ace-chrome .ace_xml-pe {\ -color: rgb(104, 104, 91);\ -}\ -.ace-chrome .ace_entity.ace_name.ace_function {\ -color: #0000A2;\ -}\ -.ace-chrome .ace_heading {\ -color: rgb(12, 7, 255);\ -}\ -.ace-chrome .ace_list {\ -color:rgb(185, 6, 144);\ -}\ -.ace-chrome .ace_marker-layer .ace_selection {\ -background: rgb(181, 213, 255);\ -}\ -.ace-chrome .ace_marker-layer .ace_step {\ -background: rgb(252, 255, 0);\ -}\ -.ace-chrome .ace_marker-layer .ace_stack {\ -background: rgb(164, 229, 101);\ -}\ -.ace-chrome .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgb(192, 192, 192);\ -}\ -.ace-chrome .ace_marker-layer .ace_active-line {\ -background: rgba(0, 0, 0, 0.07);\ -}\ -.ace-chrome .ace_gutter-active-line {\ -background-color : #dcdcdc;\ -}\ -.ace-chrome .ace_marker-layer .ace_selected-word {\ -background: rgb(250, 250, 255);\ -border: 1px solid rgb(200, 200, 250);\ -}\ -.ace-chrome .ace_storage,\ -.ace-chrome .ace_keyword,\ -.ace-chrome .ace_meta.ace_tag {\ -color: rgb(147, 15, 128);\ -}\ -.ace-chrome .ace_string.ace_regex {\ -color: rgb(255, 0, 0)\ -}\ -.ace-chrome .ace_string {\ -color: #1A1AA6;\ -}\ -.ace-chrome .ace_entity.ace_other.ace_attribute-name {\ -color: #994409;\ -}\ -.ace-chrome .ace_indent-guide {\ -background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\ -}\ -"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/monokai",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = true; -exports.cssClass = "ace-monokai"; -exports.cssText = ".ace-monokai .ace_gutter {\ -background: #2F3129;\ -color: #8F908A\ -}\ -.ace-monokai .ace_print-margin {\ -width: 1px;\ -background: #555651\ -}\ -.ace-monokai {\ -background-color: #272822;\ -color: #F8F8F2\ -}\ -.ace-monokai .ace_cursor {\ -color: #F8F8F0\ -}\ -.ace-monokai .ace_marker-layer .ace_selection {\ -background: #49483E\ -}\ -.ace-monokai.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #272822;\ -}\ -.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: #202020\ -}\ -.ace-monokai .ace_gutter-active-line {\ -background-color: #272727\ -}\ -.ace-monokai .ace_marker-layer .ace_selected-word {\ -border: 1px solid #49483E\ -}\ -.ace-monokai .ace_invisible {\ -color: #52524d\ -}\ -.ace-monokai .ace_entity.ace_name.ace_tag,\ -.ace-monokai .ace_keyword,\ -.ace-monokai .ace_meta.ace_tag,\ -.ace-monokai .ace_storage {\ -color: #F92672\ -}\ -.ace-monokai .ace_punctuation,\ -.ace-monokai .ace_punctuation.ace_tag {\ -color: #fff\ -}\ -.ace-monokai .ace_constant.ace_character,\ -.ace-monokai .ace_constant.ace_language,\ -.ace-monokai .ace_constant.ace_numeric,\ -.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,\ -.ace-monokai .ace_support.ace_function {\ -color: #66D9EF\ -}\ -.ace-monokai .ace_fold {\ -background-color: #A6E22E;\ -border-color: #F8F8F2\ -}\ -.ace-monokai .ace_storage.ace_type,\ -.ace-monokai .ace_support.ace_class,\ -.ace-monokai .ace_support.ace_type {\ -font-style: italic;\ -color: #66D9EF\ -}\ -.ace-monokai .ace_entity.ace_name.ace_function,\ -.ace-monokai .ace_entity.ace_other,\ -.ace-monokai .ace_entity.ace_other.ace_attribute-name,\ -.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_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y\ -}"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/solarized_dark",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = true; -exports.cssClass = "ace-solarized-dark"; -exports.cssText = ".ace-solarized-dark .ace_gutter {\ -background: #01313f;\ -color: #d0edf7\ -}\ -.ace-solarized-dark .ace_print-margin {\ -width: 1px;\ -background: #33555E\ -}\ -.ace-solarized-dark {\ -background-color: #002B36;\ -color: #93A1A1\ -}\ -.ace-solarized-dark .ace_entity.ace_other.ace_attribute-name,\ -.ace-solarized-dark .ace_storage {\ -color: #93A1A1\ -}\ -.ace-solarized-dark .ace_cursor,\ -.ace-solarized-dark .ace_string.ace_regexp {\ -color: #D30102\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_active-line,\ -.ace-solarized-dark .ace_marker-layer .ace_selection {\ -background: rgba(255, 255, 255, 0.1)\ -}\ -.ace-solarized-dark.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #002B36;\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_step {\ -background: rgb(102, 82, 0)\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-dark .ace_gutter-active-line {\ -background-color: #0d3440\ -}\ -.ace-solarized-dark .ace_marker-layer .ace_selected-word {\ -border: 1px solid #073642\ -}\ -.ace-solarized-dark .ace_invisible {\ -color: rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-dark .ace_keyword,\ -.ace-solarized-dark .ace_meta,\ -.ace-solarized-dark .ace_support.ace_class,\ -.ace-solarized-dark .ace_support.ace_type {\ -color: #859900\ -}\ -.ace-solarized-dark .ace_constant.ace_character,\ -.ace-solarized-dark .ace_constant.ace_other {\ -color: #CB4B16\ -}\ -.ace-solarized-dark .ace_constant.ace_language {\ -color: #B58900\ -}\ -.ace-solarized-dark .ace_constant.ace_numeric {\ -color: #D33682\ -}\ -.ace-solarized-dark .ace_fold {\ -background-color: #268BD2;\ -border-color: #93A1A1\ -}\ -.ace-solarized-dark .ace_entity.ace_name.ace_function,\ -.ace-solarized-dark .ace_entity.ace_name.ace_tag,\ -.ace-solarized-dark .ace_support.ace_function,\ -.ace-solarized-dark .ace_variable,\ -.ace-solarized-dark .ace_variable.ace_language {\ -color: #268BD2\ -}\ -.ace-solarized-dark .ace_string {\ -color: #2AA198\ -}\ -.ace-solarized-dark .ace_comment {\ -font-style: italic;\ -color: #657B83\ -}\ -.ace-solarized-dark .ace_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNg0Db1ZVCxc/sPAAd4AlUHlLenAAAAAElFTkSuQmCC) right repeat-y\ -}"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 63 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/solarized_light",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = false; -exports.cssClass = "ace-solarized-light"; -exports.cssText = ".ace-solarized-light .ace_gutter {\ -background: #fbf1d3;\ -color: #333\ -}\ -.ace-solarized-light .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8\ -}\ -.ace-solarized-light {\ -background-color: #FDF6E3;\ -color: #586E75\ -}\ -.ace-solarized-light .ace_cursor {\ -color: #000000\ -}\ -.ace-solarized-light .ace_marker-layer .ace_selection {\ -background: rgba(7, 54, 67, 0.09)\ -}\ -.ace-solarized-light.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #FDF6E3;\ -}\ -.ace-solarized-light .ace_marker-layer .ace_step {\ -background: rgb(255, 255, 0)\ -}\ -.ace-solarized-light .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-light .ace_marker-layer .ace_active-line {\ -background: #EEE8D5\ -}\ -.ace-solarized-light .ace_gutter-active-line {\ -background-color : #EDE5C1\ -}\ -.ace-solarized-light .ace_marker-layer .ace_selected-word {\ -border: 1px solid #073642\ -}\ -.ace-solarized-light .ace_invisible {\ -color: rgba(147, 161, 161, 0.50)\ -}\ -.ace-solarized-light .ace_keyword,\ -.ace-solarized-light .ace_meta,\ -.ace-solarized-light .ace_support.ace_class,\ -.ace-solarized-light .ace_support.ace_type {\ -color: #859900\ -}\ -.ace-solarized-light .ace_constant.ace_character,\ -.ace-solarized-light .ace_constant.ace_other {\ -color: #CB4B16\ -}\ -.ace-solarized-light .ace_constant.ace_language {\ -color: #B58900\ -}\ -.ace-solarized-light .ace_constant.ace_numeric {\ -color: #D33682\ -}\ -.ace-solarized-light .ace_fold {\ -background-color: #268BD2;\ -border-color: #586E75\ -}\ -.ace-solarized-light .ace_entity.ace_name.ace_function,\ -.ace-solarized-light .ace_entity.ace_name.ace_tag,\ -.ace-solarized-light .ace_support.ace_function,\ -.ace-solarized-light .ace_variable,\ -.ace-solarized-light .ace_variable.ace_language {\ -color: #268BD2\ -}\ -.ace-solarized-light .ace_storage {\ -color: #073642\ -}\ -.ace-solarized-light .ace_string {\ -color: #2AA198\ -}\ -.ace-solarized-light .ace_string.ace_regexp {\ -color: #D30102\ -}\ -.ace-solarized-light .ace_comment,\ -.ace-solarized-light .ace_entity.ace_other.ace_attribute-name {\ -color: #93A1A1\ -}\ -.ace-solarized-light .ace_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYHjy8NJ/AAjgA5fzQUmBAAAAAElFTkSuQmCC) right repeat-y\ -}"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 64 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/terminal",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = true; -exports.cssClass = "ace-terminal-theme"; -exports.cssText = ".ace-terminal-theme .ace_gutter {\ -background: #1a0005;\ -color: steelblue\ -}\ -.ace-terminal-theme .ace_print-margin {\ -width: 1px;\ -background: #1a1a1a\ -}\ -.ace-terminal-theme {\ -background-color: black;\ -color: #DEDEDE\ -}\ -.ace-terminal-theme .ace_cursor {\ -color: #9F9F9F\ -}\ -.ace-terminal-theme .ace_marker-layer .ace_selection {\ -background: #424242\ -}\ -.ace-terminal-theme.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px black;\ -}\ -.ace-terminal-theme .ace_marker-layer .ace_step {\ -background: rgb(0, 0, 0)\ -}\ -.ace-terminal-theme .ace_marker-layer .ace_bracket {\ -background: #090;\ -}\ -.ace-terminal-theme .ace_marker-layer .ace_bracket-start {\ -background: #090;\ -}\ -.ace-terminal-theme .ace_marker-layer .ace_bracket-unmatched {\ -margin: -1px 0 0 -1px;\ -border: 1px solid #900\ -}\ -.ace-terminal-theme .ace_marker-layer .ace_active-line {\ -background: #2A2A2A\ -}\ -.ace-terminal-theme .ace_gutter-active-line {\ -background-color: #2A112A\ -}\ -.ace-terminal-theme .ace_marker-layer .ace_selected-word {\ -border: 1px solid #424242\ -}\ -.ace-terminal-theme .ace_invisible {\ -color: #343434\ -}\ -.ace-terminal-theme .ace_keyword,\ -.ace-terminal-theme .ace_meta,\ -.ace-terminal-theme .ace_storage,\ -.ace-terminal-theme .ace_storage.ace_type,\ -.ace-terminal-theme .ace_support.ace_type {\ -color: tomato\ -}\ -.ace-terminal-theme .ace_keyword.ace_operator {\ -color: deeppink\ -}\ -.ace-terminal-theme .ace_constant.ace_character,\ -.ace-terminal-theme .ace_constant.ace_language,\ -.ace-terminal-theme .ace_constant.ace_numeric,\ -.ace-terminal-theme .ace_keyword.ace_other.ace_unit,\ -.ace-terminal-theme .ace_support.ace_constant,\ -.ace-terminal-theme .ace_variable.ace_parameter {\ -color: #E78C45\ -}\ -.ace-terminal-theme .ace_constant.ace_other {\ -color: gold\ -}\ -.ace-terminal-theme .ace_invalid {\ -color: yellow;\ -background-color: red\ -}\ -.ace-terminal-theme .ace_invalid.ace_deprecated {\ -color: #CED2CF;\ -background-color: #B798BF\ -}\ -.ace-terminal-theme .ace_fold {\ -background-color: #7AA6DA;\ -border-color: #DEDEDE\ -}\ -.ace-terminal-theme .ace_entity.ace_name.ace_function,\ -.ace-terminal-theme .ace_support.ace_function,\ -.ace-terminal-theme .ace_variable {\ -color: #7AA6DA\ -}\ -.ace-terminal-theme .ace_support.ace_class,\ -.ace-terminal-theme .ace_support.ace_type {\ -color: #E7C547\ -}\ -.ace-terminal-theme .ace_heading,\ -.ace-terminal-theme .ace_string {\ -color: #B9CA4A\ -}\ -.ace-terminal-theme .ace_entity.ace_name.ace_tag,\ -.ace-terminal-theme .ace_entity.ace_other.ace_attribute-name,\ -.ace-terminal-theme .ace_meta.ace_tag,\ -.ace-terminal-theme .ace_string.ace_regexp,\ -.ace-terminal-theme .ace_variable {\ -color: #D54E53\ -}\ -.ace-terminal-theme .ace_comment {\ -color: orangered\ -}\ -.ace-terminal-theme .ace_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYLBWV/8PAAK4AYnhiq+xAAAAAElFTkSuQmCC) right repeat-y;\ -}\ -"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/twilight",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = true; -exports.cssClass = "ace-twilight"; -exports.cssText = ".ace-twilight .ace_gutter {\ -background: #232323;\ -color: #E2E2E2\ -}\ -.ace-twilight .ace_print-margin {\ -width: 1px;\ -background: #232323\ -}\ -.ace-twilight {\ -background-color: #141414;\ -color: #F8F8F8\ -}\ -.ace-twilight .ace_cursor {\ -color: #A7A7A7\ -}\ -.ace-twilight .ace_marker-layer .ace_selection {\ -background: rgba(221, 240, 255, 0.20)\ -}\ -.ace-twilight.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #141414;\ -}\ -.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: rgba(255, 255, 255, 0.031)\ -}\ -.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_character,\ -.ace-twilight .ace_constant.ace_character.ace_escape,\ -.ace-twilight .ace_constant.ace_other,\ -.ace-twilight .ace_heading,\ -.ace-twilight .ace_markup.ace_heading,\ -.ace-twilight .ace_support.ace_constant {\ -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_fold {\ -background-color: #AC885B;\ -border-color: #F8F8F8\ -}\ -.ace-twilight .ace_support.ace_function {\ -color: #DAD085\ -}\ -.ace-twilight .ace_list,\ -.ace-twilight .ace_markup.ace_list,\ -.ace-twilight .ace_storage {\ -color: #F9EE98\ -}\ -.ace-twilight .ace_entity.ace_name.ace_function,\ -.ace-twilight .ace_meta.ace_tag,\ -.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_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWMQERFpYLC1tf0PAAgOAnPnhxyiAAAAAElFTkSuQmCC) right repeat-y\ -}"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 66 */ -/***/ (function(module, exports) { - -ace.define("ace/theme/xcode",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { - -exports.isDark = false; -exports.cssClass = "ace-xcode"; -exports.cssText = "\ -.ace-xcode .ace_gutter {\ -background: #e8e8e8;\ -color: #333\ -}\ -.ace-xcode .ace_print-margin {\ -width: 1px;\ -background: #e8e8e8\ -}\ -.ace-xcode {\ -background-color: #FFFFFF;\ -color: #000000\ -}\ -.ace-xcode .ace_cursor {\ -color: #000000\ -}\ -.ace-xcode .ace_marker-layer .ace_selection {\ -background: #B5D5FF\ -}\ -.ace-xcode.ace_multiselect .ace_selection.ace_start {\ -box-shadow: 0 0 3px 0px #FFFFFF;\ -}\ -.ace-xcode .ace_marker-layer .ace_step {\ -background: rgb(198, 219, 174)\ -}\ -.ace-xcode .ace_marker-layer .ace_bracket {\ -margin: -1px 0 0 -1px;\ -border: 1px solid #BFBFBF\ -}\ -.ace-xcode .ace_marker-layer .ace_active-line {\ -background: rgba(0, 0, 0, 0.071)\ -}\ -.ace-xcode .ace_gutter-active-line {\ -background-color: rgba(0, 0, 0, 0.071)\ -}\ -.ace-xcode .ace_marker-layer .ace_selected-word {\ -border: 1px solid #B5D5FF\ -}\ -.ace-xcode .ace_constant.ace_language,\ -.ace-xcode .ace_keyword,\ -.ace-xcode .ace_meta,\ -.ace-xcode .ace_variable.ace_language {\ -color: #C800A4\ -}\ -.ace-xcode .ace_invisible {\ -color: #BFBFBF\ -}\ -.ace-xcode .ace_constant.ace_character,\ -.ace-xcode .ace_constant.ace_other {\ -color: #275A5E\ -}\ -.ace-xcode .ace_constant.ace_numeric {\ -color: #3A00DC\ -}\ -.ace-xcode .ace_entity.ace_other.ace_attribute-name,\ -.ace-xcode .ace_support.ace_constant,\ -.ace-xcode .ace_support.ace_function {\ -color: #450084\ -}\ -.ace-xcode .ace_fold {\ -background-color: #C800A4;\ -border-color: #000000\ -}\ -.ace-xcode .ace_entity.ace_name.ace_tag,\ -.ace-xcode .ace_support.ace_class,\ -.ace-xcode .ace_support.ace_type {\ -color: #790EAD\ -}\ -.ace-xcode .ace_storage {\ -color: #C900A4\ -}\ -.ace-xcode .ace_string {\ -color: #DF0002\ -}\ -.ace-xcode .ace_comment {\ -color: #008E00\ -}\ -.ace-xcode .ace_indent-guide {\ -background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==) right repeat-y\ -}"; - -var dom = acequire("../lib/dom"); -dom.importCssString(exports.cssText, exports.cssClass); -}); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports) { - -ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"], function(acequire, exports, module) { - 'use strict'; - - function log() { - var d = ""; - function format(p) { - if (typeof p != "object") - return p + ""; - if ("line" in p) { - return p.line + ":" + p.ch; - } - if ("anchor" in p) { - return format(p.anchor) + "->" + format(p.head); - } - if (Array.isArray(p)) - return "[" + p.map(function(x) { - return format(x); - }) + "]"; - return JSON.stringify(p); - } - for (var i = 0; i < arguments.length; i++) { - var p = arguments[i]; - var f = format(p); - d += f + " "; - } - console.log(d); - } - var Range = acequire("../range").Range; - var EventEmitter = acequire("../lib/event_emitter").EventEmitter; - var dom = acequire("../lib/dom"); - var oop = acequire("../lib/oop"); - var KEYS = acequire("../lib/keys"); - var event = acequire("../lib/event"); - var Search = acequire("../search").Search; - var useragent = acequire("../lib/useragent"); - var SearchHighlight = acequire("../search_highlight").SearchHighlight; - var multiSelectCommands = acequire("../commands/multi_select_commands"); - var TextModeTokenRe = acequire("../mode/text").Mode.prototype.tokenRe; - acequire("../multi_select"); - - var CodeMirror = function(ace) { - this.ace = ace; - this.state = {}; - this.marks = {}; - this.$uid = 0; - this.onChange = this.onChange.bind(this); - this.onSelectionChange = this.onSelectionChange.bind(this); - this.onBeforeEndOperation = this.onBeforeEndOperation.bind(this); - this.ace.on('change', this.onChange); - this.ace.on('changeSelection', this.onSelectionChange); - this.ace.on('beforeEndOperation', this.onBeforeEndOperation); - }; - CodeMirror.Pos = function(line, ch) { - if (!(this instanceof Pos)) return new Pos(line, ch); - this.line = line; this.ch = ch; - }; - CodeMirror.defineOption = function(name, val, setter) {}; - CodeMirror.commands = { - redo: function(cm) { cm.ace.redo(); }, - undo: function(cm) { cm.ace.undo(); }, - newlineAndIndent: function(cm) { cm.ace.insert("\n"); } - }; - CodeMirror.keyMap = {}; - CodeMirror.addClass = CodeMirror.rmClass = - CodeMirror.e_stop = function() {}; - CodeMirror.keyName = function(e) { - if (e.key) return e.key; - var key = (KEYS[e.keyCode] || ""); - if (key.length == 1) key = key.toUpperCase(); - key = event.getModifierString(e).replace(/(^|-)\w/g, function(m) { - return m.toUpperCase(); - }) + key; - return key; - }; - CodeMirror.keyMap['default'] = function(key) { - return function(cm) { - var cmd = cm.ace.commands.commandKeyBinding[key.toLowerCase()]; - return cmd && cm.ace.execCommand(cmd) !== false; - }; - }; - CodeMirror.lookupKey = function lookupKey(key, map, handle) { - if (typeof map == "string") - map = CodeMirror.keyMap[map]; - var found = typeof map == "function" ? map(key) : map[key]; - if (found === false) return "nothing"; - if (found === "...") return "multi"; - if (found != null && handle(found)) return "handled"; - - if (map.fallthrough) { - if (!Array.isArray(map.fallthrough)) - return lookupKey(key, map.fallthrough, handle); - for (var i = 0; i < map.fallthrough.length; i++) { - var result = lookupKey(key, map.fallthrough[i], handle); - if (result) return result; - } - } - }; - - CodeMirror.signal = function(o, name, e) { return o._signal(name, e) }; - CodeMirror.on = event.addListener; - CodeMirror.off = event.removeListener; - CodeMirror.isWordChar = function(ch) { - if (ch < "\x7f") return /^\w$/.test(ch); - TextModeTokenRe.lastIndex = 0; - return TextModeTokenRe.test(ch); - }; - -(function() { - oop.implement(CodeMirror.prototype, EventEmitter); - - this.destroy = function() { - this.ace.off('change', this.onChange); - this.ace.off('changeSelection', this.onSelectionChange); - this.ace.off('beforeEndOperation', this.onBeforeEndOperation); - this.removeOverlay(); - }; - this.virtualSelectionMode = function() { - return this.ace.inVirtualSelectionMode && this.ace.selection.index; - }; - this.onChange = function(delta) { - var change = { text: delta.action[0] == 'i' ? delta.lines : [] }; - var curOp = this.curOp = this.curOp || {}; - if (!curOp.changeHandlers) - curOp.changeHandlers = this._eventRegistry["change"] && this._eventRegistry["change"].slice(); - if (this.virtualSelectionMode()) return; - if (!curOp.lastChange) { - curOp.lastChange = curOp.change = change; - } else { - curOp.lastChange.next = curOp.lastChange = change; - } - this.$updateMarkers(delta); - }; - this.onSelectionChange = function() { - var curOp = this.curOp = this.curOp || {}; - if (!curOp.cursorActivityHandlers) - curOp.cursorActivityHandlers = this._eventRegistry["cursorActivity"] && this._eventRegistry["cursorActivity"].slice(); - this.curOp.cursorActivity = true; - if (this.ace.inMultiSelectMode) { - this.ace.keyBinding.removeKeyboardHandler(multiSelectCommands.keyboardHandler); - } - }; - this.operation = function(fn, force) { - if (!force && this.curOp || force && this.curOp && this.curOp.force) { - return fn(); - } - if (force || !this.ace.curOp) { - if (this.curOp) - this.onBeforeEndOperation(); - } - if (!this.ace.curOp) { - var prevOp = this.ace.prevOp; - this.ace.startOperation({ - command: { name: "vim", scrollIntoView: "cursor" } - }); - } - var curOp = this.curOp = this.curOp || {}; - this.curOp.force = force; - var result = fn(); - if (this.ace.curOp && this.ace.curOp.command.name == "vim") { - this.ace.endOperation(); - if (!curOp.cursorActivity && !curOp.lastChange && prevOp) - this.ace.prevOp = prevOp; - } - if (force || !this.ace.curOp) { - if (this.curOp) - this.onBeforeEndOperation(); - } - return result; - }; - this.onBeforeEndOperation = function() { - var op = this.curOp; - if (op) { - if (op.change) { this.signal("change", op.change, op); } - if (op && op.cursorActivity) { this.signal("cursorActivity", null, op); } - this.curOp = null; - } - }; - - this.signal = function(eventName, e, handlers) { - var listeners = handlers ? handlers[eventName + "Handlers"] - : (this._eventRegistry || {})[eventName]; - if (!listeners) - return; - listeners = listeners.slice(); - for (var i=0; i 0) { - point.row += rowShift; - point.column += point.row == end.row ? colShift : 0; - continue; - } - if (!isInsert && cmp2 <= 0) { - point.row = start.row; - point.column = start.column; - if (cmp2 === 0) - point.bias = 1; - } - } - }; - var Marker = function(cm, id, row, column) { - this.cm = cm; - this.id = id; - this.row = row; - this.column = column; - cm.marks[this.id] = this; - }; - Marker.prototype.clear = function() { delete this.cm.marks[this.id] }; - Marker.prototype.find = function() { return toCmPos(this) }; - this.setBookmark = function(cursor, options) { - var bm = new Marker(this, this.$uid++, cursor.line, cursor.ch); - if (!options || !options.insertLeft) - bm.$insertRight = true; - this.marks[bm.id] = bm; - return bm; - }; - this.moveH = function(increment, unit) { - if (unit == 'char') { - var sel = this.ace.selection; - sel.clearSelection(); - sel.moveCursorBy(0, increment); - } - }; - this.findPosV = function(start, amount, unit, goalColumn) { - if (unit == 'page') { - var renderer = this.ace.renderer; - var config = renderer.layerConfig; - amount = amount * Math.floor(config.height / config.lineHeight); - unit = 'line'; - } - if (unit == 'line') { - var screenPos = this.ace.session.documentToScreenPosition(start.line, start.ch); - if (goalColumn != null) - screenPos.column = goalColumn; - screenPos.row += amount; - screenPos.row = Math.min(Math.max(0, screenPos.row), this.ace.session.getScreenLength() - 1); - var pos = this.ace.session.screenToDocumentPosition(screenPos.row, screenPos.column); - return toCmPos(pos); - } else { - debugger; - } - }; - this.charCoords = function(pos, mode) { - if (mode == 'div' || !mode) { - var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); - return {left: sc.column, top: sc.row}; - }if (mode == 'local') { - var renderer = this.ace.renderer; - var sc = this.ace.session.documentToScreenPosition(pos.line, pos.ch); - var lh = renderer.layerConfig.lineHeight; - var cw = renderer.layerConfig.characterWidth; - var top = lh * sc.row; - return {left: sc.column * cw, top: top, bottom: top + lh}; - } - }; - this.coordsChar = function(pos, mode) { - var renderer = this.ace.renderer; - if (mode == 'local') { - var row = Math.max(0, Math.floor(pos.top / renderer.lineHeight)); - var col = Math.max(0, Math.floor(pos.left / renderer.characterWidth)); - var ch = renderer.session.screenToDocumentPosition(row, col); - return toCmPos(ch); - } else if (mode == 'div') { - throw "not implemented"; - } - }; - this.getSearchCursor = function(query, pos, caseFold) { - var caseSensitive = false; - var isRegexp = false; - if (query instanceof RegExp && !query.global) { - caseSensitive = !query.ignoreCase; - query = query.source; - isRegexp = true; - } - var search = new Search(); - if (pos.ch == undefined) pos.ch = Number.MAX_VALUE; - var acePos = {row: pos.line, column: pos.ch}; - var cm = this; - var last = null; - return { - findNext: function() { return this.find(false) }, - findPrevious: function() {return this.find(true) }, - find: function(back) { - search.setOptions({ - needle: query, - caseSensitive: caseSensitive, - wrap: false, - backwards: back, - regExp: isRegexp, - start: last || acePos - }); - var range = search.find(cm.ace.session); - if (range && range.isEmpty()) { - if (cm.getLine(range.start.row).length == range.start.column) { - search.$options.start = range; - range = search.find(cm.ace.session); - } - } - last = range; - return last; - }, - from: function() { return last && toCmPos(last.start) }, - to: function() { return last && toCmPos(last.end) }, - replace: function(text) { - if (last) { - last.end = cm.ace.session.doc.replace(last, text); - } - } - }; - }; - this.scrollTo = function(x, y) { - var renderer = this.ace.renderer; - var config = renderer.layerConfig; - var maxHeight = config.maxHeight; - maxHeight -= (renderer.$size.scrollerHeight - renderer.lineHeight) * renderer.$scrollPastEnd; - if (y != null) this.ace.session.setScrollTop(Math.max(0, Math.min(y, maxHeight))); - if (x != null) this.ace.session.setScrollLeft(Math.max(0, Math.min(x, config.width))); - }; - this.scrollInfo = function() { return 0; }; - this.scrollIntoView = function(pos, margin) { - if (pos) { - var renderer = this.ace.renderer; - var viewMargin = { "top": 0, "bottom": margin }; - renderer.scrollCursorIntoView(toAcePos(pos), - (renderer.lineHeight * 2) / renderer.$size.scrollerHeight, viewMargin); - } - }; - this.getLine = function(row) { return this.ace.session.getLine(row) }; - this.getRange = function(s, e) { - return this.ace.session.getTextRange(new Range(s.line, s.ch, e.line, e.ch)); - }; - this.replaceRange = function(text, s, e) { - if (!e) e = s; - return this.ace.session.replace(new Range(s.line, s.ch, e.line, e.ch), text); - }; - this.replaceSelections = function(p) { - var sel = this.ace.selection; - if (this.ace.inVirtualSelectionMode) { - this.ace.session.replace(sel.getRange(), p[0] || ""); - return; - } - sel.inVirtualSelectionMode = true; - var ranges = sel.rangeList.ranges; - if (!ranges.length) ranges = [this.ace.multiSelect.getRange()]; - for (var i = ranges.length; i--;) - this.ace.session.replace(ranges[i], p[i] || ""); - sel.inVirtualSelectionMode = false; - }; - this.getSelection = function() { - return this.ace.getSelectedText(); - }; - this.getSelections = function() { - return this.listSelections().map(function(x) { - return this.getRange(x.anchor, x.head); - }, this); - }; - this.getInputField = function() { - return this.ace.textInput.getElement(); - }; - this.getWrapperElement = function() { - return this.ace.containter; - }; - var optMap = { - indentWithTabs: "useSoftTabs", - indentUnit: "tabSize", - tabSize: "tabSize", - firstLineNumber: "firstLineNumber", - readOnly: "readOnly" - }; - this.setOption = function(name, val) { - this.state[name] = val; - switch (name) { - case 'indentWithTabs': - name = optMap[name]; - val = !val; - break; - default: - name = optMap[name]; - } - if (name) - this.ace.setOption(name, val); - }; - this.getOption = function(name, val) { - var aceOpt = optMap[name]; - if (aceOpt) - val = this.ace.getOption(aceOpt); - switch (name) { - case 'indentWithTabs': - name = optMap[name]; - return !val; - } - return aceOpt ? val : this.state[name]; - }; - this.toggleOverwrite = function(on) { - this.state.overwrite = on; - return this.ace.setOverwrite(on); - }; - this.addOverlay = function(o) { - if (!this.$searchHighlight || !this.$searchHighlight.session) { - var highlight = new SearchHighlight(null, "ace_highlight-marker", "text"); - var marker = this.ace.session.addDynamicMarker(highlight); - highlight.id = marker.id; - highlight.session = this.ace.session; - highlight.destroy = function(o) { - highlight.session.off("change", highlight.updateOnChange); - highlight.session.off("changeEditor", highlight.destroy); - highlight.session.removeMarker(highlight.id); - highlight.session = null; - }; - highlight.updateOnChange = function(delta) { - var row = delta.start.row; - if (row == delta.end.row) highlight.cache[row] = undefined; - else highlight.cache.splice(row, highlight.cache.length); - }; - highlight.session.on("changeEditor", highlight.destroy); - highlight.session.on("change", highlight.updateOnChange); - } - var re = new RegExp(o.query.source, "gmi"); - this.$searchHighlight = o.highlight = highlight; - this.$searchHighlight.setRegexp(re); - this.ace.renderer.updateBackMarkers(); - }; - this.removeOverlay = function(o) { - if (this.$searchHighlight && this.$searchHighlight.session) { - this.$searchHighlight.destroy(); - } - }; - this.getScrollInfo = function() { - var renderer = this.ace.renderer; - var config = renderer.layerConfig; - return { - left: renderer.scrollLeft, - top: renderer.scrollTop, - height: config.maxHeight, - width: config.width, - clientHeight: config.height, - clientWidth: config.width - }; - }; - this.getValue = function() { - return this.ace.getValue(); - }; - this.setValue = function(v) { - return this.ace.setValue(v); - }; - this.getTokenTypeAt = function(pos) { - var token = this.ace.session.getTokenAt(pos.line, pos.ch); - return token && /comment|string/.test(token.type) ? "string" : ""; - }; - this.findMatchingBracket = function(pos) { - var m = this.ace.session.findMatchingBracket(toAcePos(pos)); - return {to: m && toCmPos(m)}; - }; - this.indentLine = function(line, method) { - if (method === true) - this.ace.session.indentRows(line, line, "\t"); - else if (method === false) - this.ace.session.outdentRows(new Range(line, 0, line, 0)); - }; - this.indexFromPos = function(pos) { - return this.ace.session.doc.positionToIndex(toAcePos(pos)); - }; - this.posFromIndex = function(index) { - return toCmPos(this.ace.session.doc.indexToPosition(index)); - }; - this.focus = function(index) { - return this.ace.focus(); - }; - this.blur = function(index) { - return this.ace.blur(); - }; - this.defaultTextHeight = function(index) { - return this.ace.renderer.layerConfig.lineHeight; - }; - this.scanForBracket = function(pos, dir, _, options) { - var re = options.bracketRegex.source; - if (dir == 1) { - var m = this.ace.session.$findClosingBracket(re.slice(1, 2), toAcePos(pos), /paren|text/); - } else { - var m = this.ace.session.$findOpeningBracket(re.slice(-2, -1), {row: pos.line, column: pos.ch + 1}, /paren|text/); - } - return m && {pos: toCmPos(m)}; - }; - this.refresh = function() { - return this.ace.resize(true); - }; - this.getMode = function() { - return { name : this.getOption("mode") }; - } -}).call(CodeMirror.prototype); - function toAcePos(cmPos) { - return {row: cmPos.line, column: cmPos.ch}; - } - function toCmPos(acePos) { - return new Pos(acePos.row, acePos.column); - } - - var StringStream = CodeMirror.StringStream = function(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - }; - - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == this.lineStart;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() { - throw "not implemented"; - }, - indentation: function() { - throw "not implemented"; - }, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) this.pos += pattern.length; - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) return null; - if (match && consume !== false) this.pos += match[0].length; - return match; - } - }, - current: function(){return this.string.slice(this.start, this.pos);}, - hideFirstChars: function(n, inner) { - this.lineStart += n; - try { return inner(); } - finally { this.lineStart -= n; } - } - }; -CodeMirror.defineExtension = function(name, fn) { - CodeMirror.prototype[name] = fn; -}; -dom.importCssString(".normal-mode .ace_cursor{\ - border: 1px solid red;\ - background-color: red;\ - opacity: 0.5;\ -}\ -.normal-mode .ace_hidden-cursors .ace_cursor{\ - background-color: transparent;\ -}\ -.ace_dialog {\ - position: absolute;\ - left: 0; right: 0;\ - background: white;\ - z-index: 15;\ - padding: .1em .8em;\ - overflow: hidden;\ - color: #333;\ -}\ -.ace_dialog-top {\ - border-bottom: 1px solid #eee;\ - top: 0;\ -}\ -.ace_dialog-bottom {\ - border-top: 1px solid #eee;\ - bottom: 0;\ -}\ -.ace_dialog input {\ - border: none;\ - outline: none;\ - background: transparent;\ - width: 20em;\ - color: inherit;\ - font-family: monospace;\ -}", "vimMode"); -(function() { - function dialogDiv(cm, template, bottom) { - var wrap = cm.ace.container; - var dialog; - dialog = wrap.appendChild(document.createElement("div")); - if (bottom) - dialog.className = "ace_dialog ace_dialog-bottom"; - else - dialog.className = "ace_dialog ace_dialog-top"; - - if (typeof template == "string") { - dialog.innerHTML = template; - } else { // Assuming it's a detached DOM element. - dialog.appendChild(template); - } - return dialog; - } - - function closeNotification(cm, newVal) { - if (cm.state.currentNotificationClose) - cm.state.currentNotificationClose(); - cm.state.currentNotificationClose = newVal; - } - - CodeMirror.defineExtension("openDialog", function(template, callback, options) { - if (this.virtualSelectionMode()) return; - if (!options) options = {}; - - closeNotification(this, null); - - var dialog = dialogDiv(this, template, options.bottom); - var closed = false, me = this; - function close(newVal) { - if (typeof newVal == 'string') { - inp.value = newVal; - } else { - if (closed) return; - closed = true; - dialog.parentNode.removeChild(dialog); - me.focus(); - - if (options.onClose) options.onClose(dialog); - } - } - - var inp = dialog.getElementsByTagName("input")[0], button; - if (inp) { - if (options.value) { - inp.value = options.value; - if (options.select !== false) inp.select(); - } - - if (options.onInput) - CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);}); - if (options.onKeyUp) - CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);}); - - CodeMirror.on(inp, "keydown", function(e) { - if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; } - if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) { - inp.blur(); - CodeMirror.e_stop(e); - close(); - } - if (e.keyCode == 13) callback(inp.value); - }); - - if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close); - - inp.focus(); - } else if (button = dialog.getElementsByTagName("button")[0]) { - CodeMirror.on(button, "click", function() { - close(); - me.focus(); - }); - - if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); - - button.focus(); - } - return close; - }); - - CodeMirror.defineExtension("openNotification", function(template, options) { - if (this.virtualSelectionMode()) return; - closeNotification(this, close); - var dialog = dialogDiv(this, template, options && options.bottom); - var closed = false, doneTimer; - var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000; - - function close() { - if (closed) return; - closed = true; - clearTimeout(doneTimer); - dialog.parentNode.removeChild(dialog); - } - - CodeMirror.on(dialog, 'click', function(e) { - CodeMirror.e_preventDefault(e); - close(); - }); - - if (duration) - doneTimer = setTimeout(close, duration); - - return close; - }); -})(); - - - var defaultKeymap = [ - { keys: '', type: 'keyToKey', toKeys: 'h' }, - { keys: '', type: 'keyToKey', toKeys: 'l' }, - { keys: '', type: 'keyToKey', toKeys: 'k' }, - { keys: '', type: 'keyToKey', toKeys: 'j' }, - { keys: '', type: 'keyToKey', toKeys: 'l' }, - { keys: '', type: 'keyToKey', toKeys: 'h', context: 'normal'}, - { keys: '', type: 'keyToKey', toKeys: 'W' }, - { keys: '', type: 'keyToKey', toKeys: 'B', context: 'normal' }, - { keys: '', type: 'keyToKey', toKeys: 'w' }, - { keys: '', type: 'keyToKey', toKeys: 'b', context: 'normal' }, - { keys: '', type: 'keyToKey', toKeys: 'j' }, - { keys: '', type: 'keyToKey', toKeys: 'k' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, - { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, - { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' }, - { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'}, - { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' }, - { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' }, - { keys: '', type: 'keyToKey', toKeys: '0' }, - { keys: '', type: 'keyToKey', toKeys: '$' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: '' }, - { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' }, - { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }}, - { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }}, - { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }}, - { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }}, - { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }}, - { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }}, - { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }}, - { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }}, - { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }}, - { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }}, - { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }}, - { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }}, - { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }}, - { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }}, - { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }}, - { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }}, - { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }}, - { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }}, - { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }}, - { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }}, - { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }}, - { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }}, - { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }}, - { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }}, - { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }}, - { keys: '0', type: 'motion', motion: 'moveToStartOfLine' }, - { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }}, - { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }}, - { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }}, - { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }}, - { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }}, - { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }}, - { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }}, - { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }}, - { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }}, - { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }}, - { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }}, - { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}}, - { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, - { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } }, - { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } }, - { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } }, - { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } }, - { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}}, - { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}}, - { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}}, - { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}}, - { keys: '|', type: 'motion', motion: 'moveToColumn'}, - { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'}, - { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'}, - { keys: 'd', type: 'operator', operator: 'delete' }, - { keys: 'y', type: 'operator', operator: 'yank' }, - { keys: 'c', type: 'operator', operator: 'change' }, - { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }}, - { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }}, - { keys: 'g~', type: 'operator', operator: 'changeCase' }, - { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true }, - { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true }, - { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }}, - { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }}, - { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }}, - { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }}, - { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, - { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'}, - { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, - { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'}, - { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, - { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'}, - { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'}, - { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'}, - { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' }, - { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }}, - { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }}, - { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }}, - { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }}, - { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' }, - { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' }, - { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' }, - { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' }, - { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' }, - { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' }, - { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' }, - { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' }, - { keys: 'v', type: 'action', action: 'toggleVisualMode' }, - { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }}, - { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, - { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, - { keys: 'gv', type: 'action', action: 'reselectLastSelection' }, - { keys: 'J', type: 'action', action: 'joinLines', isEdit: true }, - { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }}, - { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }}, - { keys: 'r', type: 'action', action: 'replace', isEdit: true }, - { keys: '@', type: 'action', action: 'replayMacro' }, - { keys: 'q', type: 'action', action: 'enterMacroRecordMode' }, - { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }}, - { keys: 'u', type: 'action', action: 'undo', context: 'normal' }, - { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true }, - { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true }, - { keys: '', type: 'action', action: 'redo' }, - { keys: 'm', type: 'action', action: 'setMark' }, - { keys: '"', type: 'action', action: 'setRegister' }, - { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }}, - { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }}, - { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }}, - { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, - { keys: '.', type: 'action', action: 'repeatLastEdit' }, - { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}}, - { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}}, - { keys: 'a', type: 'motion', motion: 'textObjectManipulation' }, - { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }}, - { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }}, - { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }}, - { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, - { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, - { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }}, - { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }}, - { keys: ':', type: 'ex' } - ]; - var defaultExCommandMap = [ - { name: 'colorscheme', shortName: 'colo' }, - { name: 'map' }, - { name: 'imap', shortName: 'im' }, - { name: 'nmap', shortName: 'nm' }, - { name: 'vmap', shortName: 'vm' }, - { name: 'unmap' }, - { name: 'write', shortName: 'w' }, - { name: 'quit', shortName: 'q' }, - { name: 'xwritequit', shortName: 'x'}, - { name: 'wqwritequit', shortName: 'wq'}, - { name: 'undo', shortName: 'u' }, - { name: 'redo', shortName: 'red' }, - { name: 'set', shortName: 'se' }, - { name: 'set', shortName: 'se' }, - { name: 'setlocal', shortName: 'setl' }, - { name: 'setglobal', shortName: 'setg' }, - { name: 'sort', shortName: 'sor' }, - { name: 'substitute', shortName: 's', possiblyAsync: true }, - { name: 'nohlsearch', shortName: 'noh' }, - { name: 'delmarks', shortName: 'delm' }, - { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true }, - { name: 'global', shortName: 'g' } - ]; - - var Pos = CodeMirror.Pos; - - var Vim = function() { return vimApi; } //{ - function enterVimMode(cm) { - cm.setOption('disableInput', true); - cm.setOption('showCursorWhenSelecting', false); - CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); - cm.on('cursorActivity', onCursorActivity); - maybeInitVimState(cm); - CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm)); - } - - function leaveVimMode(cm) { - cm.setOption('disableInput', false); - cm.off('cursorActivity', onCursorActivity); - CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm)); - cm.state.vim = null; - } - - function detachVimMap(cm, next) { - if (this == CodeMirror.keyMap.vim) - CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor"); - - if (!next || next.attach != attachVimMap) - leaveVimMode(cm, false); - } - function attachVimMap(cm, prev) { - if (this == CodeMirror.keyMap.vim) - CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor"); - - if (!prev || prev.attach != attachVimMap) - enterVimMode(cm); - } - CodeMirror.defineOption('vimMode', false, function(cm, val, prev) { - if (val && cm.getOption("keyMap") != "vim") - cm.setOption("keyMap", "vim"); - else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap"))) - cm.setOption("keyMap", "default"); - }); - - function cmKey(key, cm) { - if (!cm) { return undefined; } - var vimKey = cmKeyToVimKey(key); - if (!vimKey) { - return false; - } - var cmd = CodeMirror.Vim.findKey(cm, vimKey); - if (typeof cmd == 'function') { - CodeMirror.signal(cm, 'vim-keypress', vimKey); - } - return cmd; - } - - var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'}; - var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del'}; - function cmKeyToVimKey(key) { - if (key.charAt(0) == '\'') { - return key.charAt(1); - } - var pieces = key.split(/-(?!$)/); - var lastPiece = pieces[pieces.length - 1]; - if (pieces.length == 1 && pieces[0].length == 1) { - return false; - } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) { - return false; - } - var hasCharacter = false; - for (var i = 0; i < pieces.length; i++) { - var piece = pieces[i]; - if (piece in modifiers) { pieces[i] = modifiers[piece]; } - else { hasCharacter = true; } - if (piece in specialKeys) { pieces[i] = specialKeys[piece]; } - } - if (!hasCharacter) { - return false; - } - if (isUpperCase(lastPiece)) { - pieces[pieces.length - 1] = lastPiece.toLowerCase(); - } - return '<' + pieces.join('-') + '>'; - } - - function getOnPasteFn(cm) { - var vim = cm.state.vim; - if (!vim.onPasteFn) { - vim.onPasteFn = function() { - if (!vim.insertMode) { - cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); - actions.enterInsertMode(cm, {}, vim); - } - }; - } - return vim.onPasteFn; - } - - var numberRegex = /[\d]/; - var wordCharTest = [CodeMirror.isWordChar, function(ch) { - return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch); - }], bigWordCharTest = [function(ch) { - return /\S/.test(ch); - }]; - function makeKeyRange(start, size) { - var keys = []; - for (var i = start; i < start + size; i++) { - keys.push(String.fromCharCode(i)); - } - return keys; - } - var upperCaseAlphabet = makeKeyRange(65, 26); - var lowerCaseAlphabet = makeKeyRange(97, 26); - var numbers = makeKeyRange(48, 10); - var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']); - var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']); - - function isLine(cm, line) { - return line >= cm.firstLine() && line <= cm.lastLine(); - } - function isLowerCase(k) { - return (/^[a-z]$/).test(k); - } - function isMatchableSymbol(k) { - return '()[]{}'.indexOf(k) != -1; - } - function isNumber(k) { - return numberRegex.test(k); - } - function isUpperCase(k) { - return (/^[A-Z]$/).test(k); - } - function isWhiteSpaceString(k) { - return (/^\s*$/).test(k); - } - function inArray(val, arr) { - for (var i = 0; i < arr.length; i++) { - if (arr[i] == val) { - return true; - } - } - return false; - } - - var options = {}; - function defineOption(name, defaultValue, type, aliases, callback) { - if (defaultValue === undefined && !callback) { - throw Error('defaultValue is acequired unless callback is provided'); - } - if (!type) { type = 'string'; } - options[name] = { - type: type, - defaultValue: defaultValue, - callback: callback - }; - if (aliases) { - for (var i = 0; i < aliases.length; i++) { - options[aliases[i]] = options[name]; - } - } - if (defaultValue) { - setOption(name, defaultValue); - } - } - - function setOption(name, value, cm, cfg) { - var option = options[name]; - cfg = cfg || {}; - var scope = cfg.scope; - if (!option) { - throw Error('Unknown option: ' + name); - } - if (option.type == 'boolean') { - if (value && value !== true) { - throw Error('Invalid argument: ' + name + '=' + value); - } else if (value !== false) { - value = true; - } - } - if (option.callback) { - if (scope !== 'local') { - option.callback(value, undefined); - } - if (scope !== 'global' && cm) { - option.callback(value, cm); - } - } else { - if (scope !== 'local') { - option.value = option.type == 'boolean' ? !!value : value; - } - if (scope !== 'global' && cm) { - cm.state.vim.options[name] = {value: value}; - } - } - } - - function getOption(name, cm, cfg) { - var option = options[name]; - cfg = cfg || {}; - var scope = cfg.scope; - if (!option) { - throw Error('Unknown option: ' + name); - } - if (option.callback) { - var local = cm && option.callback(undefined, cm); - if (scope !== 'global' && local !== undefined) { - return local; - } - if (scope !== 'local') { - return option.callback(); - } - return; - } else { - var local = (scope !== 'global') && (cm && cm.state.vim.options[name]); - return (local || (scope !== 'local') && option || {}).value; - } - } - - defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) { - if (cm === undefined) { - return; - } - if (name === undefined) { - var mode = cm.getOption('mode'); - return mode == 'null' ? '' : mode; - } else { - var mode = name == '' ? 'null' : name; - cm.setOption('mode', mode); - } - }); - - var createCircularJumpList = function() { - var size = 100; - var pointer = -1; - var head = 0; - var tail = 0; - var buffer = new Array(size); - function add(cm, oldCur, newCur) { - var current = pointer % size; - var curMark = buffer[current]; - function useNextSlot(cursor) { - var next = ++pointer % size; - var trashMark = buffer[next]; - if (trashMark) { - trashMark.clear(); - } - buffer[next] = cm.setBookmark(cursor); - } - if (curMark) { - var markPos = curMark.find(); - if (markPos && !cursorEqual(markPos, oldCur)) { - useNextSlot(oldCur); - } - } else { - useNextSlot(oldCur); - } - useNextSlot(newCur); - head = pointer; - tail = pointer - size + 1; - if (tail < 0) { - tail = 0; - } - } - function move(cm, offset) { - pointer += offset; - if (pointer > head) { - pointer = head; - } else if (pointer < tail) { - pointer = tail; - } - var mark = buffer[(size + pointer) % size]; - if (mark && !mark.find()) { - var inc = offset > 0 ? 1 : -1; - var newCur; - var oldCur = cm.getCursor(); - do { - pointer += inc; - mark = buffer[(size + pointer) % size]; - if (mark && - (newCur = mark.find()) && - !cursorEqual(oldCur, newCur)) { - break; - } - } while (pointer < head && pointer > tail); - } - return mark; - } - return { - cachedCursor: undefined, //used for # and * jumps - add: add, - move: move - }; - }; - var createInsertModeChanges = function(c) { - if (c) { - return { - changes: c.changes, - expectCursorActivityForChange: c.expectCursorActivityForChange - }; - } - return { - changes: [], - expectCursorActivityForChange: false - }; - }; - - function MacroModeState() { - this.latestRegister = undefined; - this.isPlaying = false; - this.isRecording = false; - this.replaySearchQueries = []; - this.onRecordingDone = undefined; - this.lastInsertModeChanges = createInsertModeChanges(); - } - MacroModeState.prototype = { - exitMacroRecordMode: function() { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.onRecordingDone) { - macroModeState.onRecordingDone(); // close dialog - } - macroModeState.onRecordingDone = undefined; - macroModeState.isRecording = false; - }, - enterMacroRecordMode: function(cm, registerName) { - var register = - vimGlobalState.registerController.getRegister(registerName); - if (register) { - register.clear(); - this.latestRegister = registerName; - if (cm.openDialog) { - this.onRecordingDone = cm.openDialog( - '(recording)['+registerName+']', null, {bottom:true}); - } - this.isRecording = true; - } - } - }; - - function maybeInitVimState(cm) { - if (!cm.state.vim) { - cm.state.vim = { - inputState: new InputState(), - lastEditInputState: undefined, - lastEditActionCommand: undefined, - lastHPos: -1, - lastHSPos: -1, - lastMotion: null, - marks: {}, - fakeCursor: null, - insertMode: false, - insertModeRepeat: undefined, - visualMode: false, - visualLine: false, - visualBlock: false, - lastSelection: null, - lastPastedText: null, - sel: {}, - options: {} - }; - } - return cm.state.vim; - } - var vimGlobalState; - function resetVimGlobalState() { - vimGlobalState = { - searchQuery: null, - searchIsReversed: false, - lastSubstituteReplacePart: undefined, - jumpList: createCircularJumpList(), - macroModeState: new MacroModeState, - lastChararacterSearch: {increment:0, forward:true, selectedCharacter:''}, - registerController: new RegisterController({}), - searchHistoryController: new HistoryController({}), - exCommandHistoryController : new HistoryController({}) - }; - for (var optionName in options) { - var option = options[optionName]; - option.value = option.defaultValue; - } - } - - var lastInsertModeKeyTimer; - var vimApi= { - buildKeyMap: function() { - }, - getRegisterController: function() { - return vimGlobalState.registerController; - }, - resetVimGlobalState_: resetVimGlobalState, - getVimGlobalState_: function() { - return vimGlobalState; - }, - maybeInitVimState_: maybeInitVimState, - - suppressErrorLogging: false, - - InsertModeKey: InsertModeKey, - map: function(lhs, rhs, ctx) { - exCommandDispatcher.map(lhs, rhs, ctx); - }, - unmap: function(lhs, ctx) { - exCommandDispatcher.unmap(lhs, ctx); - }, - setOption: setOption, - getOption: getOption, - defineOption: defineOption, - defineEx: function(name, prefix, func){ - if (!prefix) { - prefix = name; - } else if (name.indexOf(prefix) !== 0) { - throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered'); - } - exCommands[name]=func; - exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; - }, - handleKey: function (cm, key, origin) { - var command = this.findKey(cm, key, origin); - if (typeof command === 'function') { - return command(); - } - }, - findKey: function(cm, key, origin) { - var vim = maybeInitVimState(cm); - function handleMacroRecording() { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isRecording) { - if (key == 'q') { - macroModeState.exitMacroRecordMode(); - clearInputState(cm); - return true; - } - if (origin != 'mapping') { - logKey(macroModeState, key); - } - } - } - function handleEsc() { - if (key == '') { - clearInputState(cm); - if (vim.visualMode) { - exitVisualMode(cm); - } else if (vim.insertMode) { - exitInsertMode(cm); - } - return true; - } - } - function doKeyToKey(keys) { - var match; - while (keys) { - match = (/<\w+-.+?>|<\w+>|./).exec(keys); - key = match[0]; - keys = keys.substring(match.index + key.length); - CodeMirror.Vim.handleKey(cm, key, 'mapping'); - } - } - - function handleKeyInsertMode() { - if (handleEsc()) { return true; } - var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; - var keysAreChars = key.length == 1; - var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); - while (keys.length > 1 && match.type != 'full') { - var keys = vim.inputState.keyBuffer = keys.slice(1); - var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); - if (thisMatch.type != 'none') { match = thisMatch; } - } - if (match.type == 'none') { clearInputState(cm); return false; } - else if (match.type == 'partial') { - if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } - lastInsertModeKeyTimer = window.setTimeout( - function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } }, - getOption('insertModeEscKeysTimeout')); - return !keysAreChars; - } - - if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } - if (keysAreChars) { - var selections = cm.listSelections(); - for (var i = 0; i < selections.length; i++) { - var here = selections[i].head; - cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input'); - } - vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop(); - } - clearInputState(cm); - return match.command; - } - - function handleKeyNonInsertMode() { - if (handleMacroRecording() || handleEsc()) { return true; } - - var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; - if (/^[1-9]\d*$/.test(keys)) { return true; } - - var keysMatcher = /^(\d*)(.*)$/.exec(keys); - if (!keysMatcher) { clearInputState(cm); return false; } - var context = vim.visualMode ? 'visual' : - 'normal'; - var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context); - if (match.type == 'none') { clearInputState(cm); return false; } - else if (match.type == 'partial') { return true; } - - vim.inputState.keyBuffer = ''; - var keysMatcher = /^(\d*)(.*)$/.exec(keys); - if (keysMatcher[1] && keysMatcher[1] != '0') { - vim.inputState.pushRepeatDigit(keysMatcher[1]); - } - return match.command; - } - - var command; - if (vim.insertMode) { command = handleKeyInsertMode(); } - else { command = handleKeyNonInsertMode(); } - if (command === false) { - return undefined; - } else if (command === true) { - return function() { return true; }; - } else { - return function() { - if ((command.operator || command.isEdit) && cm.getOption('readOnly')) - return; // ace_patch - return cm.operation(function() { - cm.curOp.isVimOp = true; - try { - if (command.type == 'keyToKey') { - doKeyToKey(command.toKeys); - } else { - commandDispatcher.processCommand(cm, vim, command); - } - } catch (e) { - cm.state.vim = undefined; - maybeInitVimState(cm); - if (!CodeMirror.Vim.suppressErrorLogging) { - console['log'](e); - } - throw e; - } - return true; - }); - }; - } - }, - handleEx: function(cm, input) { - exCommandDispatcher.processCommand(cm, input); - }, - - defineMotion: defineMotion, - defineAction: defineAction, - defineOperator: defineOperator, - mapCommand: mapCommand, - _mapCommand: _mapCommand, - - defineRegister: defineRegister, - - exitVisualMode: exitVisualMode, - exitInsertMode: exitInsertMode - }; - function InputState() { - this.prefixRepeat = []; - this.motionRepeat = []; - - this.operator = null; - this.operatorArgs = null; - this.motion = null; - this.motionArgs = null; - this.keyBuffer = []; // For matching multi-key commands. - this.registerName = null; // Defaults to the unnamed register. - } - InputState.prototype.pushRepeatDigit = function(n) { - if (!this.operator) { - this.prefixRepeat = this.prefixRepeat.concat(n); - } else { - this.motionRepeat = this.motionRepeat.concat(n); - } - }; - InputState.prototype.getRepeat = function() { - var repeat = 0; - if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) { - repeat = 1; - if (this.prefixRepeat.length > 0) { - repeat *= parseInt(this.prefixRepeat.join(''), 10); - } - if (this.motionRepeat.length > 0) { - repeat *= parseInt(this.motionRepeat.join(''), 10); - } - } - return repeat; - }; - - function clearInputState(cm, reason) { - cm.state.vim.inputState = new InputState(); - CodeMirror.signal(cm, 'vim-command-done', reason); - } - function Register(text, linewise, blockwise) { - this.clear(); - this.keyBuffer = [text || '']; - this.insertModeChanges = []; - this.searchQueries = []; - this.linewise = !!linewise; - this.blockwise = !!blockwise; - } - Register.prototype = { - setText: function(text, linewise, blockwise) { - this.keyBuffer = [text || '']; - this.linewise = !!linewise; - this.blockwise = !!blockwise; - }, - pushText: function(text, linewise) { - if (linewise) { - if (!this.linewise) { - this.keyBuffer.push('\n'); - } - this.linewise = true; - } - this.keyBuffer.push(text); - }, - pushInsertModeChanges: function(changes) { - this.insertModeChanges.push(createInsertModeChanges(changes)); - }, - pushSearchQuery: function(query) { - this.searchQueries.push(query); - }, - clear: function() { - this.keyBuffer = []; - this.insertModeChanges = []; - this.searchQueries = []; - this.linewise = false; - }, - toString: function() { - return this.keyBuffer.join(''); - } - }; - function defineRegister(name, register) { - var registers = vimGlobalState.registerController.registers[name]; - if (!name || name.length != 1) { - throw Error('Register name must be 1 character'); - } - registers[name] = register; - validRegisters.push(name); - } - function RegisterController(registers) { - this.registers = registers; - this.unnamedRegister = registers['"'] = new Register(); - registers['.'] = new Register(); - registers[':'] = new Register(); - registers['/'] = new Register(); - } - RegisterController.prototype = { - pushText: function(registerName, operator, text, linewise, blockwise) { - if (linewise && text.charAt(0) == '\n') { - text = text.slice(1) + '\n'; - } - if (linewise && text.charAt(text.length - 1) !== '\n'){ - text += '\n'; - } - var register = this.isValidRegister(registerName) ? - this.getRegister(registerName) : null; - if (!register) { - switch (operator) { - case 'yank': - this.registers['0'] = new Register(text, linewise, blockwise); - break; - case 'delete': - case 'change': - if (text.indexOf('\n') == -1) { - this.registers['-'] = new Register(text, linewise); - } else { - this.shiftNumericRegisters_(); - this.registers['1'] = new Register(text, linewise); - } - break; - } - this.unnamedRegister.setText(text, linewise, blockwise); - return; - } - var append = isUpperCase(registerName); - if (append) { - register.pushText(text, linewise); - } else { - register.setText(text, linewise, blockwise); - } - this.unnamedRegister.setText(register.toString(), linewise); - }, - getRegister: function(name) { - if (!this.isValidRegister(name)) { - return this.unnamedRegister; - } - name = name.toLowerCase(); - if (!this.registers[name]) { - this.registers[name] = new Register(); - } - return this.registers[name]; - }, - isValidRegister: function(name) { - return name && inArray(name, validRegisters); - }, - shiftNumericRegisters_: function() { - for (var i = 9; i >= 2; i--) { - this.registers[i] = this.getRegister('' + (i - 1)); - } - } - }; - function HistoryController() { - this.historyBuffer = []; - this.iterator; - this.initialPrefix = null; - } - HistoryController.prototype = { - nextMatch: function (input, up) { - var historyBuffer = this.historyBuffer; - var dir = up ? -1 : 1; - if (this.initialPrefix === null) this.initialPrefix = input; - for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) { - var element = historyBuffer[i]; - for (var j = 0; j <= element.length; j++) { - if (this.initialPrefix == element.substring(0, j)) { - this.iterator = i; - return element; - } - } - } - if (i >= historyBuffer.length) { - this.iterator = historyBuffer.length; - return this.initialPrefix; - } - if (i < 0 ) return input; - }, - pushInput: function(input) { - var index = this.historyBuffer.indexOf(input); - if (index > -1) this.historyBuffer.splice(index, 1); - if (input.length) this.historyBuffer.push(input); - }, - reset: function() { - this.initialPrefix = null; - this.iterator = this.historyBuffer.length; - } - }; - var commandDispatcher = { - matchCommand: function(keys, keyMap, inputState, context) { - var matches = commandMatches(keys, keyMap, context, inputState); - if (!matches.full && !matches.partial) { - return {type: 'none'}; - } else if (!matches.full && matches.partial) { - return {type: 'partial'}; - } - - var bestMatch; - for (var i = 0; i < matches.full.length; i++) { - var match = matches.full[i]; - if (!bestMatch) { - bestMatch = match; - } - } - if (bestMatch.keys.slice(-11) == '') { - inputState.selectedCharacter = lastChar(keys); - } - return {type: 'full', command: bestMatch}; - }, - processCommand: function(cm, vim, command) { - vim.inputState.repeatOverride = command.repeatOverride; - switch (command.type) { - case 'motion': - this.processMotion(cm, vim, command); - break; - case 'operator': - this.processOperator(cm, vim, command); - break; - case 'operatorMotion': - this.processOperatorMotion(cm, vim, command); - break; - case 'action': - this.processAction(cm, vim, command); - break; - case 'search': - this.processSearch(cm, vim, command); - break; - case 'ex': - case 'keyToEx': - this.processEx(cm, vim, command); - break; - default: - break; - } - }, - processMotion: function(cm, vim, command) { - vim.inputState.motion = command.motion; - vim.inputState.motionArgs = copyArgs(command.motionArgs); - this.evalInput(cm, vim); - }, - processOperator: function(cm, vim, command) { - var inputState = vim.inputState; - if (inputState.operator) { - if (inputState.operator == command.operator) { - inputState.motion = 'expandToLine'; - inputState.motionArgs = { linewise: true }; - this.evalInput(cm, vim); - return; - } else { - clearInputState(cm); - } - } - inputState.operator = command.operator; - inputState.operatorArgs = copyArgs(command.operatorArgs); - if (vim.visualMode) { - this.evalInput(cm, vim); - } - }, - processOperatorMotion: function(cm, vim, command) { - var visualMode = vim.visualMode; - var operatorMotionArgs = copyArgs(command.operatorMotionArgs); - if (operatorMotionArgs) { - if (visualMode && operatorMotionArgs.visualLine) { - vim.visualLine = true; - } - } - this.processOperator(cm, vim, command); - if (!visualMode) { - this.processMotion(cm, vim, command); - } - }, - processAction: function(cm, vim, command) { - var inputState = vim.inputState; - var repeat = inputState.getRepeat(); - var repeatIsExplicit = !!repeat; - var actionArgs = copyArgs(command.actionArgs) || {}; - if (inputState.selectedCharacter) { - actionArgs.selectedCharacter = inputState.selectedCharacter; - } - if (command.operator) { - this.processOperator(cm, vim, command); - } - if (command.motion) { - this.processMotion(cm, vim, command); - } - if (command.motion || command.operator) { - this.evalInput(cm, vim); - } - actionArgs.repeat = repeat || 1; - actionArgs.repeatIsExplicit = repeatIsExplicit; - actionArgs.registerName = inputState.registerName; - clearInputState(cm); - vim.lastMotion = null; - if (command.isEdit) { - this.recordLastEdit(vim, inputState, command); - } - actions[command.action](cm, actionArgs, vim); - }, - processSearch: function(cm, vim, command) { - if (!cm.getSearchCursor) { - return; - } - var forward = command.searchArgs.forward; - var wholeWordOnly = command.searchArgs.wholeWordOnly; - getSearchState(cm).setReversed(!forward); - var promptPrefix = (forward) ? '/' : '?'; - var originalQuery = getSearchState(cm).getQuery(); - var originalScrollPos = cm.getScrollInfo(); - function handleQuery(query, ignoreCase, smartCase) { - vimGlobalState.searchHistoryController.pushInput(query); - vimGlobalState.searchHistoryController.reset(); - try { - updateSearchQuery(cm, query, ignoreCase, smartCase); - } catch (e) { - showConfirm(cm, 'Invalid regex: ' + query); - clearInputState(cm); - return; - } - commandDispatcher.processMotion(cm, vim, { - type: 'motion', - motion: 'findNext', - motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist } - }); - } - function onPromptClose(query) { - cm.scrollTo(originalScrollPos.left, originalScrollPos.top); - handleQuery(query, true /** ignoreCase */, true /** smartCase */); - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isRecording) { - logSearchQuery(macroModeState, query); - } - } - function onPromptKeyUp(e, query, close) { - var keyName = CodeMirror.keyName(e), up; - if (keyName == 'Up' || keyName == 'Down') { - up = keyName == 'Up' ? true : false; - query = vimGlobalState.searchHistoryController.nextMatch(query, up) || ''; - close(query); - } else { - if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') - vimGlobalState.searchHistoryController.reset(); - } - var parsedQuery; - try { - parsedQuery = updateSearchQuery(cm, query, - true /** ignoreCase */, true /** smartCase */); - } catch (e) { - } - if (parsedQuery) { - cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30); - } else { - clearSearchHighlight(cm); - cm.scrollTo(originalScrollPos.left, originalScrollPos.top); - } - } - function onPromptKeyDown(e, query, close) { - var keyName = CodeMirror.keyName(e); - if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || - (keyName == 'Backspace' && query == '')) { - vimGlobalState.searchHistoryController.pushInput(query); - vimGlobalState.searchHistoryController.reset(); - updateSearchQuery(cm, originalQuery); - clearSearchHighlight(cm); - cm.scrollTo(originalScrollPos.left, originalScrollPos.top); - CodeMirror.e_stop(e); - clearInputState(cm); - close(); - cm.focus(); - } else if (keyName == 'Ctrl-U') { - CodeMirror.e_stop(e); - close(''); - } - } - switch (command.searchArgs.querySrc) { - case 'prompt': - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isPlaying) { - var query = macroModeState.replaySearchQueries.shift(); - handleQuery(query, true /** ignoreCase */, false /** smartCase */); - } else { - showPrompt(cm, { - onClose: onPromptClose, - prefix: promptPrefix, - desc: searchPromptDesc, - onKeyUp: onPromptKeyUp, - onKeyDown: onPromptKeyDown - }); - } - break; - case 'wordUnderCursor': - var word = expandWordUnderCursor(cm, false /** inclusive */, - true /** forward */, false /** bigWord */, - true /** noSymbol */); - var isKeyword = true; - if (!word) { - word = expandWordUnderCursor(cm, false /** inclusive */, - true /** forward */, false /** bigWord */, - false /** noSymbol */); - isKeyword = false; - } - if (!word) { - return; - } - var query = cm.getLine(word.start.line).substring(word.start.ch, - word.end.ch); - if (isKeyword && wholeWordOnly) { - query = '\\b' + query + '\\b'; - } else { - query = escapeRegex(query); - } - vimGlobalState.jumpList.cachedCursor = cm.getCursor(); - cm.setCursor(word.start); - - handleQuery(query, true /** ignoreCase */, false /** smartCase */); - break; - } - }, - processEx: function(cm, vim, command) { - function onPromptClose(input) { - vimGlobalState.exCommandHistoryController.pushInput(input); - vimGlobalState.exCommandHistoryController.reset(); - exCommandDispatcher.processCommand(cm, input); - } - function onPromptKeyDown(e, input, close) { - var keyName = CodeMirror.keyName(e), up; - if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || - (keyName == 'Backspace' && input == '')) { - vimGlobalState.exCommandHistoryController.pushInput(input); - vimGlobalState.exCommandHistoryController.reset(); - CodeMirror.e_stop(e); - clearInputState(cm); - close(); - cm.focus(); - } - if (keyName == 'Up' || keyName == 'Down') { - up = keyName == 'Up' ? true : false; - input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || ''; - close(input); - } else if (keyName == 'Ctrl-U') { - CodeMirror.e_stop(e); - close(''); - } else { - if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') - vimGlobalState.exCommandHistoryController.reset(); - } - } - if (command.type == 'keyToEx') { - exCommandDispatcher.processCommand(cm, command.exArgs.input); - } else { - if (vim.visualMode) { - showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>', - onKeyDown: onPromptKeyDown}); - } else { - showPrompt(cm, { onClose: onPromptClose, prefix: ':', - onKeyDown: onPromptKeyDown}); - } - } - }, - evalInput: function(cm, vim) { - var inputState = vim.inputState; - var motion = inputState.motion; - var motionArgs = inputState.motionArgs || {}; - var operator = inputState.operator; - var operatorArgs = inputState.operatorArgs || {}; - var registerName = inputState.registerName; - var sel = vim.sel; - var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head')); - var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor')); - var oldHead = copyCursor(origHead); - var oldAnchor = copyCursor(origAnchor); - var newHead, newAnchor; - var repeat; - if (operator) { - this.recordLastEdit(vim, inputState); - } - if (inputState.repeatOverride !== undefined) { - repeat = inputState.repeatOverride; - } else { - repeat = inputState.getRepeat(); - } - if (repeat > 0 && motionArgs.explicitRepeat) { - motionArgs.repeatIsExplicit = true; - } else if (motionArgs.noRepeat || - (!motionArgs.explicitRepeat && repeat === 0)) { - repeat = 1; - motionArgs.repeatIsExplicit = false; - } - if (inputState.selectedCharacter) { - motionArgs.selectedCharacter = operatorArgs.selectedCharacter = - inputState.selectedCharacter; - } - motionArgs.repeat = repeat; - clearInputState(cm); - if (motion) { - var motionResult = motions[motion](cm, origHead, motionArgs, vim); - vim.lastMotion = motions[motion]; - if (!motionResult) { - return; - } - if (motionArgs.toJumplist) { - if (!operator && cm.ace.curOp != null) - cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch - var jumpList = vimGlobalState.jumpList; - var cachedCursor = jumpList.cachedCursor; - if (cachedCursor) { - recordJumpPosition(cm, cachedCursor, motionResult); - delete jumpList.cachedCursor; - } else { - recordJumpPosition(cm, origHead, motionResult); - } - } - if (motionResult instanceof Array) { - newAnchor = motionResult[0]; - newHead = motionResult[1]; - } else { - newHead = motionResult; - } - if (!newHead) { - newHead = copyCursor(origHead); - } - if (vim.visualMode) { - if (!(vim.visualBlock && newHead.ch === Infinity)) { - newHead = clipCursorToContent(cm, newHead, vim.visualBlock); - } - if (newAnchor) { - newAnchor = clipCursorToContent(cm, newAnchor, true); - } - newAnchor = newAnchor || oldAnchor; - sel.anchor = newAnchor; - sel.head = newHead; - updateCmSelection(cm); - updateMark(cm, vim, '<', - cursorIsBefore(newAnchor, newHead) ? newAnchor - : newHead); - updateMark(cm, vim, '>', - cursorIsBefore(newAnchor, newHead) ? newHead - : newAnchor); - } else if (!operator) { - newHead = clipCursorToContent(cm, newHead); - cm.setCursor(newHead.line, newHead.ch); - } - } - if (operator) { - if (operatorArgs.lastSel) { - newAnchor = oldAnchor; - var lastSel = operatorArgs.lastSel; - var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line); - var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch); - if (lastSel.visualLine) { - newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); - } else if (lastSel.visualBlock) { - newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset); - } else if (lastSel.head.line == lastSel.anchor.line) { - newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset); - } else { - newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); - } - vim.visualMode = true; - vim.visualLine = lastSel.visualLine; - vim.visualBlock = lastSel.visualBlock; - sel = vim.sel = { - anchor: newAnchor, - head: newHead - }; - updateCmSelection(cm); - } else if (vim.visualMode) { - operatorArgs.lastSel = { - anchor: copyCursor(sel.anchor), - head: copyCursor(sel.head), - visualBlock: vim.visualBlock, - visualLine: vim.visualLine - }; - } - var curStart, curEnd, linewise, mode; - var cmSel; - if (vim.visualMode) { - curStart = cursorMin(sel.head, sel.anchor); - curEnd = cursorMax(sel.head, sel.anchor); - linewise = vim.visualLine || operatorArgs.linewise; - mode = vim.visualBlock ? 'block' : - linewise ? 'line' : - 'char'; - cmSel = makeCmSelection(cm, { - anchor: curStart, - head: curEnd - }, mode); - if (linewise) { - var ranges = cmSel.ranges; - if (mode == 'block') { - for (var i = 0; i < ranges.length; i++) { - ranges[i].head.ch = lineLength(cm, ranges[i].head.line); - } - } else if (mode == 'line') { - ranges[0].head = Pos(ranges[0].head.line + 1, 0); - } - } - } else { - curStart = copyCursor(newAnchor || oldAnchor); - curEnd = copyCursor(newHead || oldHead); - if (cursorIsBefore(curEnd, curStart)) { - var tmp = curStart; - curStart = curEnd; - curEnd = tmp; - } - linewise = motionArgs.linewise || operatorArgs.linewise; - if (linewise) { - expandSelectionToLine(cm, curStart, curEnd); - } else if (motionArgs.forward) { - clipToLine(cm, curStart, curEnd); - } - mode = 'char'; - var exclusive = !motionArgs.inclusive || linewise; - cmSel = makeCmSelection(cm, { - anchor: curStart, - head: curEnd - }, mode, exclusive); - } - cm.setSelections(cmSel.ranges, cmSel.primary); - vim.lastMotion = null; - operatorArgs.repeat = repeat; // For indent in visual mode. - operatorArgs.registerName = registerName; - operatorArgs.linewise = linewise; - var operatorMoveTo = operators[operator]( - cm, operatorArgs, cmSel.ranges, oldAnchor, newHead); - if (vim.visualMode) { - exitVisualMode(cm, operatorMoveTo != null); - } - if (operatorMoveTo) { - cm.setCursor(operatorMoveTo); - } - } - }, - recordLastEdit: function(vim, inputState, actionCommand) { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isPlaying) { return; } - vim.lastEditInputState = inputState; - vim.lastEditActionCommand = actionCommand; - macroModeState.lastInsertModeChanges.changes = []; - macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false; - } - }; - var motions = { - moveToTopLine: function(cm, _head, motionArgs) { - var line = getUserVisibleLines(cm).top + motionArgs.repeat -1; - return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); - }, - moveToMiddleLine: function(cm) { - var range = getUserVisibleLines(cm); - var line = Math.floor((range.top + range.bottom) * 0.5); - return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); - }, - moveToBottomLine: function(cm, _head, motionArgs) { - var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1; - return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); - }, - expandToLine: function(_cm, head, motionArgs) { - var cur = head; - return Pos(cur.line + motionArgs.repeat - 1, Infinity); - }, - findNext: function(cm, _head, motionArgs) { - var state = getSearchState(cm); - var query = state.getQuery(); - if (!query) { - return; - } - var prev = !motionArgs.forward; - prev = (state.isReversed()) ? !prev : prev; - highlightSearchMatches(cm, query); - return findNext(cm, prev/** prev */, query, motionArgs.repeat); - }, - goToMark: function(cm, _head, motionArgs, vim) { - var mark = vim.marks[motionArgs.selectedCharacter]; - if (mark) { - var pos = mark.find(); - return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos; - } - return null; - }, - moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) { - if (vim.visualBlock && motionArgs.sameLine) { - var sel = vim.sel; - return [ - clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)), - clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch)) - ]; - } else { - return ([vim.sel.head, vim.sel.anchor]); - } - }, - jumpToMark: function(cm, head, motionArgs, vim) { - var best = head; - for (var i = 0; i < motionArgs.repeat; i++) { - var cursor = best; - for (var key in vim.marks) { - if (!isLowerCase(key)) { - continue; - } - var mark = vim.marks[key].find(); - var isWrongDirection = (motionArgs.forward) ? - cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark); - - if (isWrongDirection) { - continue; - } - if (motionArgs.linewise && (mark.line == cursor.line)) { - continue; - } - - var equal = cursorEqual(cursor, best); - var between = (motionArgs.forward) ? - cursorIsBetween(cursor, mark, best) : - cursorIsBetween(best, mark, cursor); - - if (equal || between) { - best = mark; - } - } - } - - if (motionArgs.linewise) { - best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))); - } - return best; - }, - moveByCharacters: function(_cm, head, motionArgs) { - var cur = head; - var repeat = motionArgs.repeat; - var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; - return Pos(cur.line, ch); - }, - moveByLines: function(cm, head, motionArgs, vim) { - var cur = head; - var endCh = cur.ch; - switch (vim.lastMotion) { - case this.moveByLines: - case this.moveByDisplayLines: - case this.moveByScroll: - case this.moveToColumn: - case this.moveToEol: - endCh = vim.lastHPos; - break; - default: - vim.lastHPos = endCh; - } - var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0); - var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; - var first = cm.firstLine(); - var last = cm.lastLine(); - if ((line < first && cur.line == first) || - (line > last && cur.line == last)) { - return; - } - var fold = cm.ace.session.getFoldLine(line); - if (fold) { - if (motionArgs.forward) { - if (line > fold.start.row) - line = fold.end.row + 1; - } else { - line = fold.start.row; - } - } - if (motionArgs.toFirstChar){ - endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)); - vim.lastHPos = endCh; - } - vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left; - return Pos(line, endCh); - }, - moveByDisplayLines: function(cm, head, motionArgs, vim) { - var cur = head; - switch (vim.lastMotion) { - case this.moveByDisplayLines: - case this.moveByScroll: - case this.moveByLines: - case this.moveToColumn: - case this.moveToEol: - break; - default: - vim.lastHSPos = cm.charCoords(cur,'div').left; - } - var repeat = motionArgs.repeat; - var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos); - if (res.hitSide) { - if (motionArgs.forward) { - var lastCharCoords = cm.charCoords(res, 'div'); - var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos }; - var res = cm.coordsChar(goalCoords, 'div'); - } else { - var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div'); - resCoords.left = vim.lastHSPos; - res = cm.coordsChar(resCoords, 'div'); - } - } - vim.lastHPos = res.ch; - return res; - }, - moveByPage: function(cm, head, motionArgs) { - var curStart = head; - var repeat = motionArgs.repeat; - return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page'); - }, - moveByParagraph: function(cm, head, motionArgs) { - var dir = motionArgs.forward ? 1 : -1; - return findParagraph(cm, head, motionArgs.repeat, dir); - }, - moveByScroll: function(cm, head, motionArgs, vim) { - var scrollbox = cm.getScrollInfo(); - var curEnd = null; - var repeat = motionArgs.repeat; - if (!repeat) { - repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight()); - } - var orig = cm.charCoords(head, 'local'); - motionArgs.repeat = repeat; - var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim); - if (!curEnd) { - return null; - } - var dest = cm.charCoords(curEnd, 'local'); - cm.scrollTo(null, scrollbox.top + dest.top - orig.top); - return curEnd; - }, - moveByWords: function(cm, head, motionArgs) { - return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward, - !!motionArgs.wordEnd, !!motionArgs.bigWord); - }, - moveTillCharacter: function(cm, _head, motionArgs) { - var repeat = motionArgs.repeat; - var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, - motionArgs.selectedCharacter); - var increment = motionArgs.forward ? -1 : 1; - recordLastCharacterSearch(increment, motionArgs); - if (!curEnd) return null; - curEnd.ch += increment; - return curEnd; - }, - moveToCharacter: function(cm, head, motionArgs) { - var repeat = motionArgs.repeat; - recordLastCharacterSearch(0, motionArgs); - return moveToCharacter(cm, repeat, motionArgs.forward, - motionArgs.selectedCharacter) || head; - }, - moveToSymbol: function(cm, head, motionArgs) { - var repeat = motionArgs.repeat; - return findSymbol(cm, repeat, motionArgs.forward, - motionArgs.selectedCharacter) || head; - }, - moveToColumn: function(cm, head, motionArgs, vim) { - var repeat = motionArgs.repeat; - vim.lastHPos = repeat - 1; - vim.lastHSPos = cm.charCoords(head,'div').left; - return moveToColumn(cm, repeat); - }, - moveToEol: function(cm, head, motionArgs, vim) { - var cur = head; - vim.lastHPos = Infinity; - var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity); - var end=cm.clipPos(retval); - end.ch--; - vim.lastHSPos = cm.charCoords(end,'div').left; - return retval; - }, - moveToFirstNonWhiteSpaceCharacter: function(cm, head) { - var cursor = head; - return Pos(cursor.line, - findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line))); - }, - moveToMatchedSymbol: function(cm, head) { - var cursor = head; - var line = cursor.line; - var ch = cursor.ch; - var lineText = cm.getLine(line); - var symbol; - do { - symbol = lineText.charAt(ch++); - if (symbol && isMatchableSymbol(symbol)) { - var style = cm.getTokenTypeAt(Pos(line, ch)); - if (style !== "string" && style !== "comment") { - break; - } - } - } while (symbol); - if (symbol) { - var matched = cm.findMatchingBracket(Pos(line, ch)); - return matched.to; - } else { - return cursor; - } - }, - moveToStartOfLine: function(_cm, head) { - return Pos(head.line, 0); - }, - moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) { - var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine(); - if (motionArgs.repeatIsExplicit) { - lineNum = motionArgs.repeat - cm.getOption('firstLineNumber'); - } - return Pos(lineNum, - findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum))); - }, - textObjectManipulation: function(cm, head, motionArgs, vim) { - var mirroredPairs = {'(': ')', ')': '(', - '{': '}', '}': '{', - '[': ']', ']': '['}; - var selfPaired = {'\'': true, '"': true}; - - var character = motionArgs.selectedCharacter; - if (character == 'b') { - character = '('; - } else if (character == 'B') { - character = '{'; - } - var inclusive = !motionArgs.textObjectInner; - - var tmp; - if (mirroredPairs[character]) { - tmp = selectCompanionObject(cm, head, character, inclusive); - } else if (selfPaired[character]) { - tmp = findBeginningAndEnd(cm, head, character, inclusive); - } else if (character === 'W') { - tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, - true /** bigWord */); - } else if (character === 'w') { - tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, - false /** bigWord */); - } else if (character === 'p') { - tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive); - motionArgs.linewise = true; - if (vim.visualMode) { - if (!vim.visualLine) { vim.visualLine = true; } - } else { - var operatorArgs = vim.inputState.operatorArgs; - if (operatorArgs) { operatorArgs.linewise = true; } - tmp.end.line--; - } - } else { - return null; - } - - if (!cm.state.vim.visualMode) { - return [tmp.start, tmp.end]; - } else { - return expandSelection(cm, tmp.start, tmp.end); - } - }, - - repeatLastCharacterSearch: function(cm, head, motionArgs) { - var lastSearch = vimGlobalState.lastChararacterSearch; - var repeat = motionArgs.repeat; - var forward = motionArgs.forward === lastSearch.forward; - var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1); - cm.moveH(-increment, 'char'); - motionArgs.inclusive = forward ? true : false; - var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter); - if (!curEnd) { - cm.moveH(increment, 'char'); - return head; - } - curEnd.ch += increment; - return curEnd; - } - }; - - function defineMotion(name, fn) { - motions[name] = fn; - } - - function fillArray(val, times) { - var arr = []; - for (var i = 0; i < times; i++) { - arr.push(val); - } - return arr; - } - var operators = { - change: function(cm, args, ranges) { - var finalHead, text; - var vim = cm.state.vim; - vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock; - if (!vim.visualMode) { - var anchor = ranges[0].anchor, - head = ranges[0].head; - text = cm.getRange(anchor, head); - var lastState = vim.lastEditInputState || {}; - if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) { - var match = (/\s+$/).exec(text); - if (match && lastState.motionArgs && lastState.motionArgs.forward) { - head = offsetCursor(head, 0, - match[0].length); - text = text.slice(0, - match[0].length); - } - } - var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE); - var wasLastLine = cm.firstLine() == cm.lastLine(); - if (head.line > cm.lastLine() && args.linewise && !wasLastLine) { - cm.replaceRange('', prevLineEnd, head); - } else { - cm.replaceRange('', anchor, head); - } - if (args.linewise) { - if (!wasLastLine) { - cm.setCursor(prevLineEnd); - CodeMirror.commands.newlineAndIndent(cm); - } - anchor.ch = Number.MAX_VALUE; - } - finalHead = anchor; - } else { - text = cm.getSelection(); - var replacement = fillArray('', ranges.length); - cm.replaceSelections(replacement); - finalHead = cursorMin(ranges[0].head, ranges[0].anchor); - } - vimGlobalState.registerController.pushText( - args.registerName, 'change', text, - args.linewise, ranges.length > 1); - actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim); - }, - 'delete': function(cm, args, ranges) { - var finalHead, text; - var vim = cm.state.vim; - if (!vim.visualBlock) { - var anchor = ranges[0].anchor, - head = ranges[0].head; - if (args.linewise && - head.line != cm.firstLine() && - anchor.line == cm.lastLine() && - anchor.line == head.line - 1) { - if (anchor.line == cm.firstLine()) { - anchor.ch = 0; - } else { - anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1)); - } - } - text = cm.getRange(anchor, head); - cm.replaceRange('', anchor, head); - finalHead = anchor; - if (args.linewise) { - finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor); - } - } else { - text = cm.getSelection(); - var replacement = fillArray('', ranges.length); - cm.replaceSelections(replacement); - finalHead = ranges[0].anchor; - } - vimGlobalState.registerController.pushText( - args.registerName, 'delete', text, - args.linewise, vim.visualBlock); - return clipCursorToContent(cm, finalHead); - }, - indent: function(cm, args, ranges) { - var vim = cm.state.vim; - var startLine = ranges[0].anchor.line; - var endLine = vim.visualBlock ? - ranges[ranges.length - 1].anchor.line : - ranges[0].head.line; - var repeat = (vim.visualMode) ? args.repeat : 1; - if (args.linewise) { - endLine--; - } - for (var i = startLine; i <= endLine; i++) { - for (var j = 0; j < repeat; j++) { - cm.indentLine(i, args.indentRight); - } - } - return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor); - }, - changeCase: function(cm, args, ranges, oldAnchor, newHead) { - var selections = cm.getSelections(); - var swapped = []; - var toLower = args.toLower; - for (var j = 0; j < selections.length; j++) { - var toSwap = selections[j]; - var text = ''; - if (toLower === true) { - text = toSwap.toLowerCase(); - } else if (toLower === false) { - text = toSwap.toUpperCase(); - } else { - for (var i = 0; i < toSwap.length; i++) { - var character = toSwap.charAt(i); - text += isUpperCase(character) ? character.toLowerCase() : - character.toUpperCase(); - } - } - swapped.push(text); - } - cm.replaceSelections(swapped); - if (args.shouldMoveCursor){ - return newHead; - } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) { - return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor); - } else if (args.linewise){ - return oldAnchor; - } else { - return cursorMin(ranges[0].anchor, ranges[0].head); - } - }, - yank: function(cm, args, ranges, oldAnchor) { - var vim = cm.state.vim; - var text = cm.getSelection(); - var endPos = vim.visualMode - ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor) - : oldAnchor; - vimGlobalState.registerController.pushText( - args.registerName, 'yank', - text, args.linewise, vim.visualBlock); - return endPos; - } - }; - - function defineOperator(name, fn) { - operators[name] = fn; - } - - var actions = { - jumpListWalk: function(cm, actionArgs, vim) { - if (vim.visualMode) { - return; - } - var repeat = actionArgs.repeat; - var forward = actionArgs.forward; - var jumpList = vimGlobalState.jumpList; - - var mark = jumpList.move(cm, forward ? repeat : -repeat); - var markPos = mark ? mark.find() : undefined; - markPos = markPos ? markPos : cm.getCursor(); - cm.setCursor(markPos); - cm.ace.curOp.command.scrollIntoView = "center-animate"; // ace_patch - }, - scroll: function(cm, actionArgs, vim) { - if (vim.visualMode) { - return; - } - var repeat = actionArgs.repeat || 1; - var lineHeight = cm.defaultTextHeight(); - var top = cm.getScrollInfo().top; - var delta = lineHeight * repeat; - var newPos = actionArgs.forward ? top + delta : top - delta; - var cursor = copyCursor(cm.getCursor()); - var cursorCoords = cm.charCoords(cursor, 'local'); - if (actionArgs.forward) { - if (newPos > cursorCoords.top) { - cursor.line += (newPos - cursorCoords.top) / lineHeight; - cursor.line = Math.ceil(cursor.line); - cm.setCursor(cursor); - cursorCoords = cm.charCoords(cursor, 'local'); - cm.scrollTo(null, cursorCoords.top); - } else { - cm.scrollTo(null, newPos); - } - } else { - var newBottom = newPos + cm.getScrollInfo().clientHeight; - if (newBottom < cursorCoords.bottom) { - cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight; - cursor.line = Math.floor(cursor.line); - cm.setCursor(cursor); - cursorCoords = cm.charCoords(cursor, 'local'); - cm.scrollTo( - null, cursorCoords.bottom - cm.getScrollInfo().clientHeight); - } else { - cm.scrollTo(null, newPos); - } - } - }, - scrollToCursor: function(cm, actionArgs) { - var lineNum = cm.getCursor().line; - var charCoords = cm.charCoords(Pos(lineNum, 0), 'local'); - var height = cm.getScrollInfo().clientHeight; - var y = charCoords.top; - var lineHeight = charCoords.bottom - y; - switch (actionArgs.position) { - case 'center': y = y - (height / 2) + lineHeight; - break; - case 'bottom': y = y - height + lineHeight*1.4; - break; - case 'top': y = y + lineHeight*0.4; - break; - } - cm.scrollTo(null, y); - }, - replayMacro: function(cm, actionArgs, vim) { - var registerName = actionArgs.selectedCharacter; - var repeat = actionArgs.repeat; - var macroModeState = vimGlobalState.macroModeState; - if (registerName == '@') { - registerName = macroModeState.latestRegister; - } - while(repeat--){ - executeMacroRegister(cm, vim, macroModeState, registerName); - } - }, - enterMacroRecordMode: function(cm, actionArgs) { - var macroModeState = vimGlobalState.macroModeState; - var registerName = actionArgs.selectedCharacter; - macroModeState.enterMacroRecordMode(cm, registerName); - }, - enterInsertMode: function(cm, actionArgs, vim) { - if (cm.getOption('readOnly')) { return; } - vim.insertMode = true; - vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1; - var insertAt = (actionArgs) ? actionArgs.insertAt : null; - var sel = vim.sel; - var head = actionArgs.head || cm.getCursor('head'); - var height = cm.listSelections().length; - if (insertAt == 'eol') { - head = Pos(head.line, lineLength(cm, head.line)); - } else if (insertAt == 'charAfter') { - head = offsetCursor(head, 0, 1); - } else if (insertAt == 'firstNonBlank') { - head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head); - } else if (insertAt == 'startOfSelectedArea') { - if (!vim.visualBlock) { - if (sel.head.line < sel.anchor.line) { - head = sel.head; - } else { - head = Pos(sel.anchor.line, 0); - } - } else { - head = Pos( - Math.min(sel.head.line, sel.anchor.line), - Math.min(sel.head.ch, sel.anchor.ch)); - height = Math.abs(sel.head.line - sel.anchor.line) + 1; - } - } else if (insertAt == 'endOfSelectedArea') { - if (!vim.visualBlock) { - if (sel.head.line >= sel.anchor.line) { - head = offsetCursor(sel.head, 0, 1); - } else { - head = Pos(sel.anchor.line, 0); - } - } else { - head = Pos( - Math.min(sel.head.line, sel.anchor.line), - Math.max(sel.head.ch + 1, sel.anchor.ch)); - height = Math.abs(sel.head.line - sel.anchor.line) + 1; - } - } else if (insertAt == 'inplace') { - if (vim.visualMode){ - return; - } - } - cm.setOption('keyMap', 'vim-insert'); - cm.setOption('disableInput', false); - if (actionArgs && actionArgs.replace) { - cm.toggleOverwrite(true); - cm.setOption('keyMap', 'vim-replace'); - CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); - } else { - cm.setOption('keyMap', 'vim-insert'); - CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); - } - if (!vimGlobalState.macroModeState.isPlaying) { - cm.on('change', onChange); - CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); - } - if (vim.visualMode) { - exitVisualMode(cm); - } - selectForInsert(cm, head, height); - }, - toggleVisualMode: function(cm, actionArgs, vim) { - var repeat = actionArgs.repeat; - var anchor = cm.getCursor(); - var head; - if (!vim.visualMode) { - vim.visualMode = true; - vim.visualLine = !!actionArgs.linewise; - vim.visualBlock = !!actionArgs.blockwise; - head = clipCursorToContent( - cm, Pos(anchor.line, anchor.ch + repeat - 1), - true /** includeLineBreak */); - vim.sel = { - anchor: anchor, - head: head - }; - CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); - updateCmSelection(cm); - updateMark(cm, vim, '<', cursorMin(anchor, head)); - updateMark(cm, vim, '>', cursorMax(anchor, head)); - } else if (vim.visualLine ^ actionArgs.linewise || - vim.visualBlock ^ actionArgs.blockwise) { - vim.visualLine = !!actionArgs.linewise; - vim.visualBlock = !!actionArgs.blockwise; - CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); - updateCmSelection(cm); - } else { - exitVisualMode(cm); - } - }, - reselectLastSelection: function(cm, _actionArgs, vim) { - var lastSelection = vim.lastSelection; - if (vim.visualMode) { - updateLastSelection(cm, vim); - } - if (lastSelection) { - var anchor = lastSelection.anchorMark.find(); - var head = lastSelection.headMark.find(); - if (!anchor || !head) { - return; - } - vim.sel = { - anchor: anchor, - head: head - }; - vim.visualMode = true; - vim.visualLine = lastSelection.visualLine; - vim.visualBlock = lastSelection.visualBlock; - updateCmSelection(cm); - updateMark(cm, vim, '<', cursorMin(anchor, head)); - updateMark(cm, vim, '>', cursorMax(anchor, head)); - CodeMirror.signal(cm, 'vim-mode-change', { - mode: 'visual', - subMode: vim.visualLine ? 'linewise' : - vim.visualBlock ? 'blockwise' : ''}); - } - }, - joinLines: function(cm, actionArgs, vim) { - var curStart, curEnd; - if (vim.visualMode) { - curStart = cm.getCursor('anchor'); - curEnd = cm.getCursor('head'); - if (cursorIsBefore(curEnd, curStart)) { - var tmp = curEnd; - curEnd = curStart; - curStart = tmp; - } - curEnd.ch = lineLength(cm, curEnd.line) - 1; - } else { - var repeat = Math.max(actionArgs.repeat, 2); - curStart = cm.getCursor(); - curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1, - Infinity)); - } - var finalCh = 0; - for (var i = curStart.line; i < curEnd.line; i++) { - finalCh = lineLength(cm, curStart.line); - var tmp = Pos(curStart.line + 1, - lineLength(cm, curStart.line + 1)); - var text = cm.getRange(curStart, tmp); - text = text.replace(/\n\s*/g, ' '); - cm.replaceRange(text, curStart, tmp); - } - var curFinalPos = Pos(curStart.line, finalCh); - if (vim.visualMode) { - exitVisualMode(cm, false); - } - cm.setCursor(curFinalPos); - }, - newLineAndEnterInsertMode: function(cm, actionArgs, vim) { - vim.insertMode = true; - var insertAt = copyCursor(cm.getCursor()); - if (insertAt.line === cm.firstLine() && !actionArgs.after) { - cm.replaceRange('\n', Pos(cm.firstLine(), 0)); - cm.setCursor(cm.firstLine(), 0); - } else { - insertAt.line = (actionArgs.after) ? insertAt.line : - insertAt.line - 1; - insertAt.ch = lineLength(cm, insertAt.line); - cm.setCursor(insertAt); - var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment || - CodeMirror.commands.newlineAndIndent; - newlineFn(cm); - } - this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim); - }, - paste: function(cm, actionArgs, vim) { - var cur = copyCursor(cm.getCursor()); - var register = vimGlobalState.registerController.getRegister( - actionArgs.registerName); - var text = register.toString(); - if (!text) { - return; - } - if (actionArgs.matchIndent) { - var tabSize = cm.getOption("tabSize"); - var whitespaceLength = function(str) { - var tabs = (str.split("\t").length - 1); - var spaces = (str.split(" ").length - 1); - return tabs * tabSize + spaces * 1; - }; - var currentLine = cm.getLine(cm.getCursor().line); - var indent = whitespaceLength(currentLine.match(/^\s*/)[0]); - var chompedText = text.replace(/\n$/, ''); - var wasChomped = text !== chompedText; - var firstIndent = whitespaceLength(text.match(/^\s*/)[0]); - var text = chompedText.replace(/^\s*/gm, function(wspace) { - var newIndent = indent + (whitespaceLength(wspace) - firstIndent); - if (newIndent < 0) { - return ""; - } - else if (cm.getOption("indentWithTabs")) { - var quotient = Math.floor(newIndent / tabSize); - return Array(quotient + 1).join('\t'); - } - else { - return Array(newIndent + 1).join(' '); - } - }); - text += wasChomped ? "\n" : ""; - } - if (actionArgs.repeat > 1) { - var text = Array(actionArgs.repeat + 1).join(text); - } - var linewise = register.linewise; - var blockwise = register.blockwise; - if (linewise && !blockwise) { - if(vim.visualMode) { - text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n'; - } else if (actionArgs.after) { - text = '\n' + text.slice(0, text.length - 1); - cur.ch = lineLength(cm, cur.line); - } else { - cur.ch = 0; - } - } else { - if (blockwise) { - text = text.split('\n'); - for (var i = 0; i < text.length; i++) { - text[i] = (text[i] == '') ? ' ' : text[i]; - } - } - cur.ch += actionArgs.after ? 1 : 0; - } - var curPosFinal; - var idx; - if (vim.visualMode) { - vim.lastPastedText = text; - var lastSelectionCurEnd; - var selectedArea = getSelectedAreaRange(cm, vim); - var selectionStart = selectedArea[0]; - var selectionEnd = selectedArea[1]; - var selectedText = cm.getSelection(); - var selections = cm.listSelections(); - var emptyStrings = new Array(selections.length).join('1').split('1'); - if (vim.lastSelection) { - lastSelectionCurEnd = vim.lastSelection.headMark.find(); - } - vimGlobalState.registerController.unnamedRegister.setText(selectedText); - if (blockwise) { - cm.replaceSelections(emptyStrings); - selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch); - cm.setCursor(selectionStart); - selectBlock(cm, selectionEnd); - cm.replaceSelections(text); - curPosFinal = selectionStart; - } else if (vim.visualBlock) { - cm.replaceSelections(emptyStrings); - cm.setCursor(selectionStart); - cm.replaceRange(text, selectionStart, selectionStart); - curPosFinal = selectionStart; - } else { - cm.replaceRange(text, selectionStart, selectionEnd); - curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1); - } - if(lastSelectionCurEnd) { - vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd); - } - if (linewise) { - curPosFinal.ch=0; - } - } else { - if (blockwise) { - cm.setCursor(cur); - for (var i = 0; i < text.length; i++) { - var line = cur.line+i; - if (line > cm.lastLine()) { - cm.replaceRange('\n', Pos(line, 0)); - } - var lastCh = lineLength(cm, line); - if (lastCh < cur.ch) { - extendLineToColumn(cm, line, cur.ch); - } - } - cm.setCursor(cur); - selectBlock(cm, Pos(cur.line + text.length-1, cur.ch)); - cm.replaceSelections(text); - curPosFinal = cur; - } else { - cm.replaceRange(text, cur); - if (linewise && actionArgs.after) { - curPosFinal = Pos( - cur.line + 1, - findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1))); - } else if (linewise && !actionArgs.after) { - curPosFinal = Pos( - cur.line, - findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line))); - } else if (!linewise && actionArgs.after) { - idx = cm.indexFromPos(cur); - curPosFinal = cm.posFromIndex(idx + text.length - 1); - } else { - idx = cm.indexFromPos(cur); - curPosFinal = cm.posFromIndex(idx + text.length); - } - } - } - if (vim.visualMode) { - exitVisualMode(cm, false); - } - cm.setCursor(curPosFinal); - }, - undo: function(cm, actionArgs) { - cm.operation(function() { - repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); - cm.setCursor(cm.getCursor('anchor')); - }); - }, - redo: function(cm, actionArgs) { - repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); - }, - setRegister: function(_cm, actionArgs, vim) { - vim.inputState.registerName = actionArgs.selectedCharacter; - }, - setMark: function(cm, actionArgs, vim) { - var markName = actionArgs.selectedCharacter; - updateMark(cm, vim, markName, cm.getCursor()); - }, - replace: function(cm, actionArgs, vim) { - var replaceWith = actionArgs.selectedCharacter; - var curStart = cm.getCursor(); - var replaceTo; - var curEnd; - var selections = cm.listSelections(); - if (vim.visualMode) { - curStart = cm.getCursor('start'); - curEnd = cm.getCursor('end'); - } else { - var line = cm.getLine(curStart.line); - replaceTo = curStart.ch + actionArgs.repeat; - if (replaceTo > line.length) { - replaceTo=line.length; - } - curEnd = Pos(curStart.line, replaceTo); - } - if (replaceWith=='\n') { - if (!vim.visualMode) cm.replaceRange('', curStart, curEnd); - (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm); - } else { - var replaceWithStr = cm.getRange(curStart, curEnd); - replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith); - if (vim.visualBlock) { - var spaces = new Array(cm.getOption("tabSize")+1).join(' '); - replaceWithStr = cm.getSelection(); - replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n'); - cm.replaceSelections(replaceWithStr); - } else { - cm.replaceRange(replaceWithStr, curStart, curEnd); - } - if (vim.visualMode) { - curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ? - selections[0].anchor : selections[0].head; - cm.setCursor(curStart); - exitVisualMode(cm, false); - } else { - cm.setCursor(offsetCursor(curEnd, 0, -1)); - } - } - }, - incrementNumberToken: function(cm, actionArgs) { - var cur = cm.getCursor(); - var lineStr = cm.getLine(cur.line); - var re = /-?\d+/g; - var match; - var start; - var end; - var numberStr; - var token; - while ((match = re.exec(lineStr)) !== null) { - token = match[0]; - start = match.index; - end = start + token.length; - if (cur.ch < end)break; - } - if (!actionArgs.backtrack && (end <= cur.ch))return; - if (token) { - var increment = actionArgs.increase ? 1 : -1; - var number = parseInt(token) + (increment * actionArgs.repeat); - var from = Pos(cur.line, start); - var to = Pos(cur.line, end); - numberStr = number.toString(); - cm.replaceRange(numberStr, from, to); - } else { - return; - } - cm.setCursor(Pos(cur.line, start + numberStr.length - 1)); - }, - repeatLastEdit: function(cm, actionArgs, vim) { - var lastEditInputState = vim.lastEditInputState; - if (!lastEditInputState) { return; } - var repeat = actionArgs.repeat; - if (repeat && actionArgs.repeatIsExplicit) { - vim.lastEditInputState.repeatOverride = repeat; - } else { - repeat = vim.lastEditInputState.repeatOverride || repeat; - } - repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */); - }, - exitInsertMode: exitInsertMode - }; - - function defineAction(name, fn) { - actions[name] = fn; - } - function clipCursorToContent(cm, cur, includeLineBreak) { - var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() ); - var maxCh = lineLength(cm, line) - 1; - maxCh = (includeLineBreak) ? maxCh + 1 : maxCh; - var ch = Math.min(Math.max(0, cur.ch), maxCh); - return Pos(line, ch); - } - function copyArgs(args) { - var ret = {}; - for (var prop in args) { - if (args.hasOwnProperty(prop)) { - ret[prop] = args[prop]; - } - } - return ret; - } - function offsetCursor(cur, offsetLine, offsetCh) { - if (typeof offsetLine === 'object') { - offsetCh = offsetLine.ch; - offsetLine = offsetLine.line; - } - return Pos(cur.line + offsetLine, cur.ch + offsetCh); - } - function getOffset(anchor, head) { - return { - line: head.line - anchor.line, - ch: head.line - anchor.line - }; - } - function commandMatches(keys, keyMap, context, inputState) { - var match, partial = [], full = []; - for (var i = 0; i < keyMap.length; i++) { - var command = keyMap[i]; - if (context == 'insert' && command.context != 'insert' || - command.context && command.context != context || - inputState.operator && command.type == 'action' || - !(match = commandMatch(keys, command.keys))) { continue; } - if (match == 'partial') { partial.push(command); } - if (match == 'full') { full.push(command); } - } - return { - partial: partial.length && partial, - full: full.length && full - }; - } - function commandMatch(pressed, mapped) { - if (mapped.slice(-11) == '') { - var prefixLen = mapped.length - 11; - var pressedPrefix = pressed.slice(0, prefixLen); - var mappedPrefix = mapped.slice(0, prefixLen); - return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' : - mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false; - } else { - return pressed == mapped ? 'full' : - mapped.indexOf(pressed) == 0 ? 'partial' : false; - } - } - function lastChar(keys) { - var match = /^.*(<[\w\-]+>)$/.exec(keys); - var selectedCharacter = match ? match[1] : keys.slice(-1); - if (selectedCharacter.length > 1){ - switch(selectedCharacter){ - case '': - selectedCharacter='\n'; - break; - case '': - selectedCharacter=' '; - break; - default: - break; - } - } - return selectedCharacter; - } - function repeatFn(cm, fn, repeat) { - return function() { - for (var i = 0; i < repeat; i++) { - fn(cm); - } - }; - } - function copyCursor(cur) { - return Pos(cur.line, cur.ch); - } - function cursorEqual(cur1, cur2) { - return cur1.ch == cur2.ch && cur1.line == cur2.line; - } - function cursorIsBefore(cur1, cur2) { - if (cur1.line < cur2.line) { - return true; - } - if (cur1.line == cur2.line && cur1.ch < cur2.ch) { - return true; - } - return false; - } - function cursorMin(cur1, cur2) { - if (arguments.length > 2) { - cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1)); - } - return cursorIsBefore(cur1, cur2) ? cur1 : cur2; - } - function cursorMax(cur1, cur2) { - if (arguments.length > 2) { - cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1)); - } - return cursorIsBefore(cur1, cur2) ? cur2 : cur1; - } - function cursorIsBetween(cur1, cur2, cur3) { - var cur1before2 = cursorIsBefore(cur1, cur2); - var cur2before3 = cursorIsBefore(cur2, cur3); - return cur1before2 && cur2before3; - } - function lineLength(cm, lineNum) { - return cm.getLine(lineNum).length; - } - function trim(s) { - if (s.trim) { - return s.trim(); - } - return s.replace(/^\s+|\s+$/g, ''); - } - function escapeRegex(s) { - return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1'); - } - function extendLineToColumn(cm, lineNum, column) { - var endCh = lineLength(cm, lineNum); - var spaces = new Array(column-endCh+1).join(' '); - cm.setCursor(Pos(lineNum, endCh)); - cm.replaceRange(spaces, cm.getCursor()); - } - function selectBlock(cm, selectionEnd) { - var selections = [], ranges = cm.listSelections(); - var head = copyCursor(cm.clipPos(selectionEnd)); - var isClipped = !cursorEqual(selectionEnd, head); - var curHead = cm.getCursor('head'); - var primIndex = getIndex(ranges, curHead); - var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor); - var max = ranges.length - 1; - var index = max - primIndex > primIndex ? max : 0; - var base = ranges[index].anchor; - - var firstLine = Math.min(base.line, head.line); - var lastLine = Math.max(base.line, head.line); - var baseCh = base.ch, headCh = head.ch; - - var dir = ranges[index].head.ch - baseCh; - var newDir = headCh - baseCh; - if (dir > 0 && newDir <= 0) { - baseCh++; - if (!isClipped) { headCh--; } - } else if (dir < 0 && newDir >= 0) { - baseCh--; - if (!wasClipped) { headCh++; } - } else if (dir < 0 && newDir == -1) { - baseCh--; - headCh++; - } - for (var line = firstLine; line <= lastLine; line++) { - var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)}; - selections.push(range); - } - primIndex = head.line == lastLine ? selections.length - 1 : 0; - cm.setSelections(selections); - selectionEnd.ch = headCh; - base.ch = baseCh; - return base; - } - function selectForInsert(cm, head, height) { - var sel = []; - for (var i = 0; i < height; i++) { - var lineHead = offsetCursor(head, i, 0); - sel.push({anchor: lineHead, head: lineHead}); - } - cm.setSelections(sel, 0); - } - function getIndex(ranges, cursor, end) { - for (var i = 0; i < ranges.length; i++) { - var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor); - var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor); - if (atAnchor || atHead) { - return i; - } - } - return -1; - } - function getSelectedAreaRange(cm, vim) { - var lastSelection = vim.lastSelection; - var getCurrentSelectedAreaRange = function() { - var selections = cm.listSelections(); - var start = selections[0]; - var end = selections[selections.length-1]; - var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head; - var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor; - return [selectionStart, selectionEnd]; - }; - var getLastSelectedAreaRange = function() { - var selectionStart = cm.getCursor(); - var selectionEnd = cm.getCursor(); - var block = lastSelection.visualBlock; - if (block) { - var width = block.width; - var height = block.height; - selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width); - var selections = []; - for (var i = selectionStart.line; i < selectionEnd.line; i++) { - var anchor = Pos(i, selectionStart.ch); - var head = Pos(i, selectionEnd.ch); - var range = {anchor: anchor, head: head}; - selections.push(range); - } - cm.setSelections(selections); - } else { - var start = lastSelection.anchorMark.find(); - var end = lastSelection.headMark.find(); - var line = end.line - start.line; - var ch = end.ch - start.ch; - selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch}; - if (lastSelection.visualLine) { - selectionStart = Pos(selectionStart.line, 0); - selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line)); - } - cm.setSelection(selectionStart, selectionEnd); - } - return [selectionStart, selectionEnd]; - }; - if (!vim.visualMode) { - return getLastSelectedAreaRange(); - } else { - return getCurrentSelectedAreaRange(); - } - } - function updateLastSelection(cm, vim) { - var anchor = vim.sel.anchor; - var head = vim.sel.head; - if (vim.lastPastedText) { - head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length); - vim.lastPastedText = null; - } - vim.lastSelection = {'anchorMark': cm.setBookmark(anchor), - 'headMark': cm.setBookmark(head), - 'anchor': copyCursor(anchor), - 'head': copyCursor(head), - 'visualMode': vim.visualMode, - 'visualLine': vim.visualLine, - 'visualBlock': vim.visualBlock}; - } - function expandSelection(cm, start, end) { - var sel = cm.state.vim.sel; - var head = sel.head; - var anchor = sel.anchor; - var tmp; - if (cursorIsBefore(end, start)) { - tmp = end; - end = start; - start = tmp; - } - if (cursorIsBefore(head, anchor)) { - head = cursorMin(start, head); - anchor = cursorMax(anchor, end); - } else { - anchor = cursorMin(start, anchor); - head = cursorMax(head, end); - head = offsetCursor(head, 0, -1); - if (head.ch == -1 && head.line != cm.firstLine()) { - head = Pos(head.line - 1, lineLength(cm, head.line - 1)); - } - } - return [anchor, head]; - } - function updateCmSelection(cm, sel, mode) { - var vim = cm.state.vim; - sel = sel || vim.sel; - var mode = mode || - vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char'; - var cmSel = makeCmSelection(cm, sel, mode); - cm.setSelections(cmSel.ranges, cmSel.primary); - updateFakeCursor(cm); - } - function makeCmSelection(cm, sel, mode, exclusive) { - var head = copyCursor(sel.head); - var anchor = copyCursor(sel.anchor); - if (mode == 'char') { - var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; - var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; - head = offsetCursor(sel.head, 0, headOffset); - anchor = offsetCursor(sel.anchor, 0, anchorOffset); - return { - ranges: [{anchor: anchor, head: head}], - primary: 0 - }; - } else if (mode == 'line') { - if (!cursorIsBefore(sel.head, sel.anchor)) { - anchor.ch = 0; - - var lastLine = cm.lastLine(); - if (head.line > lastLine) { - head.line = lastLine; - } - head.ch = lineLength(cm, head.line); - } else { - head.ch = 0; - anchor.ch = lineLength(cm, anchor.line); - } - return { - ranges: [{anchor: anchor, head: head}], - primary: 0 - }; - } else if (mode == 'block') { - var top = Math.min(anchor.line, head.line), - left = Math.min(anchor.ch, head.ch), - bottom = Math.max(anchor.line, head.line), - right = Math.max(anchor.ch, head.ch) + 1; - var height = bottom - top + 1; - var primary = head.line == top ? 0 : height - 1; - var ranges = []; - for (var i = 0; i < height; i++) { - ranges.push({ - anchor: Pos(top + i, left), - head: Pos(top + i, right) - }); - } - return { - ranges: ranges, - primary: primary - }; - } - } - function getHead(cm) { - var cur = cm.getCursor('head'); - if (cm.getSelection().length == 1) { - cur = cursorMin(cur, cm.getCursor('anchor')); - } - return cur; - } - function exitVisualMode(cm, moveHead) { - var vim = cm.state.vim; - if (moveHead !== false) { - cm.setCursor(clipCursorToContent(cm, vim.sel.head)); - } - updateLastSelection(cm, vim); - vim.visualMode = false; - vim.visualLine = false; - vim.visualBlock = false; - CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); - if (vim.fakeCursor) { - vim.fakeCursor.clear(); - } - } - function clipToLine(cm, curStart, curEnd) { - var selection = cm.getRange(curStart, curEnd); - if (/\n\s*$/.test(selection)) { - var lines = selection.split('\n'); - lines.pop(); - var line; - for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) { - curEnd.line--; - curEnd.ch = 0; - } - if (line) { - curEnd.line--; - curEnd.ch = lineLength(cm, curEnd.line); - } else { - curEnd.ch = 0; - } - } - } - function expandSelectionToLine(_cm, curStart, curEnd) { - curStart.ch = 0; - curEnd.ch = 0; - curEnd.line++; - } - - function findFirstNonWhiteSpaceCharacter(text) { - if (!text) { - return 0; - } - var firstNonWS = text.search(/\S/); - return firstNonWS == -1 ? text.length : firstNonWS; - } - - function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) { - var cur = getHead(cm); - var line = cm.getLine(cur.line); - var idx = cur.ch; - var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0]; - while (!test(line.charAt(idx))) { - idx++; - if (idx >= line.length) { return null; } - } - - if (bigWord) { - test = bigWordCharTest[0]; - } else { - test = wordCharTest[0]; - if (!test(line.charAt(idx))) { - test = wordCharTest[1]; - } - } - - var end = idx, start = idx; - while (test(line.charAt(end)) && end < line.length) { end++; } - while (test(line.charAt(start)) && start >= 0) { start--; } - start++; - - if (inclusive) { - var wordEnd = end; - while (/\s/.test(line.charAt(end)) && end < line.length) { end++; } - if (wordEnd == end) { - var wordStart = start; - while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; } - if (!start) { start = wordStart; } - } - } - return { start: Pos(cur.line, start), end: Pos(cur.line, end) }; - } - - function recordJumpPosition(cm, oldCur, newCur) { - if (!cursorEqual(oldCur, newCur)) { - vimGlobalState.jumpList.add(cm, oldCur, newCur); - } - } - - function recordLastCharacterSearch(increment, args) { - vimGlobalState.lastChararacterSearch.increment = increment; - vimGlobalState.lastChararacterSearch.forward = args.forward; - vimGlobalState.lastChararacterSearch.selectedCharacter = args.selectedCharacter; - } - - var symbolToMode = { - '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket', - '[': 'section', ']': 'section', - '*': 'comment', '/': 'comment', - 'm': 'method', 'M': 'method', - '#': 'preprocess' - }; - var findSymbolModes = { - bracket: { - isComplete: function(state) { - if (state.nextCh === state.symb) { - state.depth++; - if (state.depth >= 1)return true; - } else if (state.nextCh === state.reverseSymb) { - state.depth--; - } - return false; - } - }, - section: { - init: function(state) { - state.curMoveThrough = true; - state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}'; - }, - isComplete: function(state) { - return state.index === 0 && state.nextCh === state.symb; - } - }, - comment: { - isComplete: function(state) { - var found = state.lastCh === '*' && state.nextCh === '/'; - state.lastCh = state.nextCh; - return found; - } - }, - method: { - init: function(state) { - state.symb = (state.symb === 'm' ? '{' : '}'); - state.reverseSymb = state.symb === '{' ? '}' : '{'; - }, - isComplete: function(state) { - if (state.nextCh === state.symb)return true; - return false; - } - }, - preprocess: { - init: function(state) { - state.index = 0; - }, - isComplete: function(state) { - if (state.nextCh === '#') { - var token = state.lineText.match(/#(\w+)/)[1]; - if (token === 'endif') { - if (state.forward && state.depth === 0) { - return true; - } - state.depth++; - } else if (token === 'if') { - if (!state.forward && state.depth === 0) { - return true; - } - state.depth--; - } - if (token === 'else' && state.depth === 0)return true; - } - return false; - } - } - }; - function findSymbol(cm, repeat, forward, symb) { - var cur = copyCursor(cm.getCursor()); - var increment = forward ? 1 : -1; - var endLine = forward ? cm.lineCount() : -1; - var curCh = cur.ch; - var line = cur.line; - var lineText = cm.getLine(line); - var state = { - lineText: lineText, - nextCh: lineText.charAt(curCh), - lastCh: null, - index: curCh, - symb: symb, - reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb], - forward: forward, - depth: 0, - curMoveThrough: false - }; - var mode = symbolToMode[symb]; - if (!mode)return cur; - var init = findSymbolModes[mode].init; - var isComplete = findSymbolModes[mode].isComplete; - if (init) { init(state); } - while (line !== endLine && repeat) { - state.index += increment; - state.nextCh = state.lineText.charAt(state.index); - if (!state.nextCh) { - line += increment; - state.lineText = cm.getLine(line) || ''; - if (increment > 0) { - state.index = 0; - } else { - var lineLen = state.lineText.length; - state.index = (lineLen > 0) ? (lineLen-1) : 0; - } - state.nextCh = state.lineText.charAt(state.index); - } - if (isComplete(state)) { - cur.line = line; - cur.ch = state.index; - repeat--; - } - } - if (state.nextCh || state.curMoveThrough) { - return Pos(line, state.index); - } - return cur; - } - function findWord(cm, cur, forward, bigWord, emptyLineIsWord) { - var lineNum = cur.line; - var pos = cur.ch; - var line = cm.getLine(lineNum); - var dir = forward ? 1 : -1; - var charTests = bigWord ? bigWordCharTest: wordCharTest; - - if (emptyLineIsWord && line == '') { - lineNum += dir; - line = cm.getLine(lineNum); - if (!isLine(cm, lineNum)) { - return null; - } - pos = (forward) ? 0 : line.length; - } - - while (true) { - if (emptyLineIsWord && line == '') { - return { from: 0, to: 0, line: lineNum }; - } - var stop = (dir > 0) ? line.length : -1; - var wordStart = stop, wordEnd = stop; - while (pos != stop) { - var foundWord = false; - for (var i = 0; i < charTests.length && !foundWord; ++i) { - if (charTests[i](line.charAt(pos))) { - wordStart = pos; - while (pos != stop && charTests[i](line.charAt(pos))) { - pos += dir; - } - wordEnd = pos; - foundWord = wordStart != wordEnd; - if (wordStart == cur.ch && lineNum == cur.line && - wordEnd == wordStart + dir) { - continue; - } else { - return { - from: Math.min(wordStart, wordEnd + 1), - to: Math.max(wordStart, wordEnd), - line: lineNum }; - } - } - } - if (!foundWord) { - pos += dir; - } - } - lineNum += dir; - if (!isLine(cm, lineNum)) { - return null; - } - line = cm.getLine(lineNum); - pos = (dir > 0) ? 0 : line.length; - } - throw new Error('The impossible happened.'); - } - function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) { - var curStart = copyCursor(cur); - var words = []; - if (forward && !wordEnd || !forward && wordEnd) { - repeat++; - } - var emptyLineIsWord = !(forward && wordEnd); - for (var i = 0; i < repeat; i++) { - var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord); - if (!word) { - var eodCh = lineLength(cm, cm.lastLine()); - words.push(forward - ? {line: cm.lastLine(), from: eodCh, to: eodCh} - : {line: 0, from: 0, to: 0}); - break; - } - words.push(word); - cur = Pos(word.line, forward ? (word.to - 1) : word.from); - } - var shortCircuit = words.length != repeat; - var firstWord = words[0]; - var lastWord = words.pop(); - if (forward && !wordEnd) { - if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) { - lastWord = words.pop(); - } - return Pos(lastWord.line, lastWord.from); - } else if (forward && wordEnd) { - return Pos(lastWord.line, lastWord.to - 1); - } else if (!forward && wordEnd) { - if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) { - lastWord = words.pop(); - } - return Pos(lastWord.line, lastWord.to); - } else { - return Pos(lastWord.line, lastWord.from); - } - } - - function moveToCharacter(cm, repeat, forward, character) { - var cur = cm.getCursor(); - var start = cur.ch; - var idx; - for (var i = 0; i < repeat; i ++) { - var line = cm.getLine(cur.line); - idx = charIdxInLine(start, line, character, forward, true); - if (idx == -1) { - return null; - } - start = idx; - } - return Pos(cm.getCursor().line, idx); - } - - function moveToColumn(cm, repeat) { - var line = cm.getCursor().line; - return clipCursorToContent(cm, Pos(line, repeat - 1)); - } - - function updateMark(cm, vim, markName, pos) { - if (!inArray(markName, validMarks)) { - return; - } - if (vim.marks[markName]) { - vim.marks[markName].clear(); - } - vim.marks[markName] = cm.setBookmark(pos); - } - - function charIdxInLine(start, line, character, forward, includeChar) { - var idx; - if (forward) { - idx = line.indexOf(character, start + 1); - if (idx != -1 && !includeChar) { - idx -= 1; - } - } else { - idx = line.lastIndexOf(character, start - 1); - if (idx != -1 && !includeChar) { - idx += 1; - } - } - return idx; - } - - function findParagraph(cm, head, repeat, dir, inclusive) { - var line = head.line; - var min = cm.firstLine(); - var max = cm.lastLine(); - var start, end, i = line; - function isEmpty(i) { return !/\S/.test(cm.getLine(i)); } // ace_patch - function isBoundary(i, dir, any) { - if (any) { return isEmpty(i) != isEmpty(i + dir); } - return !isEmpty(i) && isEmpty(i + dir); - } - function skipFold(i) { - dir = dir > 0 ? 1 : -1; - var foldLine = cm.ace.session.getFoldLine(i); - if (foldLine) { - if (i + dir > foldLine.start.row && i + dir < foldLine.end.row) - dir = (dir > 0 ? foldLine.end.row : foldLine.start.row) - i; - } - } - if (dir) { - while (min <= i && i <= max && repeat > 0) { - skipFold(i); - if (isBoundary(i, dir)) { repeat--; } - i += dir; - } - return new Pos(i, 0); - } - - var vim = cm.state.vim; - if (vim.visualLine && isBoundary(line, 1, true)) { - var anchor = vim.sel.anchor; - if (isBoundary(anchor.line, -1, true)) { - if (!inclusive || anchor.line != line) { - line += 1; - } - } - } - var startState = isEmpty(line); - for (i = line; i <= max && repeat; i++) { - if (isBoundary(i, 1, true)) { - if (!inclusive || isEmpty(i) != startState) { - repeat--; - } - } - } - end = new Pos(i, 0); - if (i > max && !startState) { startState = true; } - else { inclusive = false; } - for (i = line; i > min; i--) { - if (!inclusive || isEmpty(i) == startState || i == line) { - if (isBoundary(i, -1, true)) { break; } - } - } - start = new Pos(i, 0); - return { start: start, end: end }; - } - function selectCompanionObject(cm, head, symb, inclusive) { - var cur = head, start, end; - - var bracketRegexp = ({ - '(': /[()]/, ')': /[()]/, - '[': /[[\]]/, ']': /[[\]]/, - '{': /[{}]/, '}': /[{}]/})[symb]; - var openSym = ({ - '(': '(', ')': '(', - '[': '[', ']': '[', - '{': '{', '}': '{'})[symb]; - var curChar = cm.getLine(cur.line).charAt(cur.ch); - var offset = curChar === openSym ? 1 : 0; - - start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp}); - end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp}); - - if (!start || !end) { - return { start: cur, end: cur }; - } - - start = start.pos; - end = end.pos; - - if ((start.line == end.line && start.ch > end.ch) - || (start.line > end.line)) { - var tmp = start; - start = end; - end = tmp; - } - - if (inclusive) { - end.ch += 1; - } else { - start.ch += 1; - } - - return { start: start, end: end }; - } - function findBeginningAndEnd(cm, head, symb, inclusive) { - var cur = copyCursor(head); - var line = cm.getLine(cur.line); - var chars = line.split(''); - var start, end, i, len; - var firstIndex = chars.indexOf(symb); - if (cur.ch < firstIndex) { - cur.ch = firstIndex; - } - else if (firstIndex < cur.ch && chars[cur.ch] == symb) { - end = cur.ch; // assign end to the current cursor - --cur.ch; // make sure to look backwards - } - if (chars[cur.ch] == symb && !end) { - start = cur.ch + 1; // assign start to ahead of the cursor - } else { - for (i = cur.ch; i > -1 && !start; i--) { - if (chars[i] == symb) { - start = i + 1; - } - } - } - if (start && !end) { - for (i = start, len = chars.length; i < len && !end; i++) { - if (chars[i] == symb) { - end = i; - } - } - } - if (!start || !end) { - return { start: cur, end: cur }; - } - if (inclusive) { - --start; ++end; - } - - return { - start: Pos(cur.line, start), - end: Pos(cur.line, end) - }; - } - defineOption('pcre', true, 'boolean'); - function SearchState() {} - SearchState.prototype = { - getQuery: function() { - return vimGlobalState.query; - }, - setQuery: function(query) { - vimGlobalState.query = query; - }, - getOverlay: function() { - return this.searchOverlay; - }, - setOverlay: function(overlay) { - this.searchOverlay = overlay; - }, - isReversed: function() { - return vimGlobalState.isReversed; - }, - setReversed: function(reversed) { - vimGlobalState.isReversed = reversed; - }, - getScrollbarAnnotate: function() { - return this.annotate; - }, - setScrollbarAnnotate: function(annotate) { - this.annotate = annotate; - } - }; - function getSearchState(cm) { - var vim = cm.state.vim; - return vim.searchState_ || (vim.searchState_ = new SearchState()); - } - function dialog(cm, template, shortText, onClose, options) { - if (cm.openDialog) { - cm.openDialog(template, onClose, { bottom: true, value: options.value, - onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp, - selectValueOnOpen: false}); - } - else { - onClose(prompt(shortText, '')); - } - } - function splitBySlash(argString) { - var slashes = findUnescapedSlashes(argString) || []; - if (!slashes.length) return []; - var tokens = []; - if (slashes[0] !== 0) return; - for (var i = 0; i < slashes.length; i++) { - if (typeof slashes[i] == 'number') - tokens.push(argString.substring(slashes[i] + 1, slashes[i+1])); - } - return tokens; - } - - function findUnescapedSlashes(str) { - var escapeNextChar = false; - var slashes = []; - for (var i = 0; i < str.length; i++) { - var c = str.charAt(i); - if (!escapeNextChar && c == '/') { - slashes.push(i); - } - escapeNextChar = !escapeNextChar && (c == '\\'); - } - return slashes; - } - function translateRegex(str) { - var specials = '|(){'; - var unescape = '}'; - var escapeNextChar = false; - var out = []; - for (var i = -1; i < str.length; i++) { - var c = str.charAt(i) || ''; - var n = str.charAt(i+1) || ''; - var specialComesNext = (n && specials.indexOf(n) != -1); - if (escapeNextChar) { - if (c !== '\\' || !specialComesNext) { - out.push(c); - } - escapeNextChar = false; - } else { - if (c === '\\') { - escapeNextChar = true; - if (n && unescape.indexOf(n) != -1) { - specialComesNext = true; - } - if (!specialComesNext || n === '\\') { - out.push(c); - } - } else { - out.push(c); - if (specialComesNext && n !== '\\') { - out.push('\\'); - } - } - } - } - return out.join(''); - } - var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'}; - function translateRegexReplace(str) { - var escapeNextChar = false; - var out = []; - for (var i = -1; i < str.length; i++) { - var c = str.charAt(i) || ''; - var n = str.charAt(i+1) || ''; - if (charUnescapes[c + n]) { - out.push(charUnescapes[c+n]); - i++; - } else if (escapeNextChar) { - out.push(c); - escapeNextChar = false; - } else { - if (c === '\\') { - escapeNextChar = true; - if ((isNumber(n) || n === '$')) { - out.push('$'); - } else if (n !== '/' && n !== '\\') { - out.push('\\'); - } - } else { - if (c === '$') { - out.push('$'); - } - out.push(c); - if (n === '/') { - out.push('\\'); - } - } - } - } - return out.join(''); - } - var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'}; - function unescapeRegexReplace(str) { - var stream = new CodeMirror.StringStream(str); - var output = []; - while (!stream.eol()) { - while (stream.peek() && stream.peek() != '\\') { - output.push(stream.next()); - } - var matched = false; - for (var matcher in unescapes) { - if (stream.match(matcher, true)) { - matched = true; - output.push(unescapes[matcher]); - break; - } - } - if (!matched) { - output.push(stream.next()); - } - } - return output.join(''); - } - function parseQuery(query, ignoreCase, smartCase) { - var lastSearchRegister = vimGlobalState.registerController.getRegister('/'); - lastSearchRegister.setText(query); - if (query instanceof RegExp) { return query; } - var slashes = findUnescapedSlashes(query); - var regexPart; - var forceIgnoreCase; - if (!slashes.length) { - regexPart = query; - } else { - regexPart = query.substring(0, slashes[0]); - var flagsPart = query.substring(slashes[0]); - forceIgnoreCase = (flagsPart.indexOf('i') != -1); - } - if (!regexPart) { - return null; - } - if (!getOption('pcre')) { - regexPart = translateRegex(regexPart); - } - if (smartCase) { - ignoreCase = (/^[^A-Z]*$/).test(regexPart); - } - var regexp = new RegExp(regexPart, - (ignoreCase || forceIgnoreCase) ? 'i' : undefined); - return regexp; - } - function showConfirm(cm, text) { - if (cm.openNotification) { - cm.openNotification('' + text + '', - {bottom: true, duration: 5000}); - } else { - alert(text); - } - } - function makePrompt(prefix, desc) { - var raw = ''; - if (prefix) { - raw += '' + prefix + ''; - } - raw += ' ' + - ''; - if (desc) { - raw += ''; - raw += desc; - raw += ''; - } - return raw; - } - var searchPromptDesc = '(Javascript regexp)'; - function showPrompt(cm, options) { - var shortText = (options.prefix || '') + ' ' + (options.desc || ''); - var prompt = makePrompt(options.prefix, options.desc); - dialog(cm, prompt, shortText, options.onClose, options); - } - function regexEqual(r1, r2) { - if (r1 instanceof RegExp && r2 instanceof RegExp) { - var props = ['global', 'multiline', 'ignoreCase', 'source']; - for (var i = 0; i < props.length; i++) { - var prop = props[i]; - if (r1[prop] !== r2[prop]) { - return false; - } - } - return true; - } - return false; - } - function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { - if (!rawQuery) { - return; - } - var state = getSearchState(cm); - var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase); - if (!query) { - return; - } - highlightSearchMatches(cm, query); - if (regexEqual(query, state.getQuery())) { - return query; - } - state.setQuery(query); - return query; - } - function searchOverlay(query) { - if (query.source.charAt(0) == '^') { - var matchSol = true; - } - return { - token: function(stream) { - if (matchSol && !stream.sol()) { - stream.skipToEnd(); - return; - } - var match = stream.match(query, false); - if (match) { - if (match[0].length == 0) { - stream.next(); - return 'searching'; - } - if (!stream.sol()) { - stream.backUp(1); - if (!query.exec(stream.next() + match[0])) { - stream.next(); - return null; - } - } - stream.match(query); - return 'searching'; - } - while (!stream.eol()) { - stream.next(); - if (stream.match(query, false)) break; - } - }, - query: query - }; - } - function highlightSearchMatches(cm, query) { - var searchState = getSearchState(cm); - var overlay = searchState.getOverlay(); - if (!overlay || query != overlay.query) { - if (overlay) { - cm.removeOverlay(overlay); - } - overlay = searchOverlay(query); - cm.addOverlay(overlay); - if (cm.showMatchesOnScrollbar) { - if (searchState.getScrollbarAnnotate()) { - searchState.getScrollbarAnnotate().clear(); - } - searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query)); - } - searchState.setOverlay(overlay); - } - } - function findNext(cm, prev, query, repeat) { - if (repeat === undefined) { repeat = 1; } - return cm.operation(function() { - var pos = cm.getCursor(); - var cursor = cm.getSearchCursor(query, pos); - for (var i = 0; i < repeat; i++) { - var found = cursor.find(prev); - if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); } - if (!found) { - cursor = cm.getSearchCursor(query, - (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) ); - if (!cursor.find(prev)) { - return; - } - } - } - return cursor.from(); - }); - } - function clearSearchHighlight(cm) { - var state = getSearchState(cm); - cm.removeOverlay(getSearchState(cm).getOverlay()); - state.setOverlay(null); - if (state.getScrollbarAnnotate()) { - state.getScrollbarAnnotate().clear(); - state.setScrollbarAnnotate(null); - } - } - function isInRange(pos, start, end) { - if (typeof pos != 'number') { - pos = pos.line; - } - if (start instanceof Array) { - return inArray(pos, start); - } else { - if (end) { - return (pos >= start && pos <= end); - } else { - return pos == start; - } - } - } - function getUserVisibleLines(cm) { - var renderer = cm.ace.renderer; - return { - top: renderer.getFirstFullyVisibleRow(), - bottom: renderer.getLastFullyVisibleRow() - } - } - - var ExCommandDispatcher = function() { - this.buildCommandMap_(); - }; - ExCommandDispatcher.prototype = { - processCommand: function(cm, input, opt_params) { - var that = this; - cm.operation(function () { - cm.curOp.isVimOp = true; - that._processCommand(cm, input, opt_params); - }); - }, - _processCommand: function(cm, input, opt_params) { - var vim = cm.state.vim; - var commandHistoryRegister = vimGlobalState.registerController.getRegister(':'); - var previousCommand = commandHistoryRegister.toString(); - if (vim.visualMode) { - exitVisualMode(cm); - } - var inputStream = new CodeMirror.StringStream(input); - commandHistoryRegister.setText(input); - var params = opt_params || {}; - params.input = input; - try { - this.parseInput_(cm, inputStream, params); - } catch(e) { - showConfirm(cm, e); - throw e; - } - var command; - var commandName; - if (!params.commandName) { - if (params.line !== undefined) { - commandName = 'move'; - } - } else { - command = this.matchCommand_(params.commandName); - if (command) { - commandName = command.name; - if (command.excludeFromCommandHistory) { - commandHistoryRegister.setText(previousCommand); - } - this.parseCommandArgs_(inputStream, params, command); - if (command.type == 'exToKey') { - for (var i = 0; i < command.toKeys.length; i++) { - CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping'); - } - return; - } else if (command.type == 'exToEx') { - this.processCommand(cm, command.toInput); - return; - } - } - } - if (!commandName) { - showConfirm(cm, 'Not an editor command ":' + input + '"'); - return; - } - try { - exCommands[commandName](cm, params); - if ((!command || !command.possiblyAsync) && params.callback) { - params.callback(); - } - } catch(e) { - showConfirm(cm, e); - throw e; - } - }, - parseInput_: function(cm, inputStream, result) { - inputStream.eatWhile(':'); - if (inputStream.eat('%')) { - result.line = cm.firstLine(); - result.lineEnd = cm.lastLine(); - } else { - result.line = this.parseLineSpec_(cm, inputStream); - if (result.line !== undefined && inputStream.eat(',')) { - result.lineEnd = this.parseLineSpec_(cm, inputStream); - } - } - var commandMatch = inputStream.match(/^(\w+)/); - if (commandMatch) { - result.commandName = commandMatch[1]; - } else { - result.commandName = inputStream.match(/.*/)[0]; - } - - return result; - }, - parseLineSpec_: function(cm, inputStream) { - var numberMatch = inputStream.match(/^(\d+)/); - if (numberMatch) { - return parseInt(numberMatch[1], 10) - 1; - } - switch (inputStream.next()) { - case '.': - return cm.getCursor().line; - case '$': - return cm.lastLine(); - case '\'': - var mark = cm.state.vim.marks[inputStream.next()]; - if (mark && mark.find()) { - return mark.find().line; - } - throw new Error('Mark not set'); - default: - inputStream.backUp(1); - return undefined; - } - }, - parseCommandArgs_: function(inputStream, params, command) { - if (inputStream.eol()) { - return; - } - params.argString = inputStream.match(/.*/)[0]; - var delim = command.argDelimiter || /\s+/; - var args = trim(params.argString).split(delim); - if (args.length && args[0]) { - params.args = args; - } - }, - matchCommand_: function(commandName) { - for (var i = commandName.length; i > 0; i--) { - var prefix = commandName.substring(0, i); - if (this.commandMap_[prefix]) { - var command = this.commandMap_[prefix]; - if (command.name.indexOf(commandName) === 0) { - return command; - } - } - } - return null; - }, - buildCommandMap_: function() { - this.commandMap_ = {}; - for (var i = 0; i < defaultExCommandMap.length; i++) { - var command = defaultExCommandMap[i]; - var key = command.shortName || command.name; - this.commandMap_[key] = command; - } - }, - map: function(lhs, rhs, ctx) { - if (lhs != ':' && lhs.charAt(0) == ':') { - if (ctx) { throw Error('Mode not supported for ex mappings'); } - var commandName = lhs.substring(1); - if (rhs != ':' && rhs.charAt(0) == ':') { - this.commandMap_[commandName] = { - name: commandName, - type: 'exToEx', - toInput: rhs.substring(1), - user: true - }; - } else { - this.commandMap_[commandName] = { - name: commandName, - type: 'exToKey', - toKeys: rhs, - user: true - }; - } - } else { - if (rhs != ':' && rhs.charAt(0) == ':') { - var mapping = { - keys: lhs, - type: 'keyToEx', - exArgs: { input: rhs.substring(1) }, - user: true}; - if (ctx) { mapping.context = ctx; } - defaultKeymap.unshift(mapping); - } else { - var mapping = { - keys: lhs, - type: 'keyToKey', - toKeys: rhs, - user: true - }; - if (ctx) { mapping.context = ctx; } - defaultKeymap.unshift(mapping); - } - } - }, - unmap: function(lhs, ctx) { - if (lhs != ':' && lhs.charAt(0) == ':') { - if (ctx) { throw Error('Mode not supported for ex mappings'); } - var commandName = lhs.substring(1); - if (this.commandMap_[commandName] && this.commandMap_[commandName].user) { - delete this.commandMap_[commandName]; - return; - } - } else { - var keys = lhs; - for (var i = 0; i < defaultKeymap.length; i++) { - if (keys == defaultKeymap[i].keys - && defaultKeymap[i].context === ctx - && defaultKeymap[i].user) { - defaultKeymap.splice(i, 1); - return; - } - } - } - } - }; - - var exCommands = { - colorscheme: function(cm, params) { - if (!params.args || params.args.length < 1) { - showConfirm(cm, cm.getOption('theme')); - return; - } - cm.setOption('theme', params.args[0]); - }, - map: function(cm, params, ctx) { - var mapArgs = params.args; - if (!mapArgs || mapArgs.length < 2) { - if (cm) { - showConfirm(cm, 'Invalid mapping: ' + params.input); - } - return; - } - exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx); - }, - imap: function(cm, params) { this.map(cm, params, 'insert'); }, - nmap: function(cm, params) { this.map(cm, params, 'normal'); }, - vmap: function(cm, params) { this.map(cm, params, 'visual'); }, - unmap: function(cm, params, ctx) { - var mapArgs = params.args; - if (!mapArgs || mapArgs.length < 1) { - if (cm) { - showConfirm(cm, 'No such mapping: ' + params.input); - } - return; - } - exCommandDispatcher.unmap(mapArgs[0], ctx); - }, - move: function(cm, params) { - commandDispatcher.processCommand(cm, cm.state.vim, { - type: 'motion', - motion: 'moveToLineOrEdgeOfDocument', - motionArgs: { forward: false, explicitRepeat: true, - linewise: true }, - repeatOverride: params.line+1}); - }, - set: function(cm, params) { - var setArgs = params.args; - var setCfg = params.setCfg || {}; - if (!setArgs || setArgs.length < 1) { - if (cm) { - showConfirm(cm, 'Invalid mapping: ' + params.input); - } - return; - } - var expr = setArgs[0].split('='); - var optionName = expr[0]; - var value = expr[1]; - var forceGet = false; - - if (optionName.charAt(optionName.length - 1) == '?') { - if (value) { throw Error('Trailing characters: ' + params.argString); } - optionName = optionName.substring(0, optionName.length - 1); - forceGet = true; - } - if (value === undefined && optionName.substring(0, 2) == 'no') { - optionName = optionName.substring(2); - value = false; - } - - var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean'; - if (optionIsBoolean && value == undefined) { - value = true; - } - if (!optionIsBoolean && value === undefined || forceGet) { - var oldValue = getOption(optionName, cm, setCfg); - if (oldValue === true || oldValue === false) { - showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName); - } else { - showConfirm(cm, ' ' + optionName + '=' + oldValue); - } - } else { - setOption(optionName, value, cm, setCfg); - } - }, - setlocal: function (cm, params) { - params.setCfg = {scope: 'local'}; - this.set(cm, params); - }, - setglobal: function (cm, params) { - params.setCfg = {scope: 'global'}; - this.set(cm, params); - }, - registers: function(cm, params) { - var regArgs = params.args; - var registers = vimGlobalState.registerController.registers; - var regInfo = '----------Registers----------

'; - if (!regArgs) { - for (var registerName in registers) { - var text = registers[registerName].toString(); - if (text.length) { - regInfo += '"' + registerName + ' ' + text + '
'; - } - } - } else { - var registerName; - regArgs = regArgs.join(''); - for (var i = 0; i < regArgs.length; i++) { - registerName = regArgs.charAt(i); - if (!vimGlobalState.registerController.isValidRegister(registerName)) { - continue; - } - var register = registers[registerName] || new Register(); - regInfo += '"' + registerName + ' ' + register.toString() + '
'; - } - } - showConfirm(cm, regInfo); - }, - sort: function(cm, params) { - var reverse, ignoreCase, unique, number; - function parseArgs() { - if (params.argString) { - var args = new CodeMirror.StringStream(params.argString); - if (args.eat('!')) { reverse = true; } - if (args.eol()) { return; } - if (!args.eatSpace()) { return 'Invalid arguments'; } - var opts = args.match(/[a-z]+/); - if (opts) { - opts = opts[0]; - ignoreCase = opts.indexOf('i') != -1; - unique = opts.indexOf('u') != -1; - var decimal = opts.indexOf('d') != -1 && 1; - var hex = opts.indexOf('x') != -1 && 1; - var octal = opts.indexOf('o') != -1 && 1; - if (decimal + hex + octal > 1) { return 'Invalid arguments'; } - number = decimal && 'decimal' || hex && 'hex' || octal && 'octal'; - } - if (args.match(/\/.*\//)) { return 'patterns not supported'; } - } - } - var err = parseArgs(); - if (err) { - showConfirm(cm, err + ': ' + params.argString); - return; - } - var lineStart = params.line || cm.firstLine(); - var lineEnd = params.lineEnd || params.line || cm.lastLine(); - if (lineStart == lineEnd) { return; } - var curStart = Pos(lineStart, 0); - var curEnd = Pos(lineEnd, lineLength(cm, lineEnd)); - var text = cm.getRange(curStart, curEnd).split('\n'); - var numberRegex = (number == 'decimal') ? /(-?)([\d]+)/ : - (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i : - (number == 'octal') ? /([0-7]+)/ : null; - var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null; - var numPart = [], textPart = []; - if (number) { - for (var i = 0; i < text.length; i++) { - if (numberRegex.exec(text[i])) { - numPart.push(text[i]); - } else { - textPart.push(text[i]); - } - } - } else { - textPart = text; - } - function compareFn(a, b) { - if (reverse) { var tmp; tmp = a; a = b; b = tmp; } - if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); } - var anum = number && numberRegex.exec(a); - var bnum = number && numberRegex.exec(b); - if (!anum) { return a < b ? -1 : 1; } - anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix); - bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix); - return anum - bnum; - } - numPart.sort(compareFn); - textPart.sort(compareFn); - text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart); - if (unique) { // Remove duplicate lines - var textOld = text; - var lastLine; - text = []; - for (var i = 0; i < textOld.length; i++) { - if (textOld[i] != lastLine) { - text.push(textOld[i]); - } - lastLine = textOld[i]; - } - } - cm.replaceRange(text.join('\n'), curStart, curEnd); - }, - global: function(cm, params) { - var argString = params.argString; - if (!argString) { - showConfirm(cm, 'Regular Expression missing from global'); - return; - } - var lineStart = (params.line !== undefined) ? params.line : cm.firstLine(); - var lineEnd = params.lineEnd || params.line || cm.lastLine(); - var tokens = splitBySlash(argString); - var regexPart = argString, cmd; - if (tokens.length) { - regexPart = tokens[0]; - cmd = tokens.slice(1, tokens.length).join('/'); - } - if (regexPart) { - try { - updateSearchQuery(cm, regexPart, true /** ignoreCase */, - true /** smartCase */); - } catch (e) { - showConfirm(cm, 'Invalid regex: ' + regexPart); - return; - } - } - var query = getSearchState(cm).getQuery(); - var matchedLines = [], content = ''; - for (var i = lineStart; i <= lineEnd; i++) { - var matched = query.test(cm.getLine(i)); - if (matched) { - matchedLines.push(i+1); - content+= cm.getLine(i) + '
'; - } - } - if (!cmd) { - showConfirm(cm, content); - return; - } - var index = 0; - var nextCommand = function() { - if (index < matchedLines.length) { - var command = matchedLines[index] + cmd; - exCommandDispatcher.processCommand(cm, command, { - callback: nextCommand - }); - } - index++; - }; - nextCommand(); - }, - substitute: function(cm, params) { - if (!cm.getSearchCursor) { - throw new Error('Search feature not available. Requires searchcursor.js or ' + - 'any other getSearchCursor implementation.'); - } - var argString = params.argString; - var tokens = argString ? splitBySlash(argString) : []; - var regexPart, replacePart = '', trailing, flagsPart, count; - var confirm = false; // Whether to confirm each replace. - var global = false; // True to replace all instances on a line, false to replace only 1. - if (tokens.length) { - regexPart = tokens[0]; - replacePart = tokens[1]; - if (replacePart !== undefined) { - if (getOption('pcre')) { - replacePart = unescapeRegexReplace(replacePart); - } else { - replacePart = translateRegexReplace(replacePart); - } - vimGlobalState.lastSubstituteReplacePart = replacePart; - } - trailing = tokens[2] ? tokens[2].split(' ') : []; - } else { - if (argString && argString.length) { - showConfirm(cm, 'Substitutions should be of the form ' + - ':s/pattern/replace/'); - return; - } - } - if (trailing) { - flagsPart = trailing[0]; - count = parseInt(trailing[1]); - if (flagsPart) { - if (flagsPart.indexOf('c') != -1) { - confirm = true; - flagsPart.replace('c', ''); - } - if (flagsPart.indexOf('g') != -1) { - global = true; - flagsPart.replace('g', ''); - } - regexPart = regexPart + '/' + flagsPart; - } - } - if (regexPart) { - try { - updateSearchQuery(cm, regexPart, true /** ignoreCase */, - true /** smartCase */); - } catch (e) { - showConfirm(cm, 'Invalid regex: ' + regexPart); - return; - } - } - replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart; - if (replacePart === undefined) { - showConfirm(cm, 'No previous substitute regular expression'); - return; - } - var state = getSearchState(cm); - var query = state.getQuery(); - var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line; - var lineEnd = params.lineEnd || lineStart; - if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) { - lineEnd = Infinity; - } - if (count) { - lineStart = lineEnd; - lineEnd = lineStart + count - 1; - } - var startPos = clipCursorToContent(cm, Pos(lineStart, 0)); - var cursor = cm.getSearchCursor(query, startPos); - doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback); - }, - redo: CodeMirror.commands.redo, - undo: CodeMirror.commands.undo, - write: function(cm) { - if (CodeMirror.commands.save) { - CodeMirror.commands.save(cm); - } else { - cm.save(); - } - }, - nohlsearch: function(cm) { - clearSearchHighlight(cm); - }, - delmarks: function(cm, params) { - if (!params.argString || !trim(params.argString)) { - showConfirm(cm, 'Argument acequired'); - return; - } - - var state = cm.state.vim; - var stream = new CodeMirror.StringStream(trim(params.argString)); - while (!stream.eol()) { - stream.eatSpace(); - var count = stream.pos; - - if (!stream.match(/[a-zA-Z]/, false)) { - showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); - return; - } - - var sym = stream.next(); - if (stream.match('-', true)) { - if (!stream.match(/[a-zA-Z]/, false)) { - showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); - return; - } - - var startMark = sym; - var finishMark = stream.next(); - if (isLowerCase(startMark) && isLowerCase(finishMark) || - isUpperCase(startMark) && isUpperCase(finishMark)) { - var start = startMark.charCodeAt(0); - var finish = finishMark.charCodeAt(0); - if (start >= finish) { - showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); - return; - } - for (var j = 0; j <= finish - start; j++) { - var mark = String.fromCharCode(start + j); - delete state.marks[mark]; - } - } else { - showConfirm(cm, 'Invalid argument: ' + startMark + '-'); - return; - } - } else { - delete state.marks[sym]; - } - } - } - }; - - var exCommandDispatcher = new ExCommandDispatcher(); - function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query, - replaceWith, callback) { - cm.state.vim.exMode = true; - var done = false; - var lastPos = searchCursor.from(); - function replaceAll() { - cm.operation(function() { - while (!done) { - replace(); - next(); - } - stop(); - }); - } - function replace() { - var text = cm.getRange(searchCursor.from(), searchCursor.to()); - var newText = text.replace(query, replaceWith); - searchCursor.replace(newText); - } - function next() { - while(searchCursor.findNext() && - isInRange(searchCursor.from(), lineStart, lineEnd)) { - if (!global && lastPos && searchCursor.from().line == lastPos.line) { - continue; - } - cm.scrollIntoView(searchCursor.from(), 30); - cm.setSelection(searchCursor.from(), searchCursor.to()); - lastPos = searchCursor.from(); - done = false; - return; - } - done = true; - } - function stop(close) { - if (close) { close(); } - cm.focus(); - if (lastPos) { - cm.setCursor(lastPos); - var vim = cm.state.vim; - vim.exMode = false; - vim.lastHPos = vim.lastHSPos = lastPos.ch; - } - if (callback) { callback(); } - } - function onPromptKeyDown(e, _value, close) { - CodeMirror.e_stop(e); - var keyName = CodeMirror.keyName(e); - switch (keyName) { - case 'Y': - replace(); next(); break; - case 'N': - next(); break; - case 'A': - var savedCallback = callback; - callback = undefined; - cm.operation(replaceAll); - callback = savedCallback; - break; - case 'L': - replace(); - case 'Q': - case 'Esc': - case 'Ctrl-C': - case 'Ctrl-[': - stop(close); - break; - } - if (done) { stop(close); } - return true; - } - next(); - if (done) { - showConfirm(cm, 'No matches for ' + query.source); - return; - } - if (!confirm) { - replaceAll(); - if (callback) { callback(); } - return; - } - showPrompt(cm, { - prefix: 'replace with ' + replaceWith + ' (y/n/a/q/l)', - onKeyDown: onPromptKeyDown - }); - } - - CodeMirror.keyMap.vim = { - attach: attachVimMap, - detach: detachVimMap, - call: cmKey - }; - - function exitInsertMode(cm) { - var vim = cm.state.vim; - var macroModeState = vimGlobalState.macroModeState; - var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.'); - var isPlaying = macroModeState.isPlaying; - var lastChange = macroModeState.lastInsertModeChanges; - var text = []; - if (!isPlaying) { - var selLength = lastChange.inVisualBlock ? vim.lastSelection.visualBlock.height : 1; - var changes = lastChange.changes; - var text = []; - var i = 0; - while (i < changes.length) { - text.push(changes[i]); - if (changes[i] instanceof InsertModeKey) { - i++; - } else { - i+= selLength; - } - } - lastChange.changes = text; - cm.off('change', onChange); - CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); - } - if (!isPlaying && vim.insertModeRepeat > 1) { - repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, - true /** repeatForInsert */); - vim.lastEditInputState.repeatOverride = vim.insertModeRepeat; - } - delete vim.insertModeRepeat; - vim.insertMode = false; - cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1); - cm.setOption('keyMap', 'vim'); - cm.setOption('disableInput', true); - cm.toggleOverwrite(false); // exit replace mode if we were in it. - insertModeChangeRegister.setText(lastChange.changes.join('')); - CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); - if (macroModeState.isRecording) { - logInsertModeChange(macroModeState); - } - } - - function _mapCommand(command) { - defaultKeymap.unshift(command); - } - - function mapCommand(keys, type, name, args, extra) { - var command = {keys: keys, type: type}; - command[type] = name; - command[type + "Args"] = args; - for (var key in extra) - command[key] = extra[key]; - _mapCommand(command); - } - defineOption('insertModeEscKeysTimeout', 200, 'number'); - - CodeMirror.keyMap['vim-insert'] = { - 'Ctrl-N': 'autocomplete', - 'Ctrl-P': 'autocomplete', - 'Enter': function(cm) { - var fn = CodeMirror.commands.newlineAndIndentContinueComment || - CodeMirror.commands.newlineAndIndent; - fn(cm); - }, - fallthrough: ['default'], - attach: attachVimMap, - detach: detachVimMap, - call: cmKey - }; - - CodeMirror.keyMap['vim-replace'] = { - 'Backspace': 'goCharLeft', - fallthrough: ['vim-insert'], - attach: attachVimMap, - detach: detachVimMap, - call: cmKey - }; - - function executeMacroRegister(cm, vim, macroModeState, registerName) { - var register = vimGlobalState.registerController.getRegister(registerName); - if (registerName == ':') { - if (register.keyBuffer[0]) { - exCommandDispatcher.processCommand(cm, register.keyBuffer[0]); - } - macroModeState.isPlaying = false; - return; - } - var keyBuffer = register.keyBuffer; - var imc = 0; - macroModeState.isPlaying = true; - macroModeState.replaySearchQueries = register.searchQueries.slice(0); - for (var i = 0; i < keyBuffer.length; i++) { - var text = keyBuffer[i]; - var match, key; - while (text) { - match = (/<\w+-.+?>|<\w+>|./).exec(text); - key = match[0]; - text = text.substring(match.index + key.length); - CodeMirror.Vim.handleKey(cm, key, 'macro'); - if (vim.insertMode) { - var changes = register.insertModeChanges[imc++].changes; - vimGlobalState.macroModeState.lastInsertModeChanges.changes = - changes; - repeatInsertModeChanges(cm, changes, 1); - exitInsertMode(cm); - } - } - } - macroModeState.isPlaying = false; - } - - function logKey(macroModeState, key) { - if (macroModeState.isPlaying) { return; } - var registerName = macroModeState.latestRegister; - var register = vimGlobalState.registerController.getRegister(registerName); - if (register) { - register.pushText(key); - } - } - - function logInsertModeChange(macroModeState) { - if (macroModeState.isPlaying) { return; } - var registerName = macroModeState.latestRegister; - var register = vimGlobalState.registerController.getRegister(registerName); - if (register && register.pushInsertModeChanges) { - register.pushInsertModeChanges(macroModeState.lastInsertModeChanges); - } - } - - function logSearchQuery(macroModeState, query) { - if (macroModeState.isPlaying) { return; } - var registerName = macroModeState.latestRegister; - var register = vimGlobalState.registerController.getRegister(registerName); - if (register && register.pushSearchQuery) { - register.pushSearchQuery(query); - } - } - function onChange(_cm, changeObj) { - var macroModeState = vimGlobalState.macroModeState; - var lastChange = macroModeState.lastInsertModeChanges; - if (!macroModeState.isPlaying) { - while(changeObj) { - lastChange.expectCursorActivityForChange = true; - if (changeObj.origin == '+input' || changeObj.origin == 'paste' - || changeObj.origin === undefined /* only in testing */) { - var text = changeObj.text.join('\n'); - if (lastChange.maybeReset) { - lastChange.changes = []; - lastChange.maybeReset = false; - } - lastChange.changes.push(text); - } - changeObj = changeObj.next; - } - } - } - function onCursorActivity(cm) { - var vim = cm.state.vim; - if (vim.insertMode) { - var macroModeState = vimGlobalState.macroModeState; - if (macroModeState.isPlaying) { return; } - var lastChange = macroModeState.lastInsertModeChanges; - if (lastChange.expectCursorActivityForChange) { - lastChange.expectCursorActivityForChange = false; - } else { - lastChange.maybeReset = true; - } - } else if (!cm.curOp.isVimOp) { - handleExternalSelection(cm, vim); - } - if (vim.visualMode) { - updateFakeCursor(cm); - } - } - function updateFakeCursor(cm) { - var vim = cm.state.vim; - var from = clipCursorToContent(cm, copyCursor(vim.sel.head)); - var to = offsetCursor(from, 0, 1); - if (vim.fakeCursor) { - vim.fakeCursor.clear(); - } - vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'}); - } - function handleExternalSelection(cm, vim) { - var anchor = cm.getCursor('anchor'); - var head = cm.getCursor('head'); - if (vim.visualMode && !cm.somethingSelected()) { - exitVisualMode(cm, false); - } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) { - vim.visualMode = true; - vim.visualLine = false; - CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); - } - if (vim.visualMode) { - var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; - var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; - head = offsetCursor(head, 0, headOffset); - anchor = offsetCursor(anchor, 0, anchorOffset); - vim.sel = { - anchor: anchor, - head: head - }; - updateMark(cm, vim, '<', cursorMin(head, anchor)); - updateMark(cm, vim, '>', cursorMax(head, anchor)); - } else if (!vim.insertMode) { - vim.lastHPos = cm.getCursor().ch; - } - } - function InsertModeKey(keyName) { - this.keyName = keyName; - } - function onKeyEventTargetKeyDown(e) { - var macroModeState = vimGlobalState.macroModeState; - var lastChange = macroModeState.lastInsertModeChanges; - var keyName = CodeMirror.keyName(e); - if (!keyName) { return; } - function onKeyFound() { - if (lastChange.maybeReset) { - lastChange.changes = []; - lastChange.maybeReset = false; - } - lastChange.changes.push(new InsertModeKey(keyName)); - return true; - } - if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { - CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound); - } - } - function repeatLastEdit(cm, vim, repeat, repeatForInsert) { - var macroModeState = vimGlobalState.macroModeState; - macroModeState.isPlaying = true; - var isAction = !!vim.lastEditActionCommand; - var cachedInputState = vim.inputState; - function repeatCommand() { - if (isAction) { - commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); - } else { - commandDispatcher.evalInput(cm, vim); - } - } - function repeatInsert(repeat) { - if (macroModeState.lastInsertModeChanges.changes.length > 0) { - repeat = !vim.lastEditActionCommand ? 1 : repeat; - var changeObject = macroModeState.lastInsertModeChanges; - repeatInsertModeChanges(cm, changeObject.changes, repeat); - } - } - vim.inputState = vim.lastEditInputState; - if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { - for (var i = 0; i < repeat; i++) { - repeatCommand(); - repeatInsert(1); - } - } else { - if (!repeatForInsert) { - repeatCommand(); - } - repeatInsert(repeat); - } - vim.inputState = cachedInputState; - if (vim.insertMode && !repeatForInsert) { - exitInsertMode(cm); - } - macroModeState.isPlaying = false; - } - - function repeatInsertModeChanges(cm, changes, repeat) { - function keyHandler(binding) { - if (typeof binding == 'string') { - CodeMirror.commands[binding](cm); - } else { - binding(cm); - } - return true; - } - var head = cm.getCursor('head'); - var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock; - if (inVisualBlock) { - var vim = cm.state.vim; - var lastSel = vim.lastSelection; - var offset = getOffset(lastSel.anchor, lastSel.head); - selectForInsert(cm, head, offset.line + 1); - repeat = cm.listSelections().length; - cm.setCursor(head); - } - for (var i = 0; i < repeat; i++) { - if (inVisualBlock) { - cm.setCursor(offsetCursor(head, i, 0)); - } - for (var j = 0; j < changes.length; j++) { - var change = changes[j]; - if (change instanceof InsertModeKey) { - CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler); - } else { - var cur = cm.getCursor(); - cm.replaceRange(change, cur, cur); - } - } - } - if (inVisualBlock) { - cm.setCursor(offsetCursor(head, 0, 1)); - } - } - - resetVimGlobalState(); - CodeMirror.Vim = Vim(); - - Vim = CodeMirror.Vim; - - var specialKey = {'return':'CR',backspace:'BS','delete':'Del',esc:'Esc', - left:'Left',right:'Right',up:'Up',down:'Down',space: 'Space', - home:'Home',end:'End',pageup:'PageUp',pagedown:'PageDown', enter: 'CR' - }; - function lookupKey(hashId, key, e) { - if (key.length > 1 && key[0] == "n") { - key = key.replace("numpad", ""); - } - key = specialKey[key] || key; - var name = ''; - if (e.ctrlKey) { name += 'C-'; } - if (e.altKey) { name += 'A-'; } - if (e.shiftKey) { name += 'S-'; } - - name += key; - if (name.length > 1) { name = '<' + name + '>'; } - return name; - } - var handleKey = Vim.handleKey.bind(Vim); - Vim.handleKey = function(cm, key, origin) { - return cm.operation(function() { - return handleKey(cm, key, origin); - }, true); - } - function cloneVimState(state) { - var n = new state.constructor(); - Object.keys(state).forEach(function(key) { - var o = state[key]; - if (Array.isArray(o)) - o = o.slice(); - else if (o && typeof o == "object" && o.constructor != Object) - o = cloneVimState(o); - n[key] = o; - }); - if (state.sel) { - n.sel = { - head: state.sel.head && copyCursor(state.sel.head), - anchor: state.sel.anchor && copyCursor(state.sel.anchor) - }; - } - return n; - } - function multiSelectHandleKey(cm, key, origin) { - var isHandled = false; - var vim = Vim.maybeInitVimState_(cm); - var visualBlock = vim.visualBlock || vim.wasInVisualBlock; - if (vim.wasInVisualBlock && !cm.ace.inMultiSelectMode) { - vim.wasInVisualBlock = false; - } else if (cm.ace.inMultiSelectMode && vim.visualBlock) { - vim.wasInVisualBlock = true; - } - - if (key == '' && !vim.insertMode && !vim.visualMode && cm.ace.inMultiSelectMode) { - cm.ace.exitMultiSelectMode(); - } else if (visualBlock || !cm.ace.inMultiSelectMode || cm.ace.inVirtualSelectionMode) { - isHandled = Vim.handleKey(cm, key, origin); - } else { - var old = cloneVimState(vim); - cm.operation(function() { - cm.ace.forEachSelection(function() { - var sel = cm.ace.selection; - cm.state.vim.lastHPos = sel.$desiredColumn == null ? sel.lead.column : sel.$desiredColumn; - var head = cm.getCursor("head"); - var anchor = cm.getCursor("anchor"); - var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; - var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; - head = offsetCursor(head, 0, headOffset); - anchor = offsetCursor(anchor, 0, anchorOffset); - cm.state.vim.sel.head = head; - cm.state.vim.sel.anchor = anchor; - - isHandled = handleKey(cm, key, origin); - sel.$desiredColumn = cm.state.vim.lastHPos == -1 ? null : cm.state.vim.lastHPos; - if (cm.virtualSelectionMode()) { - cm.state.vim = cloneVimState(old); - } - }); - if (cm.curOp.cursorActivity && !isHandled) - cm.curOp.cursorActivity = false; - }, true); - } - return isHandled; - } - exports.CodeMirror = CodeMirror; - var getVim = Vim.maybeInitVimState_; - exports.handler = { - $id: "ace/keyboard/vim", - drawCursor: function(style, pixelPos, config, sel, session) { - var vim = this.state.vim || {}; - var w = config.characterWidth; - var h = config.lineHeight; - var top = pixelPos.top; - var left = pixelPos.left; - if (!vim.insertMode) { - var isbackwards = !sel.cursor - ? session.selection.isBackwards() || session.selection.isEmpty() - : Range.comparePoints(sel.cursor, sel.start) <= 0; - if (!isbackwards && left > w) - left -= w; - } - if (!vim.insertMode && vim.status) { - h = h / 2; - top += h; - } - style.left = left + "px"; - style.top = top + "px"; - style.width = w + "px"; - style.height = h + "px"; - }, - handleKeyboard: function(data, hashId, key, keyCode, e) { - var editor = data.editor; - var cm = editor.state.cm; - var vim = getVim(cm); - if (keyCode == -1) return; - - if (key == "c" && hashId == 1) { // key == "ctrl-c" - if (!useragent.isMac && editor.getCopyText()) { - editor.once("copy", function() { - editor.selection.clearSelection(); - }); - return {command: "null", passEvent: true}; - } - } else if (!vim.insertMode) { - if (useragent.isMac && this.handleMacRepeat(data, hashId, key)) { - hashId = -1; - key = data.inputChar; - } - } - - if (hashId == -1 || hashId & 1 || hashId === 0 && key.length > 1) { - var insertMode = vim.insertMode; - var name = lookupKey(hashId, key, e || {}); - if (vim.status == null) - vim.status = ""; - var isHandled = multiSelectHandleKey(cm, name, 'user'); - vim = getVim(cm); // may be changed by multiSelectHandleKey - if (isHandled && vim.status != null) - vim.status += name; - else if (vim.status == null) - vim.status = ""; - cm._signal("changeStatus"); - if (!isHandled && (hashId != -1 || insertMode)) - return; - return {command: "null", passEvent: !isHandled}; - } - }, - attach: function(editor) { - if (!editor.state) editor.state = {}; - var cm = new CodeMirror(editor); - editor.state.cm = cm; - editor.$vimModeHandler = this; - CodeMirror.keyMap.vim.attach(cm); - getVim(cm).status = null; - cm.on('vim-command-done', function() { - if (cm.virtualSelectionMode()) return; - getVim(cm).status = null; - cm.ace._signal("changeStatus"); - cm.ace.session.markUndoGroup(); - }); - cm.on("changeStatus", function() { - cm.ace.renderer.updateCursor(); - cm.ace._signal("changeStatus"); - }); - cm.on("vim-mode-change", function() { - if (cm.virtualSelectionMode()) return; - cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); - cm._signal("changeStatus"); - }); - cm.ace.renderer.setStyle("normal-mode", !getVim(cm).insertMode); - editor.renderer.$cursorLayer.drawCursor = this.drawCursor.bind(cm); - this.updateMacCompositionHandlers(editor, true); - }, - detach: function(editor) { - var cm = editor.state.cm; - CodeMirror.keyMap.vim.detach(cm); - cm.destroy(); - editor.state.cm = null; - editor.$vimModeHandler = null; - editor.renderer.$cursorLayer.drawCursor = null; - editor.renderer.setStyle("normal-mode", false); - this.updateMacCompositionHandlers(editor, false); - }, - getStatusText: function(editor) { - var cm = editor.state.cm; - var vim = getVim(cm); - if (vim.insertMode) - return "INSERT"; - var status = ""; - if (vim.visualMode) { - status += "VISUAL"; - if (vim.visualLine) - status += " LINE"; - if (vim.visualBlock) - status += " BLOCK"; - } - if (vim.status) - status += (status ? " " : "") + vim.status; - return status; - }, - handleMacRepeat: function(data, hashId, key) { - if (hashId == -1) { - data.inputChar = key; - data.lastEvent = "input"; - } else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) { - if (data.lastEvent == "input") { - data.lastEvent = "input1"; - } else if (data.lastEvent == "input1") { - return true; - } - } else { - data.$lastHash = hashId; - data.$lastKey = key; - data.lastEvent = "keypress"; - } - }, - updateMacCompositionHandlers: function(editor, enable) { - var onCompositionUpdateOverride = function(text) { - var cm = editor.state.cm; - var vim = getVim(cm); - if (!vim.insertMode) { - var el = this.textInput.getElement(); - el.blur(); - el.focus(); - el.value = text; - } else { - this.onCompositionUpdateOrig(text); - } - }; - var onCompositionStartOverride = function(text) { - var cm = editor.state.cm; - var vim = getVim(cm); - if (!vim.insertMode) { - this.onCompositionStartOrig(text); - } - }; - if (enable) { - if (!editor.onCompositionUpdateOrig) { - editor.onCompositionUpdateOrig = editor.onCompositionUpdate; - editor.onCompositionUpdate = onCompositionUpdateOverride; - editor.onCompositionStartOrig = editor.onCompositionStart; - editor.onCompositionStart = onCompositionStartOverride; - } - } else { - if (editor.onCompositionUpdateOrig) { - editor.onCompositionUpdate = editor.onCompositionUpdateOrig; - editor.onCompositionUpdateOrig = null; - editor.onCompositionStart = editor.onCompositionStartOrig; - editor.onCompositionStartOrig = null; - } - } - } - }; - var renderVirtualNumbers = { - getText: function(session, row) { - return (Math.abs(session.selection.lead.row - row) || (row + 1 + (row < 9? "\xb7" : "" ))) + ""; - }, - getWidth: function(session, lastLineNumber, config) { - return session.getLength().toString().length * config.characterWidth; - }, - update: function(e, editor) { - editor.renderer.$loop.schedule(editor.renderer.CHANGE_GUTTER); - }, - attach: function(editor) { - editor.renderer.$gutterLayer.$renderer = this; - editor.on("changeSelection", this.update); - }, - detach: function(editor) { - editor.renderer.$gutterLayer.$renderer = null; - editor.off("changeSelection", this.update); - } - }; - Vim.defineOption({ - name: "wrap", - set: function(value, cm) { - if (cm) {cm.ace.setOption("wrap", value)} - }, - type: "boolean" - }, false); - Vim.defineEx('write', 'w', function() { - console.log(':write is not implemented') - }); - defaultKeymap.push( - { keys: 'zc', type: 'action', action: 'fold', actionArgs: { open: false } }, - { keys: 'zC', type: 'action', action: 'fold', actionArgs: { open: false, all: true } }, - { keys: 'zo', type: 'action', action: 'fold', actionArgs: { open: true } }, - { keys: 'zO', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, - { keys: 'za', type: 'action', action: 'fold', actionArgs: { toggle: true } }, - { keys: 'zA', type: 'action', action: 'fold', actionArgs: { toggle: true, all: true } }, - { keys: 'zf', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, - { keys: 'zd', type: 'action', action: 'fold', actionArgs: { open: true, all: true } }, - - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAbove" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelow" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorAboveSkipCurrent" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "addCursorBelowSkipCurrent" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreBefore" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectMoreAfter" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextBefore" } }, - { keys: '', type: 'action', action: 'aceCommand', actionArgs: { name: "selectNextAfter" } } - ); - actions.aceCommand = function(cm, actionArgs, vim) { - cm.vimCmd = actionArgs; - if (cm.ace.inVirtualSelectionMode) - cm.ace.on("beforeEndOperation", delayedExecAceCommand); - else - delayedExecAceCommand(null, cm.ace); - }; - function delayedExecAceCommand(op, ace) { - ace.off("beforeEndOperation", delayedExecAceCommand); - var cmd = ace.state.cm.vimCmd; - if (cmd) { - ace.execCommand(cmd.exec ? cmd : cmd.name, cmd.args); - } - ace.curOp = ace.prevOp; - } - actions.fold = function(cm, actionArgs, vim) { - cm.ace.execCommand(['toggleFoldWidget', 'toggleFoldWidget', 'foldOther', 'unfoldall' - ][(actionArgs.all ? 2 : 0) + (actionArgs.open ? 1 : 0)]); - }; - - exports.handler.defaultKeymap = defaultKeymap; - exports.handler.actions = actions; - exports.Vim = Vim; - - Vim.map("Y", "yy", "normal"); -}); - - -/***/ }), -/* 68 */ -/***/ (function(module, exports) { - -ace.define("ace/occur",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/edit_session","ace/search_highlight","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var Range = acequire("./range").Range; -var Search = acequire("./search").Search; -var EditSession = acequire("./edit_session").EditSession; -var SearchHighlight = acequire("./search_highlight").SearchHighlight; -function Occur() {} - -oop.inherits(Occur, Search); - -(function() { - this.enter = function(editor, options) { - if (!options.needle) return false; - var pos = editor.getCursorPosition(); - this.displayOccurContent(editor, options); - var translatedPos = this.originalToOccurPosition(editor.session, pos); - editor.moveCursorToPosition(translatedPos); - return true; - } - this.exit = function(editor, options) { - var pos = options.translatePosition && editor.getCursorPosition(); - var translatedPos = pos && this.occurToOriginalPosition(editor.session, pos); - this.displayOriginalContent(editor); - if (translatedPos) - editor.moveCursorToPosition(translatedPos); - return true; - } - - this.highlight = function(sess, regexp) { - var hl = sess.$occurHighlight = sess.$occurHighlight || sess.addDynamicMarker( - new SearchHighlight(null, "ace_occur-highlight", "text")); - hl.setRegexp(regexp); - sess._emit("changeBackMarker"); // force highlight layer redraw - } - - this.displayOccurContent = function(editor, options) { - this.$originalSession = editor.session; - var found = this.matchingLines(editor.session, options); - var lines = found.map(function(foundLine) { return foundLine.content; }); - var occurSession = new EditSession(lines.join('\n')); - occurSession.$occur = this; - occurSession.$occurMatchingLines = found; - editor.setSession(occurSession); - this.$useEmacsStyleLineStart = this.$originalSession.$useEmacsStyleLineStart; - occurSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; - this.highlight(occurSession, options.re); - occurSession._emit('changeBackMarker'); - } - - this.displayOriginalContent = function(editor) { - editor.setSession(this.$originalSession); - this.$originalSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart; - } - this.originalToOccurPosition = function(session, pos) { - var lines = session.$occurMatchingLines; - var nullPos = {row: 0, column: 0}; - if (!lines) return nullPos; - for (var i = 0; i < lines.length; i++) { - if (lines[i].row === pos.row) - return {row: i, column: pos.column}; - } - return nullPos; - } - this.occurToOriginalPosition = function(session, pos) { - var lines = session.$occurMatchingLines; - if (!lines || !lines[pos.row]) - return pos; - return {row: lines[pos.row].row, column: pos.column}; - } - - this.matchingLines = function(session, options) { - options = oop.mixin({}, options); - if (!session || !options.needle) return []; - var search = new Search(); - search.set(options); - return search.findAll(session).reduce(function(lines, range) { - var row = range.start.row; - var last = lines[lines.length-1]; - return last && last.row === row ? - lines : - lines.concat({row: row, content: session.getLine(row)}); - }, []); - } - -}).call(Occur.prototype); - -var dom = acequire('./lib/dom'); -dom.importCssString(".ace_occur-highlight {\n\ - border-radius: 4px;\n\ - background-color: rgba(87, 255, 8, 0.25);\n\ - position: absolute;\n\ - z-index: 4;\n\ - -moz-box-sizing: border-box;\n\ - -webkit-box-sizing: border-box;\n\ - box-sizing: border-box;\n\ - box-shadow: 0 0 4px rgb(91, 255, 50);\n\ -}\n\ -.ace_dark .ace_occur-highlight {\n\ - background-color: rgb(80, 140, 85);\n\ - box-shadow: 0 0 4px rgb(60, 120, 70);\n\ -}\n", "incremental-occur-highlighting"); - -exports.Occur = Occur; - -}); - -ace.define("ace/commands/occur_commands",["require","exports","module","ace/config","ace/occur","ace/keyboard/hash_handler","ace/lib/oop"], function(acequire, exports, module) { - -var config = acequire("../config"), - Occur = acequire("../occur").Occur; -var occurStartCommand = { - name: "occur", - exec: function(editor, options) { - var alreadyInOccur = !!editor.session.$occur; - var occurSessionActive = new Occur().enter(editor, options); - if (occurSessionActive && !alreadyInOccur) - OccurKeyboardHandler.installIn(editor); - }, - readOnly: true -}; - -var occurCommands = [{ - name: "occurexit", - bindKey: 'esc|Ctrl-G', - exec: function(editor) { - var occur = editor.session.$occur; - if (!occur) return; - occur.exit(editor, {}); - if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); - }, - readOnly: true -}, { - name: "occuraccept", - bindKey: 'enter', - exec: function(editor) { - var occur = editor.session.$occur; - if (!occur) return; - occur.exit(editor, {translatePosition: true}); - if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor); - }, - readOnly: true -}]; - -var HashHandler = acequire("../keyboard/hash_handler").HashHandler; -var oop = acequire("../lib/oop"); - - -function OccurKeyboardHandler() {} - -oop.inherits(OccurKeyboardHandler, HashHandler); - -(function() { - - this.isOccurHandler = true; - - this.attach = function(editor) { - HashHandler.call(this, occurCommands, editor.commands.platform); - this.$editor = editor; - } - - var handleKeyboard$super = this.handleKeyboard; - this.handleKeyboard = function(data, hashId, key, keyCode) { - var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); - return (cmd && cmd.command) ? cmd : undefined; - } - -}).call(OccurKeyboardHandler.prototype); - -OccurKeyboardHandler.installIn = function(editor) { - var handler = new this(); - editor.keyBinding.addKeyboardHandler(handler); - editor.commands.addCommands(occurCommands); -} - -OccurKeyboardHandler.uninstallFrom = function(editor) { - editor.commands.removeCommands(occurCommands); - var handler = editor.getKeyboardHandler(); - if (handler.isOccurHandler) - editor.keyBinding.removeKeyboardHandler(handler); -} - -exports.occurStartCommand = occurStartCommand; - -}); - -ace.define("ace/commands/incremental_search_commands",["require","exports","module","ace/config","ace/lib/oop","ace/keyboard/hash_handler","ace/commands/occur_commands"], function(acequire, exports, module) { - -var config = acequire("../config"); -var oop = acequire("../lib/oop"); -var HashHandler = acequire("../keyboard/hash_handler").HashHandler; -var occurStartCommand = acequire("./occur_commands").occurStartCommand; -exports.iSearchStartCommands = [{ - name: "iSearch", - bindKey: {win: "Ctrl-F", mac: "Command-F"}, - exec: function(editor, options) { - config.loadModule(["core", "ace/incremental_search"], function(e) { - var iSearch = e.iSearch = e.iSearch || new e.IncrementalSearch(); - iSearch.activate(editor, options.backwards); - if (options.jumpToFirstMatch) iSearch.next(options); - }); - }, - readOnly: true -}, { - name: "iSearchBackwards", - exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {backwards: true}); }, - readOnly: true -}, { - name: "iSearchAndGo", - bindKey: {win: "Ctrl-K", mac: "Command-G"}, - exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {jumpToFirstMatch: true, useCurrentOrPrevSearch: true}); }, - readOnly: true -}, { - name: "iSearchBackwardsAndGo", - bindKey: {win: "Ctrl-Shift-K", mac: "Command-Shift-G"}, - exec: function(editor) { editor.execCommand('iSearch', {jumpToFirstMatch: true, backwards: true, useCurrentOrPrevSearch: true}); }, - readOnly: true -}]; -exports.iSearchCommands = [{ - name: "restartSearch", - bindKey: {win: "Ctrl-F", mac: "Command-F"}, - exec: function(iSearch) { - iSearch.cancelSearch(true); - } -}, { - name: "searchForward", - bindKey: {win: "Ctrl-S|Ctrl-K", mac: "Ctrl-S|Command-G"}, - exec: function(iSearch, options) { - options.useCurrentOrPrevSearch = true; - iSearch.next(options); - } -}, { - name: "searchBackward", - bindKey: {win: "Ctrl-R|Ctrl-Shift-K", mac: "Ctrl-R|Command-Shift-G"}, - exec: function(iSearch, options) { - options.useCurrentOrPrevSearch = true; - options.backwards = true; - iSearch.next(options); - } -}, { - name: "extendSearchTerm", - exec: function(iSearch, string) { - iSearch.addString(string); - } -}, { - name: "extendSearchTermSpace", - bindKey: "space", - exec: function(iSearch) { iSearch.addString(' '); } -}, { - name: "shrinkSearchTerm", - bindKey: "backspace", - exec: function(iSearch) { - iSearch.removeChar(); - } -}, { - name: 'confirmSearch', - bindKey: 'return', - exec: function(iSearch) { iSearch.deactivate(); } -}, { - name: 'cancelSearch', - bindKey: 'esc|Ctrl-G', - exec: function(iSearch) { iSearch.deactivate(true); } -}, { - name: 'occurisearch', - bindKey: 'Ctrl-O', - exec: function(iSearch) { - var options = oop.mixin({}, iSearch.$options); - iSearch.deactivate(); - occurStartCommand.exec(iSearch.$editor, options); - } -}, { - name: "yankNextWord", - bindKey: "Ctrl-w", - exec: function(iSearch) { - var ed = iSearch.$editor, - range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorWordRight(); }), - string = ed.session.getTextRange(range); - iSearch.addString(string); - } -}, { - name: "yankNextChar", - bindKey: "Ctrl-Alt-y", - exec: function(iSearch) { - var ed = iSearch.$editor, - range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorRight(); }), - string = ed.session.getTextRange(range); - iSearch.addString(string); - } -}, { - name: 'recenterTopBottom', - bindKey: 'Ctrl-l', - exec: function(iSearch) { iSearch.$editor.execCommand('recenterTopBottom'); } -}, { - name: 'selectAllMatches', - bindKey: 'Ctrl-space', - exec: function(iSearch) { - var ed = iSearch.$editor, - hl = ed.session.$isearchHighlight, - ranges = hl && hl.cache ? hl.cache - .reduce(function(ranges, ea) { - return ranges.concat(ea ? ea : []); }, []) : []; - iSearch.deactivate(false); - ranges.forEach(ed.selection.addRange.bind(ed.selection)); - } -}, { - name: 'searchAsRegExp', - bindKey: 'Alt-r', - exec: function(iSearch) { - iSearch.convertNeedleToRegExp(); - } -}].map(function(cmd) { - cmd.readOnly = true; - cmd.isIncrementalSearchCommand = true; - cmd.scrollIntoView = "animate-cursor"; - return cmd; -}); - -function IncrementalSearchKeyboardHandler(iSearch) { - this.$iSearch = iSearch; -} - -oop.inherits(IncrementalSearchKeyboardHandler, HashHandler); - -(function() { - - this.attach = function(editor) { - var iSearch = this.$iSearch; - HashHandler.call(this, exports.iSearchCommands, editor.commands.platform); - this.$commandExecHandler = editor.commands.addEventListener('exec', function(e) { - if (!e.command.isIncrementalSearchCommand) - return iSearch.deactivate(); - e.stopPropagation(); - e.preventDefault(); - var scrollTop = editor.session.getScrollTop(); - var result = e.command.exec(iSearch, e.args || {}); - editor.renderer.scrollCursorIntoView(null, 0.5); - editor.renderer.animateScrolling(scrollTop); - return result; - }); - }; - - this.detach = function(editor) { - if (!this.$commandExecHandler) return; - editor.commands.removeEventListener('exec', this.$commandExecHandler); - delete this.$commandExecHandler; - }; - - var handleKeyboard$super = this.handleKeyboard; - this.handleKeyboard = function(data, hashId, key, keyCode) { - if (((hashId === 1/*ctrl*/ || hashId === 8/*command*/) && key === 'v') - || (hashId === 1/*ctrl*/ && key === 'y')) return null; - var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode); - if (cmd.command) { return cmd; } - if (hashId == -1) { - var extendCmd = this.commands.extendSearchTerm; - if (extendCmd) { return {command: extendCmd, args: key}; } - } - return false; - }; - -}).call(IncrementalSearchKeyboardHandler.prototype); - - -exports.IncrementalSearchKeyboardHandler = IncrementalSearchKeyboardHandler; - -}); - -ace.define("ace/incremental_search",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/search_highlight","ace/commands/incremental_search_commands","ace/lib/dom","ace/commands/command_manager","ace/editor","ace/config"], function(acequire, exports, module) { -"use strict"; - -var oop = acequire("./lib/oop"); -var Range = acequire("./range").Range; -var Search = acequire("./search").Search; -var SearchHighlight = acequire("./search_highlight").SearchHighlight; -var iSearchCommandModule = acequire("./commands/incremental_search_commands"); -var ISearchKbd = iSearchCommandModule.IncrementalSearchKeyboardHandler; -function IncrementalSearch() { - this.$options = {wrap: false, skipCurrent: false}; - this.$keyboardHandler = new ISearchKbd(this); -} - -oop.inherits(IncrementalSearch, Search); - -function isRegExp(obj) { - return obj instanceof RegExp; -} - -function regExpToObject(re) { - var string = String(re), - start = string.indexOf('/'), - flagStart = string.lastIndexOf('/'); - return { - expression: string.slice(start+1, flagStart), - flags: string.slice(flagStart+1) - } -} - -function stringToRegExp(string, flags) { - try { - return new RegExp(string, flags); - } catch (e) { return string; } -} - -function objectToRegExp(obj) { - return stringToRegExp(obj.expression, obj.flags); -} - -(function() { - - this.activate = function(ed, backwards) { - this.$editor = ed; - this.$startPos = this.$currentPos = ed.getCursorPosition(); - this.$options.needle = ''; - this.$options.backwards = backwards; - ed.keyBinding.addKeyboardHandler(this.$keyboardHandler); - this.$originalEditorOnPaste = ed.onPaste; ed.onPaste = this.onPaste.bind(this); - this.$mousedownHandler = ed.addEventListener('mousedown', this.onMouseDown.bind(this)); - this.selectionFix(ed); - this.statusMessage(true); - }; - - this.deactivate = function(reset) { - this.cancelSearch(reset); - var ed = this.$editor; - ed.keyBinding.removeKeyboardHandler(this.$keyboardHandler); - if (this.$mousedownHandler) { - ed.removeEventListener('mousedown', this.$mousedownHandler); - delete this.$mousedownHandler; - } - ed.onPaste = this.$originalEditorOnPaste; - this.message(''); - }; - - this.selectionFix = function(editor) { - if (editor.selection.isEmpty() && !editor.session.$emacsMark) { - editor.clearSelection(); - } - }; - - this.highlight = function(regexp) { - var sess = this.$editor.session, - hl = sess.$isearchHighlight = sess.$isearchHighlight || sess.addDynamicMarker( - new SearchHighlight(null, "ace_isearch-result", "text")); - hl.setRegexp(regexp); - sess._emit("changeBackMarker"); // force highlight layer redraw - }; - - this.cancelSearch = function(reset) { - var e = this.$editor; - this.$prevNeedle = this.$options.needle; - this.$options.needle = ''; - if (reset) { - e.moveCursorToPosition(this.$startPos); - this.$currentPos = this.$startPos; - } else { - e.pushEmacsMark && e.pushEmacsMark(this.$startPos, false); - } - this.highlight(null); - return Range.fromPoints(this.$currentPos, this.$currentPos); - }; - - this.highlightAndFindWithNeedle = function(moveToNext, needleUpdateFunc) { - if (!this.$editor) return null; - var options = this.$options; - if (needleUpdateFunc) { - options.needle = needleUpdateFunc.call(this, options.needle || '') || ''; - } - if (options.needle.length === 0) { - this.statusMessage(true); - return this.cancelSearch(true); - } - options.start = this.$currentPos; - var session = this.$editor.session, - found = this.find(session), - shouldSelect = this.$editor.emacsMark ? - !!this.$editor.emacsMark() : !this.$editor.selection.isEmpty(); - if (found) { - if (options.backwards) found = Range.fromPoints(found.end, found.start); - this.$editor.selection.setRange(Range.fromPoints(shouldSelect ? this.$startPos : found.end, found.end)); - if (moveToNext) this.$currentPos = found.end; - this.highlight(options.re); - } - - this.statusMessage(found); - - return found; - }; - - this.addString = function(s) { - return this.highlightAndFindWithNeedle(false, function(needle) { - if (!isRegExp(needle)) - return needle + s; - var reObj = regExpToObject(needle); - reObj.expression += s; - return objectToRegExp(reObj); - }); - }; - - this.removeChar = function(c) { - return this.highlightAndFindWithNeedle(false, function(needle) { - if (!isRegExp(needle)) - return needle.substring(0, needle.length-1); - var reObj = regExpToObject(needle); - reObj.expression = reObj.expression.substring(0, reObj.expression.length-1); - return objectToRegExp(reObj); - }); - }; - - this.next = function(options) { - options = options || {}; - this.$options.backwards = !!options.backwards; - this.$currentPos = this.$editor.getCursorPosition(); - return this.highlightAndFindWithNeedle(true, function(needle) { - return options.useCurrentOrPrevSearch && needle.length === 0 ? - this.$prevNeedle || '' : needle; - }); - }; - - this.onMouseDown = function(evt) { - this.deactivate(); - return true; - }; - - this.onPaste = function(text) { - this.addString(text); - }; - - this.convertNeedleToRegExp = function() { - return this.highlightAndFindWithNeedle(false, function(needle) { - return isRegExp(needle) ? needle : stringToRegExp(needle, 'ig'); - }); - }; - - this.convertNeedleToString = function() { - return this.highlightAndFindWithNeedle(false, function(needle) { - return isRegExp(needle) ? regExpToObject(needle).expression : needle; - }); - }; - - this.statusMessage = function(found) { - var options = this.$options, msg = ''; - msg += options.backwards ? 'reverse-' : ''; - msg += 'isearch: ' + options.needle; - msg += found ? '' : ' (not found)'; - this.message(msg); - }; - - this.message = function(msg) { - if (this.$editor.showCommandLine) { - this.$editor.showCommandLine(msg); - this.$editor.focus(); - } else { - console.log(msg); - } - }; - -}).call(IncrementalSearch.prototype); - - -exports.IncrementalSearch = IncrementalSearch; - -var dom = acequire('./lib/dom'); -dom.importCssString && dom.importCssString("\ -.ace_marker-layer .ace_isearch-result {\ - position: absolute;\ - z-index: 6;\ - -moz-box-sizing: border-box;\ - -webkit-box-sizing: border-box;\ - box-sizing: border-box;\ -}\ -div.ace_isearch-result {\ - border-radius: 4px;\ - background-color: rgba(255, 200, 0, 0.5);\ - box-shadow: 0 0 4px rgb(255, 200, 0);\ -}\ -.ace_dark div.ace_isearch-result {\ - background-color: rgb(100, 110, 160);\ - box-shadow: 0 0 4px rgb(80, 90, 140);\ -}", "incremental-search-highlighting"); -var commands = acequire("./commands/command_manager"); -(function() { - this.setupIncrementalSearch = function(editor, val) { - if (this.usesIncrementalSearch == val) return; - this.usesIncrementalSearch = val; - var iSearchCommands = iSearchCommandModule.iSearchStartCommands; - var method = val ? 'addCommands' : 'removeCommands'; - this[method](iSearchCommands); - }; -}).call(commands.CommandManager.prototype); -var Editor = acequire("./editor").Editor; -acequire("./config").defineOptions(Editor.prototype, "editor", { - useIncrementalSearch: { - set: function(val) { - this.keyBinding.$handlers.forEach(function(handler) { - if (handler.setupIncrementalSearch) { - handler.setupIncrementalSearch(this, val); - } - }); - this._emit('incrementalSearchSettingChanged', {isEnabled: val}); - } - } -}); - -}); - -ace.define("ace/keyboard/emacs",["require","exports","module","ace/lib/dom","ace/incremental_search","ace/commands/incremental_search_commands","ace/keyboard/hash_handler","ace/lib/keys"], function(acequire, exports, module) { -"use strict"; - -var dom = acequire("../lib/dom"); -acequire("../incremental_search"); -var iSearchCommandModule = acequire("../commands/incremental_search_commands"); - - -var screenToTextBlockCoordinates = function(x, y) { - var canvasPos = this.scroller.getBoundingClientRect(); - - var col = Math.floor( - (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, col); -}; - -var HashHandler = acequire("./hash_handler").HashHandler; -exports.handler = new HashHandler(); - -exports.handler.isEmacs = true; -exports.handler.$id = "ace/keyboard/emacs"; - -var initialized = false; -var $formerLongWords; -var $formerLineStart; - -exports.handler.attach = function(editor) { - if (!initialized) { - initialized = true; - dom.importCssString('\ - .emacs-mode .ace_cursor{\ - border: 1px rgba(50,250,50,0.8) solid!important;\ - -moz-box-sizing: border-box!important;\ - -webkit-box-sizing: border-box!important;\ - box-sizing: border-box!important;\ - background-color: rgba(0,250,0,0.9);\ - opacity: 0.5;\ - }\ - .emacs-mode .ace_hidden-cursors .ace_cursor{\ - opacity: 1;\ - background-color: transparent;\ - }\ - .emacs-mode .ace_overwrite-cursors .ace_cursor {\ - opacity: 1;\ - background-color: transparent;\ - border-width: 0 0 2px 2px !important;\ - }\ - .emacs-mode .ace_text-layer {\ - z-index: 4\ - }\ - .emacs-mode .ace_cursor-layer {\ - z-index: 2\ - }', 'emacsMode' - ); - } - $formerLongWords = editor.session.$selectLongWords; - editor.session.$selectLongWords = true; - $formerLineStart = editor.session.$useEmacsStyleLineStart; - editor.session.$useEmacsStyleLineStart = true; - - editor.session.$emacsMark = null; // the active mark - editor.session.$emacsMarkRing = editor.session.$emacsMarkRing || []; - - editor.emacsMark = function() { - return this.session.$emacsMark; - }; - - editor.setEmacsMark = function(p) { - this.session.$emacsMark = p; - }; - - editor.pushEmacsMark = function(p, activate) { - var prevMark = this.session.$emacsMark; - if (prevMark) - this.session.$emacsMarkRing.push(prevMark); - if (!p || activate) this.setEmacsMark(p); - else this.session.$emacsMarkRing.push(p); - }; - - editor.popEmacsMark = function() { - var mark = this.emacsMark(); - if (mark) { this.setEmacsMark(null); return mark; } - return this.session.$emacsMarkRing.pop(); - }; - - editor.getLastEmacsMark = function(p) { - return this.session.$emacsMark || this.session.$emacsMarkRing.slice(-1)[0]; - }; - - editor.emacsMarkForSelection = function(replacement) { - var sel = this.selection, - multiRangeLength = this.multiSelect ? - this.multiSelect.getAllRanges().length : 1, - selIndex = sel.index || 0, - markRing = this.session.$emacsMarkRing, - markIndex = markRing.length - (multiRangeLength - selIndex), - lastMark = markRing[markIndex] || sel.anchor; - if (replacement) { - markRing.splice(markIndex, 1, - "row" in replacement && "column" in replacement ? - replacement : undefined); - } - return lastMark; - } - - editor.on("click", $resetMarkMode); - editor.on("changeSession", $kbSessionChange); - editor.renderer.screenToTextCoordinates = screenToTextBlockCoordinates; - editor.setStyle("emacs-mode"); - editor.commands.addCommands(commands); - exports.handler.platform = editor.commands.platform; - editor.$emacsModeHandler = this; - editor.addEventListener('copy', this.onCopy); - editor.addEventListener('paste', this.onPaste); -}; - -exports.handler.detach = function(editor) { - delete editor.renderer.screenToTextCoordinates; - editor.session.$selectLongWords = $formerLongWords; - editor.session.$useEmacsStyleLineStart = $formerLineStart; - editor.removeEventListener("click", $resetMarkMode); - editor.removeEventListener("changeSession", $kbSessionChange); - editor.unsetStyle("emacs-mode"); - editor.commands.removeCommands(commands); - editor.removeEventListener('copy', this.onCopy); - editor.removeEventListener('paste', this.onPaste); - editor.$emacsModeHandler = null; -}; - -var $kbSessionChange = function(e) { - if (e.oldSession) { - e.oldSession.$selectLongWords = $formerLongWords; - e.oldSession.$useEmacsStyleLineStart = $formerLineStart; - } - - $formerLongWords = e.session.$selectLongWords; - e.session.$selectLongWords = true; - $formerLineStart = e.session.$useEmacsStyleLineStart; - e.session.$useEmacsStyleLineStart = true; - - if (!e.session.hasOwnProperty('$emacsMark')) - e.session.$emacsMark = null; - if (!e.session.hasOwnProperty('$emacsMarkRing')) - e.session.$emacsMarkRing = []; -}; - -var $resetMarkMode = function(e) { - e.editor.session.$emacsMark = null; -}; - -var keys = acequire("../lib/keys").KEY_MODS; -var eMods = {C: "ctrl", S: "shift", M: "alt", CMD: "command"}; -var combinations = ["C-S-M-CMD", - "S-M-CMD", "C-M-CMD", "C-S-CMD", "C-S-M", - "M-CMD", "S-CMD", "S-M", "C-CMD", "C-M", "C-S", - "CMD", "M", "S", "C"]; -combinations.forEach(function(c) { - var hashId = 0; - c.split("-").forEach(function(c) { - hashId = hashId | keys[eMods[c]]; - }); - eMods[hashId] = c.toLowerCase() + "-"; -}); - -exports.handler.onCopy = function(e, editor) { - if (editor.$handlesEmacsOnCopy) return; - editor.$handlesEmacsOnCopy = true; - exports.handler.commands.killRingSave.exec(editor); - editor.$handlesEmacsOnCopy = false; -}; - -exports.handler.onPaste = function(e, editor) { - editor.pushEmacsMark(editor.getCursorPosition()); -}; - -exports.handler.bindKey = function(key, command) { - if (typeof key == "object") - key = key[this.platform]; - if (!key) - return; - - var ckb = this.commandKeyBinding; - key.split("|").forEach(function(keyPart) { - keyPart = keyPart.toLowerCase(); - ckb[keyPart] = command; - var keyParts = keyPart.split(" ").slice(0,-1); - keyParts.reduce(function(keyMapKeys, keyPart, i) { - var prefix = keyMapKeys[i-1] ? keyMapKeys[i-1] + ' ' : ''; - return keyMapKeys.concat([prefix + keyPart]); - }, []).forEach(function(keyPart) { - if (!ckb[keyPart]) ckb[keyPart] = "null"; - }); - }, this); -}; - -exports.handler.getStatusText = function(editor, data) { - var str = ""; - if (data.count) - str += data.count; - if (data.keyChain) - str += " " + data.keyChain - return str; -}; - -exports.handler.handleKeyboard = function(data, hashId, key, keyCode) { - if (keyCode === -1) return undefined; - - var editor = data.editor; - editor._signal("changeStatus"); - if (hashId == -1) { - editor.pushEmacsMark(); - if (data.count) { - var str = new Array(data.count + 1).join(key); - data.count = null; - return {command: "insertstring", args: str}; - } - } - - var modifier = eMods[hashId]; - if (modifier == "c-" || data.count) { - var count = parseInt(key[key.length - 1]); - if (typeof count === 'number' && !isNaN(count)) { - data.count = Math.max(data.count, 0) || 0; - data.count = 10 * data.count + count; - return {command: "null"}; - } - } - if (modifier) key = modifier + key; - if (data.keyChain) key = data.keyChain += " " + key; - var command = this.commandKeyBinding[key]; - data.keyChain = command == "null" ? key : ""; - if (!command) return undefined; - if (command === "null") return {command: "null"}; - - if (command === "universalArgument") { - data.count = -4; - return {command: "null"}; - } - var args; - if (typeof command !== "string") { - args = command.args; - if (command.command) command = command.command; - if (command === "goorselect") { - command = editor.emacsMark() ? args[1] : args[0]; - args = null; - } - } - - if (typeof command === "string") { - if (command === "insertstring" || - command === "splitline" || - command === "togglecomment") { - editor.pushEmacsMark(); - } - command = this.commands[command] || editor.commands.commands[command]; - if (!command) return undefined; - } - - if (!command.readOnly && !command.isYank) - data.lastCommand = null; - - if (!command.readOnly && editor.emacsMark()) - editor.setEmacsMark(null) - - if (data.count) { - var count = data.count; - data.count = 0; - if (!command || !command.handlesCount) { - return { - args: args, - command: { - exec: function(editor, args) { - for (var i = 0; i < count; i++) - command.exec(editor, args); - }, - multiSelectAction: command.multiSelectAction - } - }; - } else { - if (!args) args = {}; - if (typeof args === 'object') args.count = count; - } - } - - return {command: command, args: args}; -}; - -exports.emacsKeys = { - "Up|C-p" : {command: "goorselect", args: ["golineup","selectup"]}, - "Down|C-n" : {command: "goorselect", args: ["golinedown","selectdown"]}, - "Left|C-b" : {command: "goorselect", args: ["gotoleft","selectleft"]}, - "Right|C-f" : {command: "goorselect", args: ["gotoright","selectright"]}, - "C-Left|M-b" : {command: "goorselect", args: ["gotowordleft","selectwordleft"]}, - "C-Right|M-f" : {command: "goorselect", args: ["gotowordright","selectwordright"]}, - "Home|C-a" : {command: "goorselect", args: ["gotolinestart","selecttolinestart"]}, - "End|C-e" : {command: "goorselect", args: ["gotolineend","selecttolineend"]}, - "C-Home|S-M-,": {command: "goorselect", args: ["gotostart","selecttostart"]}, - "C-End|S-M-." : {command: "goorselect", args: ["gotoend","selecttoend"]}, - "S-Up|S-C-p" : "selectup", - "S-Down|S-C-n" : "selectdown", - "S-Left|S-C-b" : "selectleft", - "S-Right|S-C-f" : "selectright", - "S-C-Left|S-M-b" : "selectwordleft", - "S-C-Right|S-M-f" : "selectwordright", - "S-Home|S-C-a" : "selecttolinestart", - "S-End|S-C-e" : "selecttolineend", - "S-C-Home" : "selecttostart", - "S-C-End" : "selecttoend", - - "C-l" : "recenterTopBottom", - "M-s" : "centerselection", - "M-g": "gotoline", - "C-x C-p": "selectall", - "C-Down": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, - "C-Up": {command: "goorselect", args: ["gotopageup","selectpageup"]}, - "PageDown|C-v": {command: "goorselect", args: ["gotopagedown","selectpagedown"]}, - "PageUp|M-v": {command: "goorselect", args: ["gotopageup","selectpageup"]}, - "S-C-Down": "selectpagedown", - "S-C-Up": "selectpageup", - - "C-s": "iSearch", - "C-r": "iSearchBackwards", - - "M-C-s": "findnext", - "M-C-r": "findprevious", - "S-M-5": "replace", - "Backspace": "backspace", - "Delete|C-d": "del", - "Return|C-m": {command: "insertstring", args: "\n"}, // "newline" - "C-o": "splitline", - - "M-d|C-Delete": {command: "killWord", args: "right"}, - "C-Backspace|M-Backspace|M-Delete": {command: "killWord", args: "left"}, - "C-k": "killLine", - - "C-y|S-Delete": "yank", - "M-y": "yankRotate", - "C-g": "keyboardQuit", - - "C-w|C-S-W": "killRegion", - "M-w": "killRingSave", - "C-Space": "setMark", - "C-x C-x": "exchangePointAndMark", - - "C-t": "transposeletters", - "M-u": "touppercase", // Doesn't work - "M-l": "tolowercase", - "M-/": "autocomplete", // Doesn't work - "C-u": "universalArgument", - - "M-;": "togglecomment", - - "C-/|C-x u|S-C--|C-z": "undo", - "S-C-/|S-C-x u|C--|S-C-z": "redo", // infinite undo? - "C-x r": "selectRectangularRegion", - "M-x": {command: "focusCommandLine", args: "M-x "} -}; - - -exports.handler.bindKeys(exports.emacsKeys); - -exports.handler.addCommands({ - recenterTopBottom: function(editor) { - var renderer = editor.renderer; - var pos = renderer.$cursorLayer.getPixelPosition(); - var h = renderer.$size.scrollerHeight - renderer.lineHeight; - var scrollTop = renderer.scrollTop; - if (Math.abs(pos.top - scrollTop) < 2) { - scrollTop = pos.top - h; - } else if (Math.abs(pos.top - scrollTop - h * 0.5) < 2) { - scrollTop = pos.top; - } else { - scrollTop = pos.top - h * 0.5; - } - editor.session.setScrollTop(scrollTop); - }, - selectRectangularRegion: function(editor) { - editor.multiSelect.toggleBlockSelection(); - }, - setMark: { - exec: function(editor, args) { - - if (args && args.count) { - if (editor.inMultiSelectMode) editor.forEachSelection(moveToMark); - else moveToMark(); - moveToMark(); - return; - } - - var mark = editor.emacsMark(), - ranges = editor.selection.getAllRanges(), - rangePositions = ranges.map(function(r) { return {row: r.start.row, column: r.start.column}; }), - transientMarkModeActive = true, - hasNoSelection = ranges.every(function(range) { return range.isEmpty(); }); - if (transientMarkModeActive && (mark || !hasNoSelection)) { - if (editor.inMultiSelectMode) editor.forEachSelection({exec: editor.clearSelection.bind(editor)}); - else editor.clearSelection(); - if (mark) editor.pushEmacsMark(null); - return; - } - - if (!mark) { - rangePositions.forEach(function(pos) { editor.pushEmacsMark(pos); }); - editor.setEmacsMark(rangePositions[rangePositions.length-1]); - return; - } - - function moveToMark() { - var mark = editor.popEmacsMark(); - mark && editor.moveCursorToPosition(mark); - } - - }, - readOnly: true, - handlesCount: true - }, - exchangePointAndMark: { - exec: function exchangePointAndMark$exec(editor, args) { - var sel = editor.selection; - if (!args.count && !sel.isEmpty()) { // just invert selection - sel.setSelectionRange(sel.getRange(), !sel.isBackwards()); - return; - } - - if (args.count) { // replace mark and point - var pos = {row: sel.lead.row, column: sel.lead.column}; - sel.clearSelection(); - sel.moveCursorToPosition(editor.emacsMarkForSelection(pos)); - } else { // create selection to last mark - sel.selectToPosition(editor.emacsMarkForSelection()); - } - }, - readOnly: true, - handlesCount: true, - multiSelectAction: "forEach" - }, - killWord: { - exec: function(editor, dir) { - editor.clearSelection(); - if (dir == "left") - editor.selection.selectWordLeft(); - else - editor.selection.selectWordRight(); - - var range = editor.getSelectionRange(); - var text = editor.session.getTextRange(range); - exports.killRing.add(text); - - editor.session.remove(range); - editor.clearSelection(); - }, - multiSelectAction: "forEach" - }, - killLine: function(editor) { - editor.pushEmacsMark(null); - editor.clearSelection(); - var range = editor.getSelectionRange(); - var line = editor.session.getLine(range.start.row); - range.end.column = line.length; - line = line.substr(range.start.column) - - var foldLine = editor.session.getFoldLine(range.start.row); - if (foldLine && range.end.row != foldLine.end.row) { - range.end.row = foldLine.end.row; - line = "x"; - } - if (/^\s*$/.test(line)) { - range.end.row++; - line = editor.session.getLine(range.end.row); - range.end.column = /^\s*$/.test(line) ? line.length : 0; - } - var text = editor.session.getTextRange(range); - if (editor.prevOp.command == this) - exports.killRing.append(text); - else - exports.killRing.add(text); - - editor.session.remove(range); - editor.clearSelection(); - }, - yank: function(editor) { - editor.onPaste(exports.killRing.get() || ''); - editor.keyBinding.$data.lastCommand = "yank"; - }, - yankRotate: function(editor) { - if (editor.keyBinding.$data.lastCommand != "yank") - return; - editor.undo(); - editor.session.$emacsMarkRing.pop(); // also undo recording mark - editor.onPaste(exports.killRing.rotate()); - editor.keyBinding.$data.lastCommand = "yank"; - }, - killRegion: { - exec: function(editor) { - exports.killRing.add(editor.getCopyText()); - editor.commands.byName.cut.exec(editor); - editor.setEmacsMark(null); - }, - readOnly: true, - multiSelectAction: "forEach" - }, - killRingSave: { - exec: function(editor) { - - editor.$handlesEmacsOnCopy = true; - var marks = editor.session.$emacsMarkRing.slice(), - deselectedMarks = []; - exports.killRing.add(editor.getCopyText()); - - setTimeout(function() { - function deselect() { - var sel = editor.selection, range = sel.getRange(), - pos = sel.isBackwards() ? range.end : range.start; - deselectedMarks.push({row: pos.row, column: pos.column}); - sel.clearSelection(); - } - editor.$handlesEmacsOnCopy = false; - if (editor.inMultiSelectMode) editor.forEachSelection({exec: deselect}); - else deselect(); - editor.session.$emacsMarkRing = marks.concat(deselectedMarks.reverse()); - }, 0); - }, - readOnly: true - }, - keyboardQuit: function(editor) { - editor.selection.clearSelection(); - editor.setEmacsMark(null); - editor.keyBinding.$data.count = null; - }, - focusCommandLine: function(editor, arg) { - if (editor.showCommandLine) - editor.showCommandLine(arg); - } -}); - -exports.handler.addCommands(iSearchCommandModule.iSearchStartCommands); - -var commands = exports.handler.commands; -commands.yank.isYank = true; -commands.yankRotate.isYank = true; - -exports.killRing = { - $data: [], - add: function(str) { - str && this.$data.push(str); - if (this.$data.length > 30) - this.$data.shift(); - }, - append: function(str) { - var idx = this.$data.length - 1; - var text = this.$data[idx] || ""; - if (str) text += str; - if (text) this.$data[idx] = text; - }, - get: function(n) { - n = n || 1; - return this.$data.slice(this.$data.length-n, this.$data.length).reverse().join('\n'); - }, - pop: function() { - if (this.$data.length > 1) - this.$data.pop(); - return this.get(); - }, - rotate: function() { - this.$data.unshift(this.$data.pop()); - return this.get(); - } -}; - -}); - - -/***/ }), -/* 69 */ -/***/ (function(module, exports) { - -ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"], function(acequire, exports, module) { -"use strict"; -var oop = acequire("./lib/oop"); -var EventEmitter = acequire("./lib/event_emitter").EventEmitter; -var lang = acequire("./lib/lang"); -var Range = acequire("./range").Range; -var Anchor = acequire("./anchor").Anchor; -var HashHandler = acequire("./keyboard/hash_handler").HashHandler; -var Tokenizer = acequire("./tokenizer").Tokenizer; -var comparePoints = Range.comparePoints; - -var SnippetManager = function() { - this.snippetMap = {}; - this.snippetNameMap = {}; -}; - -(function() { - oop.implement(this, EventEmitter); - - this.getTokenizer = function() { - function TabstopToken(str, _, stack) { - str = str.substr(1); - if (/^\d+$/.test(str) && !stack.inFormatString) - return [{tabstopId: parseInt(str, 10)}]; - return [{text: str}]; - } - function escape(ch) { - return "(?:[^\\\\" + ch + "]|\\\\.)"; - } - SnippetManager.$tokenizer = new Tokenizer({ - start: [ - {regex: /:/, onMatch: function(val, state, stack) { - if (stack.length && stack[0].expectIf) { - stack[0].expectIf = false; - stack[0].elseBranch = stack[0]; - return [stack[0]]; - } - return ":"; - }}, - {regex: /\\./, onMatch: function(val, state, stack) { - var ch = val[1]; - if (ch == "}" && stack.length) { - val = ch; - }else if ("`$\\".indexOf(ch) != -1) { - val = ch; - } else if (stack.inFormatString) { - if (ch == "n") - val = "\n"; - else if (ch == "t") - val = "\n"; - else if ("ulULE".indexOf(ch) != -1) { - val = {changeCase: ch, local: ch > "a"}; - } - } - - return [val]; - }}, - {regex: /}/, onMatch: function(val, state, stack) { - return [stack.length ? stack.shift() : val]; - }}, - {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken}, - {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) { - var t = TabstopToken(str.substr(1), state, stack); - stack.unshift(t[0]); - return t; - }, next: "snippetVar"}, - {regex: /\n/, token: "newline", merge: false} - ], - snippetVar: [ - {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) { - stack[0].choices = val.slice(1, -1).split(","); - }, next: "start"}, - {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?", - onMatch: function(val, state, stack) { - var ts = stack[0]; - ts.fmtString = val; - - val = this.splitRegex.exec(val); - ts.guard = val[1]; - ts.fmt = val[2]; - ts.flag = val[3]; - return ""; - }, next: "start"}, - {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) { - stack[0].code = val.splice(1, -1); - return ""; - }, next: "start"}, - {regex: "\\?", onMatch: function(val, state, stack) { - if (stack[0]) - stack[0].expectIf = true; - }, next: "start"}, - {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"} - ], - formatString: [ - {regex: "/(" + escape("/") + "+)/", token: "regex"}, - {regex: "", onMatch: function(val, state, stack) { - stack.inFormatString = true; - }, next: "start"} - ] - }); - SnippetManager.prototype.getTokenizer = function() { - return SnippetManager.$tokenizer; - }; - return SnippetManager.$tokenizer; - }; - - this.tokenizeTmSnippet = function(str, startState) { - return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) { - return x.value || x; - }); - }; - - this.$getDefaultValue = function(editor, name) { - if (/^[A-Z]\d+$/.test(name)) { - var i = name.substr(1); - return (this.variables[name[0] + "__"] || {})[i]; - } - if (/^\d+$/.test(name)) { - return (this.variables.__ || {})[name]; - } - name = name.replace(/^TM_/, ""); - - if (!editor) - return; - var s = editor.session; - switch(name) { - case "CURRENT_WORD": - var r = s.getWordRange(); - case "SELECTION": - case "SELECTED_TEXT": - return s.getTextRange(r); - case "CURRENT_LINE": - return s.getLine(editor.getCursorPosition().row); - case "PREV_LINE": // not possible in textmate - return s.getLine(editor.getCursorPosition().row - 1); - case "LINE_INDEX": - return editor.getCursorPosition().column; - case "LINE_NUMBER": - return editor.getCursorPosition().row + 1; - case "SOFT_TABS": - return s.getUseSoftTabs() ? "YES" : "NO"; - case "TAB_SIZE": - return s.getTabSize(); - case "FILENAME": - case "FILEPATH": - return ""; - case "FULLNAME": - return "Ace"; - } - }; - this.variables = {}; - this.getVariableValue = function(editor, varName) { - if (this.variables.hasOwnProperty(varName)) - return this.variables[varName](editor, varName) || ""; - return this.$getDefaultValue(editor, varName) || ""; - }; - this.tmStrFormat = function(str, ch, editor) { - var flag = ch.flag || ""; - var re = ch.guard; - re = new RegExp(re, flag.replace(/[^gi]/, "")); - var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString"); - var _self = this; - var formatted = str.replace(re, function() { - _self.variables.__ = arguments; - var fmtParts = _self.resolveVariables(fmtTokens, editor); - var gChangeCase = "E"; - for (var i = 0; i < fmtParts.length; i++) { - var ch = fmtParts[i]; - if (typeof ch == "object") { - fmtParts[i] = ""; - if (ch.changeCase && ch.local) { - var next = fmtParts[i + 1]; - if (next && typeof next == "string") { - if (ch.changeCase == "u") - fmtParts[i] = next[0].toUpperCase(); - else - fmtParts[i] = next[0].toLowerCase(); - fmtParts[i + 1] = next.substr(1); - } - } else if (ch.changeCase) { - gChangeCase = ch.changeCase; - } - } else if (gChangeCase == "U") { - fmtParts[i] = ch.toUpperCase(); - } else if (gChangeCase == "L") { - fmtParts[i] = ch.toLowerCase(); - } - } - return fmtParts.join(""); - }); - this.variables.__ = null; - return formatted; - }; - - this.resolveVariables = function(snippet, editor) { - var result = []; - for (var i = 0; i < snippet.length; i++) { - var ch = snippet[i]; - if (typeof ch == "string") { - result.push(ch); - } else if (typeof ch != "object") { - continue; - } else if (ch.skip) { - gotoNext(ch); - } else if (ch.processed < i) { - continue; - } else if (ch.text) { - var value = this.getVariableValue(editor, ch.text); - if (value && ch.fmtString) - value = this.tmStrFormat(value, ch); - ch.processed = i; - if (ch.expectIf == null) { - if (value) { - result.push(value); - gotoNext(ch); - } - } else { - if (value) { - ch.skip = ch.elseBranch; - } else - gotoNext(ch); - } - } else if (ch.tabstopId != null) { - result.push(ch); - } else if (ch.changeCase != null) { - result.push(ch); - } - } - function gotoNext(ch) { - var i1 = snippet.indexOf(ch, i + 1); - if (i1 != -1) - i = i1; - } - return result; - }; - - this.insertSnippetForSelection = function(editor, snippetText) { - var cursor = editor.getCursorPosition(); - var line = editor.session.getLine(cursor.row); - var tabString = editor.session.getTabString(); - var indentString = line.match(/^\s*/)[0]; - - if (cursor.column < indentString.length) - indentString = indentString.slice(0, cursor.column); - - snippetText = snippetText.replace(/\r/g, ""); - var tokens = this.tokenizeTmSnippet(snippetText); - tokens = this.resolveVariables(tokens, editor); - tokens = tokens.map(function(x) { - if (x == "\n") - return x + indentString; - if (typeof x == "string") - return x.replace(/\t/g, tabString); - return x; - }); - var tabstops = []; - tokens.forEach(function(p, i) { - if (typeof p != "object") - return; - var id = p.tabstopId; - var ts = tabstops[id]; - if (!ts) { - ts = tabstops[id] = []; - ts.index = id; - ts.value = ""; - } - if (ts.indexOf(p) !== -1) - return; - ts.push(p); - var i1 = tokens.indexOf(p, i + 1); - if (i1 === -1) - return; - - var value = tokens.slice(i + 1, i1); - var isNested = value.some(function(t) {return typeof t === "object"}); - if (isNested && !ts.value) { - ts.value = value; - } else if (value.length && (!ts.value || typeof ts.value !== "string")) { - ts.value = value.join(""); - } - }); - tabstops.forEach(function(ts) {ts.length = 0}); - var expanding = {}; - function copyValue(val) { - var copy = []; - for (var i = 0; i < val.length; i++) { - var p = val[i]; - if (typeof p == "object") { - if (expanding[p.tabstopId]) - continue; - var j = val.lastIndexOf(p, i - 1); - p = copy[j] || {tabstopId: p.tabstopId}; - } - copy[i] = p; - } - return copy; - } - for (var i = 0; i < tokens.length; i++) { - var p = tokens[i]; - if (typeof p != "object") - continue; - var id = p.tabstopId; - var i1 = tokens.indexOf(p, i + 1); - if (expanding[id]) { - if (expanding[id] === p) - expanding[id] = null; - continue; - } - - var ts = tabstops[id]; - var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value); - arg.unshift(i + 1, Math.max(0, i1 - i)); - arg.push(p); - expanding[id] = p; - tokens.splice.apply(tokens, arg); - - if (ts.indexOf(p) === -1) - ts.push(p); - } - var row = 0, column = 0; - var text = ""; - tokens.forEach(function(t) { - if (typeof t === "string") { - var lines = t.split("\n"); - if (lines.length > 1){ - column = lines[lines.length - 1].length; - row += lines.length - 1; - } else - column += t.length; - text += t; - } else { - if (!t.start) - t.start = {row: row, column: column}; - else - t.end = {row: row, column: column}; - } - }); - var range = editor.getSelectionRange(); - var end = editor.session.replace(range, text); - - var tabstopManager = new TabstopManager(editor); - var selectionId = editor.inVirtualSelectionMode && editor.selection.index; - tabstopManager.addTabstops(tabstops, range.start, end, selectionId); - }; - - this.insertSnippet = function(editor, snippetText) { - var self = this; - if (editor.inVirtualSelectionMode) - return self.insertSnippetForSelection(editor, snippetText); - - editor.forEachSelection(function() { - self.insertSnippetForSelection(editor, snippetText); - }, null, {keepOrder: true}); - - if (editor.tabstopManager) - editor.tabstopManager.tabNext(); - }; - - this.$getScope = function(editor) { - var scope = editor.session.$mode.$id || ""; - scope = scope.split("/").pop(); - if (scope === "html" || scope === "php") { - if (scope === "php" && !editor.session.$mode.inlinePhp) - scope = "html"; - var c = editor.getCursorPosition(); - var state = editor.session.getState(c.row); - if (typeof state === "object") { - state = state[0]; - } - if (state.substring) { - if (state.substring(0, 3) == "js-") - scope = "javascript"; - else if (state.substring(0, 4) == "css-") - scope = "css"; - else if (state.substring(0, 4) == "php-") - scope = "php"; - } - } - - return scope; - }; - - this.getActiveScopes = function(editor) { - var scope = this.$getScope(editor); - var scopes = [scope]; - var snippetMap = this.snippetMap; - if (snippetMap[scope] && snippetMap[scope].includeScopes) { - scopes.push.apply(scopes, snippetMap[scope].includeScopes); - } - scopes.push("_"); - return scopes; - }; - - this.expandWithTab = function(editor, options) { - var self = this; - var result = editor.forEachSelection(function() { - return self.expandSnippetForSelection(editor, options); - }, null, {keepOrder: true}); - if (result && editor.tabstopManager) - editor.tabstopManager.tabNext(); - return result; - }; - - this.expandSnippetForSelection = function(editor, options) { - var cursor = editor.getCursorPosition(); - var line = editor.session.getLine(cursor.row); - var before = line.substring(0, cursor.column); - var after = line.substr(cursor.column); - - var snippetMap = this.snippetMap; - var snippet; - this.getActiveScopes(editor).some(function(scope) { - var snippets = snippetMap[scope]; - if (snippets) - snippet = this.findMatchingSnippet(snippets, before, after); - return !!snippet; - }, this); - if (!snippet) - return false; - if (options && options.dryRun) - return true; - editor.session.doc.removeInLine(cursor.row, - cursor.column - snippet.replaceBefore.length, - cursor.column + snippet.replaceAfter.length - ); - - this.variables.M__ = snippet.matchBefore; - this.variables.T__ = snippet.matchAfter; - this.insertSnippetForSelection(editor, snippet.content); - - this.variables.M__ = this.variables.T__ = null; - return true; - }; - - this.findMatchingSnippet = function(snippetList, before, after) { - for (var i = snippetList.length; i--;) { - var s = snippetList[i]; - if (s.startRe && !s.startRe.test(before)) - continue; - if (s.endRe && !s.endRe.test(after)) - continue; - if (!s.startRe && !s.endRe) - continue; - - s.matchBefore = s.startRe ? s.startRe.exec(before) : [""]; - s.matchAfter = s.endRe ? s.endRe.exec(after) : [""]; - s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : ""; - s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : ""; - return s; - } - }; - - this.snippetMap = {}; - this.snippetNameMap = {}; - this.register = function(snippets, scope) { - var snippetMap = this.snippetMap; - var snippetNameMap = this.snippetNameMap; - var self = this; - - if (!snippets) - snippets = []; - - function wrapRegexp(src) { - if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src)) - src = "(?:" + src + ")"; - - return src || ""; - } - function guardedRegexp(re, guard, opening) { - re = wrapRegexp(re); - guard = wrapRegexp(guard); - if (opening) { - re = guard + re; - if (re && re[re.length - 1] != "$") - re = re + "$"; - } else { - re = re + guard; - if (re && re[0] != "^") - re = "^" + re; - } - return new RegExp(re); - } - - function addSnippet(s) { - if (!s.scope) - s.scope = scope || "_"; - scope = s.scope; - if (!snippetMap[scope]) { - snippetMap[scope] = []; - snippetNameMap[scope] = {}; - } - - var map = snippetNameMap[scope]; - if (s.name) { - var old = map[s.name]; - if (old) - self.unregister(old); - map[s.name] = s; - } - snippetMap[scope].push(s); - - if (s.tabTrigger && !s.trigger) { - if (!s.guard && /^\w/.test(s.tabTrigger)) - s.guard = "\\b"; - s.trigger = lang.escapeRegExp(s.tabTrigger); - } - - if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard) - return; - - s.startRe = guardedRegexp(s.trigger, s.guard, true); - s.triggerRe = new RegExp(s.trigger, "", true); - - s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true); - s.endTriggerRe = new RegExp(s.endTrigger, "", true); - } - - if (snippets && snippets.content) - addSnippet(snippets); - else if (Array.isArray(snippets)) - snippets.forEach(addSnippet); - - this._signal("registerSnippets", {scope: scope}); - }; - this.unregister = function(snippets, scope) { - var snippetMap = this.snippetMap; - var snippetNameMap = this.snippetNameMap; - - function removeSnippet(s) { - var nameMap = snippetNameMap[s.scope||scope]; - if (nameMap && nameMap[s.name]) { - delete nameMap[s.name]; - var map = snippetMap[s.scope||scope]; - var i = map && map.indexOf(s); - if (i >= 0) - map.splice(i, 1); - } - } - if (snippets.content) - removeSnippet(snippets); - else if (Array.isArray(snippets)) - snippets.forEach(removeSnippet); - }; - this.parseSnippetFile = function(str) { - str = str.replace(/\r/g, ""); - var list = [], snippet = {}; - var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm; - var m; - while (m = re.exec(str)) { - if (m[1]) { - try { - snippet = JSON.parse(m[1]); - list.push(snippet); - } catch (e) {} - } if (m[4]) { - snippet.content = m[4].replace(/^\t/gm, ""); - list.push(snippet); - snippet = {}; - } else { - var key = m[2], val = m[3]; - if (key == "regex") { - var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g; - snippet.guard = guardRe.exec(val)[1]; - snippet.trigger = guardRe.exec(val)[1]; - snippet.endTrigger = guardRe.exec(val)[1]; - snippet.endGuard = guardRe.exec(val)[1]; - } else if (key == "snippet") { - snippet.tabTrigger = val.match(/^\S*/)[0]; - if (!snippet.name) - snippet.name = val; - } else { - snippet[key] = val; - } - } - } - return list; - }; - this.getSnippetByName = function(name, editor) { - var snippetMap = this.snippetNameMap; - var snippet; - this.getActiveScopes(editor).some(function(scope) { - var snippets = snippetMap[scope]; - if (snippets) - snippet = snippets[name]; - return !!snippet; - }, this); - return snippet; - }; - -}).call(SnippetManager.prototype); - - -var TabstopManager = function(editor) { - if (editor.tabstopManager) - return editor.tabstopManager; - editor.tabstopManager = this; - this.$onChange = this.onChange.bind(this); - this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule; - this.$onChangeSession = this.onChangeSession.bind(this); - this.$onAfterExec = this.onAfterExec.bind(this); - this.attach(editor); -}; -(function() { - this.attach = function(editor) { - this.index = 0; - this.ranges = []; - this.tabstops = []; - this.$openTabstops = null; - this.selectedTabstop = null; - - this.editor = editor; - this.editor.on("change", this.$onChange); - this.editor.on("changeSelection", this.$onChangeSelection); - this.editor.on("changeSession", this.$onChangeSession); - this.editor.commands.on("afterExec", this.$onAfterExec); - this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - }; - this.detach = function() { - this.tabstops.forEach(this.removeTabstopMarkers, this); - this.ranges = null; - this.tabstops = null; - this.selectedTabstop = null; - this.editor.removeListener("change", this.$onChange); - this.editor.removeListener("changeSelection", this.$onChangeSelection); - this.editor.removeListener("changeSession", this.$onChangeSession); - this.editor.commands.removeListener("afterExec", this.$onAfterExec); - this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); - this.editor.tabstopManager = null; - this.editor = null; - }; - - this.onChange = function(delta) { - var changeRange = delta; - var isRemove = delta.action[0] == "r"; - var start = delta.start; - var end = delta.end; - var startRow = start.row; - var endRow = end.row; - var lineDif = endRow - startRow; - var colDiff = end.column - start.column; - - if (isRemove) { - lineDif = -lineDif; - colDiff = -colDiff; - } - if (!this.$inChange && isRemove) { - var ts = this.selectedTabstop; - var changedOutside = ts && !ts.some(function(r) { - return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0; - }); - if (changedOutside) - return this.detach(); - } - var ranges = this.ranges; - for (var i = 0; i < ranges.length; i++) { - var r = ranges[i]; - if (r.end.row < start.row) - continue; - - if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) { - this.removeRange(r); - i--; - continue; - } - - if (r.start.row == startRow && r.start.column > start.column) - r.start.column += colDiff; - if (r.end.row == startRow && r.end.column >= start.column) - r.end.column += colDiff; - if (r.start.row >= startRow) - r.start.row += lineDif; - if (r.end.row >= startRow) - r.end.row += lineDif; - - if (comparePoints(r.start, r.end) > 0) - this.removeRange(r); - } - if (!ranges.length) - this.detach(); - }; - this.updateLinkedFields = function() { - var ts = this.selectedTabstop; - if (!ts || !ts.hasLinkedRanges) - return; - this.$inChange = true; - var session = this.editor.session; - var text = session.getTextRange(ts.firstNonLinked); - for (var i = ts.length; i--;) { - var range = ts[i]; - if (!range.linked) - continue; - var fmt = exports.snippetManager.tmStrFormat(text, range.original); - session.replace(range, fmt); - } - this.$inChange = false; - }; - this.onAfterExec = function(e) { - if (e.command && !e.command.readOnly) - this.updateLinkedFields(); - }; - this.onChangeSelection = function() { - if (!this.editor) - return; - var lead = this.editor.selection.lead; - var anchor = this.editor.selection.anchor; - var isEmpty = this.editor.selection.isEmpty(); - for (var i = this.ranges.length; i--;) { - if (this.ranges[i].linked) - continue; - var containsLead = this.ranges[i].contains(lead.row, lead.column); - var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column); - if (containsLead && containsAnchor) - return; - } - this.detach(); - }; - this.onChangeSession = function() { - this.detach(); - }; - this.tabNext = function(dir) { - var max = this.tabstops.length; - var index = this.index + (dir || 1); - index = Math.min(Math.max(index, 1), max); - if (index == max) - index = 0; - this.selectTabstop(index); - if (index === 0) - this.detach(); - }; - this.selectTabstop = function(index) { - this.$openTabstops = null; - var ts = this.tabstops[this.index]; - if (ts) - this.addTabstopMarkers(ts); - this.index = index; - ts = this.tabstops[this.index]; - if (!ts || !ts.length) - return; - - this.selectedTabstop = ts; - if (!this.editor.inVirtualSelectionMode) { - var sel = this.editor.multiSelect; - sel.toSingleRange(ts.firstNonLinked.clone()); - for (var i = ts.length; i--;) { - if (ts.hasLinkedRanges && ts[i].linked) - continue; - sel.addRange(ts[i].clone(), true); - } - if (sel.ranges[0]) - sel.addRange(sel.ranges[0].clone()); - } else { - this.editor.selection.setRange(ts.firstNonLinked); - } - - this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - }; - this.addTabstops = function(tabstops, start, end) { - if (!this.$openTabstops) - this.$openTabstops = []; - if (!tabstops[0]) { - var p = Range.fromPoints(end, end); - moveRelative(p.start, start); - moveRelative(p.end, start); - tabstops[0] = [p]; - tabstops[0].index = 0; - } - - var i = this.index; - var arg = [i + 1, 0]; - var ranges = this.ranges; - tabstops.forEach(function(ts, index) { - var dest = this.$openTabstops[index] || ts; - - for (var i = ts.length; i--;) { - var p = ts[i]; - var range = Range.fromPoints(p.start, p.end || p.start); - movePoint(range.start, start); - movePoint(range.end, start); - range.original = p; - range.tabstop = dest; - ranges.push(range); - if (dest != ts) - dest.unshift(range); - else - dest[i] = range; - if (p.fmtString) { - range.linked = true; - dest.hasLinkedRanges = true; - } else if (!dest.firstNonLinked) - dest.firstNonLinked = range; - } - if (!dest.firstNonLinked) - dest.hasLinkedRanges = false; - if (dest === ts) { - arg.push(dest); - this.$openTabstops[index] = dest; - } - this.addTabstopMarkers(dest); - }, this); - - if (arg.length > 2) { - if (this.tabstops.length) - arg.push(arg.splice(2, 1)[0]); - this.tabstops.splice.apply(this.tabstops, arg); - } - }; - - this.addTabstopMarkers = function(ts) { - var session = this.editor.session; - ts.forEach(function(range) { - if (!range.markerId) - range.markerId = session.addMarker(range, "ace_snippet-marker", "text"); - }); - }; - this.removeTabstopMarkers = function(ts) { - var session = this.editor.session; - ts.forEach(function(range) { - session.removeMarker(range.markerId); - range.markerId = null; - }); - }; - this.removeRange = function(range) { - var i = range.tabstop.indexOf(range); - range.tabstop.splice(i, 1); - i = this.ranges.indexOf(range); - this.ranges.splice(i, 1); - this.editor.session.removeMarker(range.markerId); - if (!range.tabstop.length) { - i = this.tabstops.indexOf(range.tabstop); - if (i != -1) - this.tabstops.splice(i, 1); - if (!this.tabstops.length) - this.detach(); - } - }; - - this.keyboardHandler = new HashHandler(); - this.keyboardHandler.bindKeys({ - "Tab": function(ed) { - if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) { - return; - } - - ed.tabstopManager.tabNext(1); - }, - "Shift-Tab": function(ed) { - ed.tabstopManager.tabNext(-1); - }, - "Esc": function(ed) { - ed.tabstopManager.detach(); - }, - "Return": function(ed) { - return false; - } - }); -}).call(TabstopManager.prototype); - - - -var changeTracker = {}; -changeTracker.onChange = Anchor.prototype.onChange; -changeTracker.setPosition = function(row, column) { - this.pos.row = row; - this.pos.column = column; -}; -changeTracker.update = function(pos, delta, $insertRight) { - this.$insertRight = $insertRight; - this.pos = pos; - this.onChange(delta); -}; - -var movePoint = function(point, diff) { - if (point.row == 0) - point.column += diff.column; - point.row += diff.row; -}; - -var moveRelative = function(point, start) { - if (point.row == start.row) - point.column -= start.column; - point.row -= start.row; -}; - - -acequire("./lib/dom").importCssString("\ -.ace_snippet-marker {\ - -moz-box-sizing: border-box;\ - box-sizing: border-box;\ - background: rgba(194, 193, 208, 0.09);\ - border: 1px dotted rgba(211, 208, 235, 0.62);\ - position: absolute;\ -}"); - -exports.snippetManager = new SnippetManager(); - - -var Editor = acequire("./editor").Editor; -(function() { - this.insertSnippet = function(content, options) { - return exports.snippetManager.insertSnippet(this, content, options); - }; - this.expandSnippet = function(options) { - return exports.snippetManager.expandWithTab(this, options); - }; -}).call(Editor.prototype); - -}); - -ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(acequire, exports, module) { -"use strict"; - -var Renderer = acequire("../virtual_renderer").VirtualRenderer; -var Editor = acequire("../editor").Editor; -var Range = acequire("../range").Range; -var event = acequire("../lib/event"); -var lang = acequire("../lib/lang"); -var dom = acequire("../lib/dom"); - -var $singleLineEditor = function(el) { - var renderer = new Renderer(el); - - renderer.$maxLines = 4; - - var editor = new Editor(renderer); - - editor.setHighlightActiveLine(false); - editor.setShowPrintMargin(false); - editor.renderer.setShowGutter(false); - editor.renderer.setHighlightGutterLine(false); - - editor.$mouseHandler.$focusWaitTimout = 0; - editor.$highlightTagPending = true; - - return editor; -}; - -var AcePopup = function(parentNode) { - var el = dom.createElement("div"); - var popup = new $singleLineEditor(el); - - if (parentNode) - parentNode.appendChild(el); - el.style.display = "none"; - popup.renderer.content.style.cursor = "default"; - popup.renderer.setStyle("ace_autocomplete"); - - popup.setOption("displayIndentGuides", false); - popup.setOption("dragDelay", 150); - - var noop = function(){}; - - popup.focus = noop; - popup.$isFocused = true; - - popup.renderer.$cursorLayer.restartTimer = noop; - popup.renderer.$cursorLayer.element.style.opacity = 0; - - popup.renderer.$maxLines = 8; - popup.renderer.$keepTextAreaAtCursor = false; - - popup.setHighlightActiveLine(false); - popup.session.highlight(""); - popup.session.$searchHighlight.clazz = "ace_highlight-marker"; - - popup.on("mousedown", function(e) { - var pos = e.getDocumentPosition(); - popup.selection.moveToPosition(pos); - selectionMarker.start.row = selectionMarker.end.row = pos.row; - e.stop(); - }); - - var lastMouseEvent; - var hoverMarker = new Range(-1,0,-1,Infinity); - var selectionMarker = new Range(-1,0,-1,Infinity); - selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine"); - popup.setSelectOnHover = function(val) { - if (!val) { - hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine"); - } else if (hoverMarker.id) { - popup.session.removeMarker(hoverMarker.id); - hoverMarker.id = null; - } - }; - popup.setSelectOnHover(false); - popup.on("mousemove", function(e) { - if (!lastMouseEvent) { - lastMouseEvent = e; - return; - } - if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) { - return; - } - lastMouseEvent = e; - lastMouseEvent.scrollTop = popup.renderer.scrollTop; - var row = lastMouseEvent.getDocumentPosition().row; - if (hoverMarker.start.row != row) { - if (!hoverMarker.id) - popup.setRow(row); - setHoverMarker(row); - } - }); - popup.renderer.on("beforeRender", function() { - if (lastMouseEvent && hoverMarker.start.row != -1) { - lastMouseEvent.$pos = null; - var row = lastMouseEvent.getDocumentPosition().row; - if (!hoverMarker.id) - popup.setRow(row); - setHoverMarker(row, true); - } - }); - popup.renderer.on("afterRender", function() { - var row = popup.getRow(); - var t = popup.renderer.$textLayer; - var selected = t.element.childNodes[row - t.config.firstRow]; - if (selected == t.selectedNode) - return; - if (t.selectedNode) - dom.removeCssClass(t.selectedNode, "ace_selected"); - t.selectedNode = selected; - if (selected) - dom.addCssClass(selected, "ace_selected"); - }); - var hideHoverMarker = function() { setHoverMarker(-1) }; - var setHoverMarker = function(row, suppressRedraw) { - if (row !== hoverMarker.start.row) { - hoverMarker.start.row = hoverMarker.end.row = row; - if (!suppressRedraw) - popup.session._emit("changeBackMarker"); - popup._emit("changeHoverMarker"); - } - }; - popup.getHoveredRow = function() { - return hoverMarker.start.row; - }; - - event.addListener(popup.container, "mouseout", hideHoverMarker); - popup.on("hide", hideHoverMarker); - popup.on("changeSelection", hideHoverMarker); - - popup.session.doc.getLength = function() { - return popup.data.length; - }; - popup.session.doc.getLine = function(i) { - var data = popup.data[i]; - if (typeof data == "string") - return data; - return (data && data.value) || ""; - }; - - var bgTokenizer = popup.session.bgTokenizer; - bgTokenizer.$tokenizeRow = function(row) { - var data = popup.data[row]; - var tokens = []; - if (!data) - return tokens; - if (typeof data == "string") - data = {value: data}; - if (!data.caption) - data.caption = data.value || data.name; - - var last = -1; - var flag, c; - for (var i = 0; i < data.caption.length; i++) { - c = data.caption[i]; - flag = data.matchMask & (1 << i) ? 1 : 0; - if (last !== flag) { - tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c}); - last = flag; - } else { - tokens[tokens.length - 1].value += c; - } - } - - if (data.meta) { - var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth; - var metaData = data.meta; - if (metaData.length + data.caption.length > maxW - 2) { - metaData = metaData.substr(0, maxW - data.caption.length - 3) + "\u2026" - } - tokens.push({type: "rightAlignedText", value: metaData}); - } - return tokens; - }; - bgTokenizer.$updateOnChange = noop; - bgTokenizer.start = noop; - - popup.session.$computeWidth = function() { - return this.screenWidth = 0; - }; - - popup.$blockScrolling = Infinity; - popup.isOpen = false; - popup.isTopdown = false; - - popup.data = []; - popup.setData = function(list) { - popup.setValue(lang.stringRepeat("\n", list.length), -1); - popup.data = list || []; - popup.setRow(0); - }; - popup.getData = function(row) { - return popup.data[row]; - }; - - popup.getRow = function() { - return selectionMarker.start.row; - }; - popup.setRow = function(line) { - line = Math.max(0, Math.min(this.data.length, line)); - if (selectionMarker.start.row != line) { - popup.selection.clearSelection(); - selectionMarker.start.row = selectionMarker.end.row = line || 0; - popup.session._emit("changeBackMarker"); - popup.moveCursorTo(line || 0, 0); - if (popup.isOpen) - popup._signal("select"); - } - }; - - popup.on("changeSelection", function() { - if (popup.isOpen) - popup.setRow(popup.selection.lead.row); - popup.renderer.scrollCursorIntoView(); - }); - - popup.hide = function() { - this.container.style.display = "none"; - this._signal("hide"); - popup.isOpen = false; - }; - popup.show = function(pos, lineHeight, topdownOnly) { - var el = this.container; - var screenHeight = window.innerHeight; - var screenWidth = window.innerWidth; - var renderer = this.renderer; - var maxH = renderer.$maxLines * lineHeight * 1.4; - var top = pos.top + this.$borderSize; - var allowTopdown = top > screenHeight / 2 && !topdownOnly; - if (allowTopdown && top + lineHeight + maxH > screenHeight) { - renderer.$maxPixelHeight = top - 2 * this.$borderSize; - el.style.top = ""; - el.style.bottom = screenHeight - top + "px"; - popup.isTopdown = false; - } else { - top += lineHeight; - renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight; - el.style.top = top + "px"; - el.style.bottom = ""; - popup.isTopdown = true; - } - - el.style.display = ""; - this.renderer.$textLayer.checkForSizeChanges(); - - var left = pos.left; - if (left + el.offsetWidth > screenWidth) - left = screenWidth - el.offsetWidth; - - el.style.left = left + "px"; - - this._signal("show"); - lastMouseEvent = null; - popup.isOpen = true; - }; - - popup.getTextLeftOffset = function() { - return this.$borderSize + this.renderer.$padding + this.$imageSize; - }; - - popup.$imageSize = 0; - popup.$borderSize = 1; - - return popup; -}; - -dom.importCssString("\ -.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\ - background-color: #CAD6FA;\ - z-index: 1;\ -}\ -.ace_editor.ace_autocomplete .ace_line-hover {\ - border: 1px solid #abbffe;\ - margin-top: -1px;\ - background: rgba(233,233,253,0.4);\ -}\ -.ace_editor.ace_autocomplete .ace_line-hover {\ - position: absolute;\ - z-index: 2;\ -}\ -.ace_editor.ace_autocomplete .ace_scroller {\ - background: none;\ - border: none;\ - box-shadow: none;\ -}\ -.ace_rightAlignedText {\ - color: gray;\ - display: inline-block;\ - position: absolute;\ - right: 4px;\ - text-align: right;\ - z-index: -1;\ -}\ -.ace_editor.ace_autocomplete .ace_completion-highlight{\ - color: #000;\ - text-shadow: 0 0 0.01em;\ -}\ -.ace_editor.ace_autocomplete {\ - width: 280px;\ - z-index: 200000;\ - background: #fbfbfb;\ - color: #444;\ - border: 1px lightgray solid;\ - position: fixed;\ - box-shadow: 2px 3px 5px rgba(0,0,0,.2);\ - line-height: 1.4;\ -}"); - -exports.AcePopup = AcePopup; - -}); - -ace.define("ace/autocomplete/util",["require","exports","module"], function(acequire, exports, module) { -"use strict"; - -exports.parForEach = function(array, fn, callback) { - var completed = 0; - var arLength = array.length; - if (arLength === 0) - callback(); - for (var i = 0; i < arLength; i++) { - fn(array[i], function(result, err) { - completed++; - if (completed === arLength) - callback(result, err); - }); - } -}; - -var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/; - -exports.retrievePrecedingIdentifier = function(text, pos, regex) { - regex = regex || ID_REGEX; - var buf = []; - for (var i = pos-1; i >= 0; i--) { - if (regex.test(text[i])) - buf.push(text[i]); - else - break; - } - return buf.reverse().join(""); -}; - -exports.retrieveFollowingIdentifier = function(text, pos, regex) { - regex = regex || ID_REGEX; - var buf = []; - for (var i = pos; i < text.length; i++) { - if (regex.test(text[i])) - buf.push(text[i]); - else - break; - } - return buf; -}; - -exports.getCompletionPrefix = function (editor) { - var pos = editor.getCursorPosition(); - var line = editor.session.getLine(pos.row); - var prefix; - editor.completers.forEach(function(completer) { - if (completer.identifierRegexps) { - completer.identifierRegexps.forEach(function(identifierRegex) { - if (!prefix && identifierRegex) - prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex); - }.bind(this)); - } - }.bind(this)); - return prefix || this.retrievePrecedingIdentifier(line, pos.column); -}; - -}); - -ace.define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/event","ace/lib/lang","ace/lib/dom","ace/snippets"], function(acequire, exports, module) { -"use strict"; - -var HashHandler = acequire("./keyboard/hash_handler").HashHandler; -var AcePopup = acequire("./autocomplete/popup").AcePopup; -var util = acequire("./autocomplete/util"); -var event = acequire("./lib/event"); -var lang = acequire("./lib/lang"); -var dom = acequire("./lib/dom"); -var snippetManager = acequire("./snippets").snippetManager; - -var Autocomplete = function() { - this.autoInsert = false; - this.autoSelect = true; - this.exactMatch = false; - this.gatherCompletionsId = 0; - this.keyboardHandler = new HashHandler(); - this.keyboardHandler.bindKeys(this.commands); - - this.blurListener = this.blurListener.bind(this); - this.changeListener = this.changeListener.bind(this); - this.mousedownListener = this.mousedownListener.bind(this); - this.mousewheelListener = this.mousewheelListener.bind(this); - - this.changeTimer = lang.delayedCall(function() { - this.updateCompletions(true); - }.bind(this)); - - this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50); -}; - -(function() { - - this.$init = function() { - this.popup = new AcePopup(document.body || document.documentElement); - this.popup.on("click", function(e) { - this.insertMatch(); - e.stop(); - }.bind(this)); - this.popup.focus = this.editor.focus.bind(this.editor); - this.popup.on("show", this.tooltipTimer.bind(null, null)); - this.popup.on("select", this.tooltipTimer.bind(null, null)); - this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null)); - return this.popup; - }; - - this.getPopup = function() { - return this.popup || this.$init(); - }; - - this.openPopup = function(editor, prefix, keepPopupPosition) { - if (!this.popup) - this.$init(); - - this.popup.setData(this.completions.filtered); - - editor.keyBinding.addKeyboardHandler(this.keyboardHandler); - - var renderer = editor.renderer; - this.popup.setRow(this.autoSelect ? 0 : -1); - if (!keepPopupPosition) { - this.popup.setTheme(editor.getTheme()); - this.popup.setFontSize(editor.getFontSize()); - - var lineHeight = renderer.layerConfig.lineHeight; - - var pos = renderer.$cursorLayer.getPixelPosition(this.base, true); - pos.left -= this.popup.getTextLeftOffset(); - - var rect = editor.container.getBoundingClientRect(); - pos.top += rect.top - renderer.layerConfig.offset; - pos.left += rect.left - editor.renderer.scrollLeft; - pos.left += renderer.gutterWidth; - - this.popup.show(pos, lineHeight); - } else if (keepPopupPosition && !prefix) { - this.detach(); - } - }; - - this.detach = function() { - this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler); - this.editor.off("changeSelection", this.changeListener); - this.editor.off("blur", this.blurListener); - this.editor.off("mousedown", this.mousedownListener); - this.editor.off("mousewheel", this.mousewheelListener); - this.changeTimer.cancel(); - this.hideDocTooltip(); - - this.gatherCompletionsId += 1; - if (this.popup && this.popup.isOpen) - this.popup.hide(); - - if (this.base) - this.base.detach(); - this.activated = false; - this.completions = this.base = null; - }; - - this.changeListener = function(e) { - var cursor = this.editor.selection.lead; - if (cursor.row != this.base.row || cursor.column < this.base.column) { - this.detach(); - } - if (this.activated) - this.changeTimer.schedule(); - else - this.detach(); - }; - - this.blurListener = function(e) { - if (e.relatedTarget && e.relatedTarget.nodeName == "A" && e.relatedTarget.href) { - window.open(e.relatedTarget.href, "_blank"); - } - var el = document.activeElement; - var text = this.editor.textInput.getElement(); - var fromTooltip = e.relatedTarget && e.relatedTarget == this.tooltipNode; - var container = this.popup && this.popup.container; - if (el != text && el.parentNode != container && !fromTooltip - && el != this.tooltipNode && e.relatedTarget != text - ) { - this.detach(); - } - }; - - this.mousedownListener = function(e) { - this.detach(); - }; - - this.mousewheelListener = function(e) { - this.detach(); - }; - - this.goTo = function(where) { - var row = this.popup.getRow(); - var max = this.popup.session.getLength() - 1; - - switch(where) { - case "up": row = row <= 0 ? max : row - 1; break; - case "down": row = row >= max ? -1 : row + 1; break; - case "start": row = 0; break; - case "end": row = max; break; - } - - this.popup.setRow(row); - }; - - this.insertMatch = function(data, options) { - if (!data) - data = this.popup.getData(this.popup.getRow()); - if (!data) - return false; - - if (data.completer && data.completer.insertMatch) { - data.completer.insertMatch(this.editor, data); - } else { - if (this.completions.filterText) { - var ranges = this.editor.selection.getAllRanges(); - for (var i = 0, range; range = ranges[i]; i++) { - range.start.column -= this.completions.filterText.length; - this.editor.session.remove(range); - } - } - if (data.snippet) - snippetManager.insertSnippet(this.editor, data.snippet); - else - this.editor.execCommand("insertstring", data.value || data); - } - this.detach(); - }; - - - this.commands = { - "Up": function(editor) { editor.completer.goTo("up"); }, - "Down": function(editor) { editor.completer.goTo("down"); }, - "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); }, - "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); }, - - "Esc": function(editor) { editor.completer.detach(); }, - "Return": function(editor) { return editor.completer.insertMatch(); }, - "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); }, - "Tab": function(editor) { - var result = editor.completer.insertMatch(); - if (!result && !editor.tabstopManager) - editor.completer.goTo("down"); - else - return result; - }, - - "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); }, - "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); } - }; - - this.gatherCompletions = function(editor, callback) { - var session = editor.getSession(); - var pos = editor.getCursorPosition(); - - var line = session.getLine(pos.row); - var prefix = util.getCompletionPrefix(editor); - - this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length); - this.base.$insertRight = true; - - var matches = []; - var total = editor.completers.length; - editor.completers.forEach(function(completer, i) { - completer.getCompletions(editor, session, pos, prefix, function(err, results) { - if (!err && results) - matches = matches.concat(results); - var pos = editor.getCursorPosition(); - var line = session.getLine(pos.row); - callback(null, { - prefix: prefix, - matches: matches, - finished: (--total === 0) - }); - }); - }); - return true; - }; - - this.showPopup = function(editor) { - if (this.editor) - this.detach(); - - this.activated = true; - - this.editor = editor; - if (editor.completer != this) { - if (editor.completer) - editor.completer.detach(); - editor.completer = this; - } - - editor.on("changeSelection", this.changeListener); - editor.on("blur", this.blurListener); - editor.on("mousedown", this.mousedownListener); - editor.on("mousewheel", this.mousewheelListener); - - this.updateCompletions(); - }; - - this.updateCompletions = function(keepPopupPosition) { - if (keepPopupPosition && this.base && this.completions) { - var pos = this.editor.getCursorPosition(); - var prefix = this.editor.session.getTextRange({start: this.base, end: pos}); - if (prefix == this.completions.filterText) - return; - this.completions.setFilter(prefix); - if (!this.completions.filtered.length) - return this.detach(); - if (this.completions.filtered.length == 1 - && this.completions.filtered[0].value == prefix - && !this.completions.filtered[0].snippet) - return this.detach(); - this.openPopup(this.editor, prefix, keepPopupPosition); - return; - } - var _id = this.gatherCompletionsId; - this.gatherCompletions(this.editor, function(err, results) { - var detachIfFinished = function() { - if (!results.finished) return; - return this.detach(); - }.bind(this); - - var prefix = results.prefix; - var matches = results && results.matches; - - if (!matches || !matches.length) - return detachIfFinished(); - if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId) - return; - - this.completions = new FilteredList(matches); - - if (this.exactMatch) - this.completions.exactMatch = true; - - this.completions.setFilter(prefix); - var filtered = this.completions.filtered; - if (!filtered.length) - return detachIfFinished(); - if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet) - return detachIfFinished(); - if (this.autoInsert && filtered.length == 1 && results.finished) - return this.insertMatch(filtered[0]); - - this.openPopup(this.editor, prefix, keepPopupPosition); - }.bind(this)); - }; - - this.cancelContextMenu = function() { - this.editor.$mouseHandler.cancelContextMenu(); - }; - - this.updateDocTooltip = function() { - var popup = this.popup; - var all = popup.data; - var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]); - var doc = null; - if (!selected || !this.editor || !this.popup.isOpen) - return this.hideDocTooltip(); - this.editor.completers.some(function(completer) { - if (completer.getDocTooltip) - doc = completer.getDocTooltip(selected); - return doc; - }); - if (!doc) - doc = selected; - - if (typeof doc == "string") - doc = {docText: doc}; - if (!doc || !(doc.docHTML || doc.docText)) - return this.hideDocTooltip(); - this.showDocTooltip(doc); - }; - - this.showDocTooltip = function(item) { - if (!this.tooltipNode) { - this.tooltipNode = dom.createElement("div"); - this.tooltipNode.className = "ace_tooltip ace_doc-tooltip"; - this.tooltipNode.style.margin = 0; - this.tooltipNode.style.pointerEvents = "auto"; - this.tooltipNode.tabIndex = -1; - this.tooltipNode.onblur = this.blurListener.bind(this); - } - - var tooltipNode = this.tooltipNode; - if (item.docHTML) { - tooltipNode.innerHTML = item.docHTML; - } else if (item.docText) { - tooltipNode.textContent = item.docText; - } - - if (!tooltipNode.parentNode) - document.body.appendChild(tooltipNode); - var popup = this.popup; - var rect = popup.container.getBoundingClientRect(); - tooltipNode.style.top = popup.container.style.top; - tooltipNode.style.bottom = popup.container.style.bottom; - - if (window.innerWidth - rect.right < 320) { - tooltipNode.style.right = window.innerWidth - rect.left + "px"; - tooltipNode.style.left = ""; - } else { - tooltipNode.style.left = (rect.right + 1) + "px"; - tooltipNode.style.right = ""; - } - tooltipNode.style.display = "block"; - }; - - this.hideDocTooltip = function() { - this.tooltipTimer.cancel(); - if (!this.tooltipNode) return; - var el = this.tooltipNode; - if (!this.editor.isFocused() && document.activeElement == el) - this.editor.focus(); - this.tooltipNode = null; - if (el.parentNode) - el.parentNode.removeChild(el); - }; - -}).call(Autocomplete.prototype); - -Autocomplete.startCommand = { - name: "startAutocomplete", - exec: function(editor) { - if (!editor.completer) - editor.completer = new Autocomplete(); - editor.completer.autoInsert = false; - editor.completer.autoSelect = true; - editor.completer.showPopup(editor); - editor.completer.cancelContextMenu(); - }, - bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space" -}; - -var FilteredList = function(array, filterText) { - this.all = array; - this.filtered = array; - this.filterText = filterText || ""; - this.exactMatch = false; -}; -(function(){ - this.setFilter = function(str) { - if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0) - var matches = this.filtered; - else - var matches = this.all; - - this.filterText = str; - matches = this.filterCompletions(matches, this.filterText); - matches = matches.sort(function(a, b) { - return b.exactMatch - a.exactMatch || b.score - a.score; - }); - var prev = null; - matches = matches.filter(function(item){ - var caption = item.snippet || item.caption || item.value; - if (caption === prev) return false; - prev = caption; - return true; - }); - - this.filtered = matches; - }; - this.filterCompletions = function(items, needle) { - var results = []; - var upper = needle.toUpperCase(); - var lower = needle.toLowerCase(); - loop: for (var i = 0, item; item = items[i]; i++) { - var caption = item.value || item.caption || item.snippet; - if (!caption) continue; - var lastIndex = -1; - var matchMask = 0; - var penalty = 0; - var index, distance; - - if (this.exactMatch) { - if (needle !== caption.substr(0, needle.length)) - continue loop; - }else{ - for (var j = 0; j < needle.length; j++) { - var i1 = caption.indexOf(lower[j], lastIndex + 1); - var i2 = caption.indexOf(upper[j], lastIndex + 1); - index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2; - if (index < 0) - continue loop; - distance = index - lastIndex - 1; - if (distance > 0) { - if (lastIndex === -1) - penalty += 10; - penalty += distance; - } - matchMask = matchMask | (1 << index); - lastIndex = index; - } - } - item.matchMask = matchMask; - item.exactMatch = penalty ? 0 : 1; - item.score = (item.score || 0) - penalty; - results.push(item); - } - return results; - }; -}).call(FilteredList.prototype); - -exports.Autocomplete = Autocomplete; -exports.FilteredList = FilteredList; - -}); - -ace.define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(acequire, exports, module) { - var Range = acequire("../range").Range; - - var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/; - - function getWordIndex(doc, pos) { - var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos)); - return textBefore.split(splitRegex).length - 1; - } - function wordDistance(doc, pos) { - var prefixPos = getWordIndex(doc, pos); - var words = doc.getValue().split(splitRegex); - var wordScores = Object.create(null); - - var currentWord = words[prefixPos]; - - words.forEach(function(word, idx) { - if (!word || word === currentWord) return; - - var distance = Math.abs(prefixPos - idx); - var score = words.length - distance; - if (wordScores[word]) { - wordScores[word] = Math.max(score, wordScores[word]); - } else { - wordScores[word] = score; - } - }); - return wordScores; - } - - exports.getCompletions = function(editor, session, pos, prefix, callback) { - var wordScore = wordDistance(session, pos, prefix); - var wordList = Object.keys(wordScore); - callback(null, wordList.map(function(word) { - return { - caption: word, - value: word, - score: wordScore[word], - meta: "local" - }; - })); - }; -}); - -ace.define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(acequire, exports, module) { -"use strict"; - -var snippetManager = acequire("../snippets").snippetManager; -var Autocomplete = acequire("../autocomplete").Autocomplete; -var config = acequire("../config"); -var lang = acequire("../lib/lang"); -var util = acequire("../autocomplete/util"); - -var textCompleter = acequire("../autocomplete/text_completer"); -var keyWordCompleter = { - getCompletions: function(editor, session, pos, prefix, callback) { - if (session.$mode.completer) { - return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback); - } - var state = editor.session.getState(pos.row); - var completions = session.$mode.getCompletions(state, session, pos, prefix); - callback(null, completions); - } -}; - -var snippetCompleter = { - getCompletions: function(editor, session, pos, prefix, callback) { - var snippetMap = snippetManager.snippetMap; - var completions = []; - snippetManager.getActiveScopes(editor).forEach(function(scope) { - var snippets = snippetMap[scope] || []; - for (var i = snippets.length; i--;) { - var s = snippets[i]; - var caption = s.name || s.tabTrigger; - if (!caption) - continue; - completions.push({ - caption: caption, - snippet: s.content, - meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet", - type: "snippet" - }); - } - }, this); - callback(null, completions); - }, - getDocTooltip: function(item) { - if (item.type == "snippet" && !item.docHTML) { - item.docHTML = [ - "", lang.escapeHTML(item.caption), "", "
", - lang.escapeHTML(item.snippet) - ].join(""); - } - } -}; - -var completers = [snippetCompleter, textCompleter, keyWordCompleter]; -exports.setCompleters = function(val) { - completers.length = 0; - if (val) completers.push.apply(completers, val); -}; -exports.addCompleter = function(completer) { - completers.push(completer); -}; -exports.textCompleter = textCompleter; -exports.keyWordCompleter = keyWordCompleter; -exports.snippetCompleter = snippetCompleter; - -var expandSnippet = { - name: "expandSnippet", - exec: function(editor) { - return snippetManager.expandWithTab(editor); - }, - bindKey: "Tab" -}; - -var onChangeMode = function(e, editor) { - loadSnippetsForMode(editor.session.$mode); -}; - -var loadSnippetsForMode = function(mode) { - var id = mode.$id; - if (!snippetManager.files) - snippetManager.files = {}; - loadSnippetFile(id); - if (mode.modes) - mode.modes.forEach(loadSnippetsForMode); -}; - -var loadSnippetFile = function(id) { - if (!id || snippetManager.files[id]) - return; - var snippetFilePath = id.replace("mode", "snippets"); - snippetManager.files[id] = {}; - config.loadModule(snippetFilePath, function(m) { - if (m) { - snippetManager.files[id] = m; - if (!m.snippets && m.snippetText) - m.snippets = snippetManager.parseSnippetFile(m.snippetText); - snippetManager.register(m.snippets || [], m.scope); - if (m.includeScopes) { - snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes; - m.includeScopes.forEach(function(x) { - loadSnippetFile("ace/mode/" + x); - }); - } - } - }); -}; - -var doLiveAutocomplete = function(e) { - var editor = e.editor; - var hasCompleter = editor.completer && editor.completer.activated; - if (e.command.name === "backspace") { - if (hasCompleter && !util.getCompletionPrefix(editor)) - editor.completer.detach(); - } - else if (e.command.name === "insertstring") { - var prefix = util.getCompletionPrefix(editor); - if (prefix && !hasCompleter) { - if (!editor.completer) { - editor.completer = new Autocomplete(); - } - editor.completer.autoInsert = false; - editor.completer.showPopup(editor); - } - } -}; - -var Editor = acequire("../editor").Editor; -acequire("../config").defineOptions(Editor.prototype, "editor", { - enableBasicAutocompletion: { - set: function(val) { - if (val) { - if (!this.completers) - this.completers = Array.isArray(val)? val: completers; - this.commands.addCommand(Autocomplete.startCommand); - } else { - this.commands.removeCommand(Autocomplete.startCommand); - } - }, - value: false - }, - enableLiveAutocompletion: { - set: function(val) { - if (val) { - if (!this.completers) - this.completers = Array.isArray(val)? val: completers; - this.commands.on('afterExec', doLiveAutocomplete); - } else { - this.commands.removeListener('afterExec', doLiveAutocomplete); - } - }, - value: false - }, - enableSnippets: { - set: function(val) { - if (val) { - this.commands.addCommand(expandSnippet); - this.on("changeMode", onChangeMode); - onChangeMode(null, this); - } else { - this.commands.removeCommand(expandSnippet); - this.off("changeMode", onChangeMode); - } - }, - value: false - } -}); -}); - (function() { - ace.acequire(["ace/ext/language_tools"], function() {}); - })(); - - /***/ }), /* 70 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return purchaseServer; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return purchaseRamForHomeComputer; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_IPAddress_js__ = __webpack_require__(17); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_YesNoBox_js__ = __webpack_require__(22); - - - - - - - - -/* Functions to handle any server-related purchasing: - * Purchasing new servers - * Purchasing more RAM for home computer - */ -function purchaseServer(ram, cost) { - //Check if player has enough money - if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.lt(cost)) { - Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You don't have enough money to purchase this server!"); - return; - } - - //Maximum server limit - if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].purchasedServers.length >= __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit) { - Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You have reached the maximum limit of " + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit + " servers. " + - "You cannot purchase any more. You can " + - "delete some of your purchased servers using the deleteServer() Netscript function in a script"); - return; - } - - var hostname = Object(__WEBPACK_IMPORTED_MODULE_5__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])(); - if (hostname == "") { - Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You must enter a hostname for your new server!"); - return; - } - - //Create server - var newServ = new __WEBPACK_IMPORTED_MODULE_2__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_4__utils_IPAddress_js__["a" /* createRandomIp */])(), hostname, "", false, true, true, ram); - Object(__WEBPACK_IMPORTED_MODULE_2__Server_js__["a" /* AddToAllServers */])(newServ); - - //Add to Player's purchasedServers array - __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].purchasedServers.push(newServ.ip); - - //Connect new server to home computer - var homeComputer = __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer(); - homeComputer.serversOnNetwork.push(newServ.ip); - newServ.serversOnNetwork.push(homeComputer.ip); - - __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(cost); - - Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Server successfully purchased with hostname " + hostname); -} - - -function purchaseRamForHomeComputer(cost) { - if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.lt(cost)) { - Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase additional RAM for your home computer"); - return; - } - - var homeComputer = __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer(); - homeComputer.maxRam *= 2; - - __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(cost); - - Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); -} - - - - -/***/ }), -/* 71 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return TerminalHelpText; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HelpTexts; }); -/* HelpText.js */ -let TerminalHelpText = - "Type 'help name' to learn more about the command 'name'

" + - 'alias [-g] [name="value"] Create or display Terminal aliases
' + - "analyze Get information about the current machine
" + - "buy [-l/program] Purchase a program through the Dark Web
" + - "cat [file] Display a .msg or .lit file
" + - "check [script] [args...] Print a script's logs to Terminal
" + - "clear Clear all text on the terminal
" + - "cls See 'clear' command
" + - "connect [ip/hostname] Connects to a remote server
" + - "download [text file] Downloads a text (.txt) file to your computer
" + - "free Check the machine's memory (RAM) usage
" + - "hack Hack the current machine
" + - "help [command] Display this help text, or the help text for a command
" + - "home Connect to home computer
" + - "hostname Displays the hostname of the machine
" + - "ifconfig Displays the IP address of the machine
" + - "kill [script] [args...] Stops the specified script on the current server
" + - "killall Stops all running scripts on the current machine
" + - "ls [| grep pattern] Displays all files on the machine
" + - "lscpu Displays the number of CPU cores on the machine
" + - "mem [script] [-t] [n] Displays the amount of RAM required to run the script
" + - "nano [script] Script editor - Open up and edit a script
" + - "ps Display all scripts that are currently running
" + - "rm [file] Delete a file from the server
" + - "run [name] [-t] [n] [args...] Execute a program or script
" + - "scan Prints all immediately-available network connections
" + - "scan-analyze [d] [-a] Prints info for all servers up to d nodes away
" + - "scp [file] [server] Copies a script or .lit file to a destination server
" + - "sudov Shows whether you have root access on this computer
" + - "tail [script] [args...] Displays dynamic logs for the specified script
" + - "theme [preset] | bg txt hlgt Change the color scheme of the UI
" + - "top Displays all running scripts and their RAM usage
" + - 'unalias "[alias name]" Deletes the specified alias
'; - -let HelpTexts = { - alias: 'alias [-g] [name="value"]
' + - "Create or display aliases. An alias enables a replacement of a word with another string. " + - "It can be used to abbreviate a commonly used command, or commonly used parts of a command. The NAME " + - "of an alias defines the word that will be replaced, while the VALUE defines what it will be replaced by. For example, " + - "you could create the alias 'nuke' for the Terminal command 'run NUKE.exe' using the following:

" + - 'alias nuke="run NUKE.exe"

' + - "Then, to run the NUKE.exe program you would just have to enter 'nuke' in Terminal rather than the full command. " + - "It is important to note that 'default' aliases will only be substituted for the first word of a Terminal command. For " + - "example, if the following alias was set:

" + - 'alias worm="HTTPWorm.exe"

' + - "and then you tried to run the following terminal command:

" + - "run worm

" + - "This would fail because the worm alias is not the first word of a Terminal command. To allow an alias to be substituted " + - "anywhere in a Terminal command, rather than just the first word, you must set it to be a global alias using the -g flag:

" + - 'alias -g worm="HTTPWorm.exe"

' + - "Now, the 'worm' alias will be substituted anytime it shows up as an individual word in a Terminal command.

" + - "Entering just the command 'alias' without any arguments prints the list of all defined aliases in the reusable form " + - "'alias NAME=VALUE' on the Terminal.

" + - "The 'unalias' command can be used to remove aliases.

", - analyze: "analze
" + - "Prints details and statistics about the current server. The information that is printed includes basic " + - "server details such as the hostname, whether the player has root access, what ports are opened/closed, and also " + - "hacking-related information such as an estimated chance to successfully hack, an estimate of how much money is " + - "available on the server, etc.", - buy: "buy [-l / program]
" + - "Purchase a program through the Dark Web. Requires a TOR router to use.

" + - "If this command is ran with the '-l' flag, it will display a list of all programs that can be bought through the " + - "dark web to the Terminal, as well as their costs.

" + - "Otherwise, the name of the program must be passed in as a parameter. This is name is NOT case-sensitive.", - cat: "cat [file]
" + - "Display message files, which are files ending with the '.msg' extension, or a literature file, which " + - "are files ending with the '.lit' extension. Examples:

" + - "cat j1.msg
" + - "cat foo.lit", - check: "check [script name] [args...]
" + - "Print the logs of the script specified by the script name and arguments to the Terminal. Each argument must be separated by " + - "a space. Remember that a running script is uniquely " + - "identified both by its name and the arguments that are used to start it. So, if a script was ran with the following arguments:

" + - "run foo.script 1 2 foodnstuff

" + - "Then to run the 'check' command on this script you would have to pass the same arguments in:

" + - "check foo.script 1 2 foodnstuff", - clear: "clear
" + - "Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " + - "and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'cls' command", - cls: "cls
" + - "Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " + - "and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'clear' command", - connect: "connect [hostname/ip]
" + - "Connect to a remote server. The hostname or IP address of the remote server must be given as the argument " + - "to this command. Note that only servers that are immediately adjacent to the current server in the network can be connected to. To " + - "see which servers can be connected to, use the 'scan' command.", - download: "download [text file]
" + - "Downloads a text file to your computer (like your real life computer). Only works on text files, " + - "which are the ones with a .txt extension.", - free: "free
" + - "Display's the memory usage on the current machine. Print the amount of RAM that is available on the current server as well as " + - "how much of it is being used.", - hack: "hack
" + - "Attempt to hack the current server. Requires root access in order to be run. See the wiki page for hacking mechanics
", - help: "help [command]
" + - "Display Terminal help information. Without arguments, 'help' prints a list of all valid Terminal commands and a brief " + - "description of their functionality. You can also pass the name of a Terminal command as an argument to 'help' to print " + - "more detailed information about the Terminal command. Examples:

" + - "help alias
" + - "help scan-analyze", - home: "home
" + - "Connect to your home computer. This will work no matter what server you are currently connected to.", - hostname: "hostname
" + - "Prints the hostname of the current server", - ifconfig: "ipconfig
" + - "Prints the IP address of the current server", - kill: "kill [script name] [args...]
" + - "Kill the script specified by the script name and arguments. Each argument must be separated by " + - "a space. Remember that a running script is uniquely identified by " + - "both its name and the arguments that are used to start it. So, if a script was ran with the following arguments:

" + - "run foo.script 1 sigma-cosmetics

" + - "Then to kill this script the same arguments would have to be used:

" + - "kill foo.script 1 sigma-cosmetics

" + - "Note that after issuing the 'kill' command for a script, it may take a while for the script to actually stop running. " + - "This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " + - "The script will not be stopped/killed until after that time has elapsed.", - killall: "killall
" + - "Kills all scripts on the current server. " + - "Note that after the 'kill' command is issued for a script, it may take a while for the script to actually stop running. " + - "This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " + - "The script will not be stopped/killed until after that time has elapsed.", - ls: "ls [| grep pattern]
" + - "The ls command, with no arguments, prints all files on the current server to the Terminal screen. " + - "This includes all scripts, programs, and message files. " + - "The files will be displayed in alphabetical order.

" + - "The '| grep pattern' optional parameter can be used to only display files whose filenames match the specified pattern. " + - "For example, if you wanted to only display files with the .script extension, you could use:

" + - "ls | grep .script

" + - "Alternatively, if you wanted to display all files with the word purchase in the filename, you could use:

" + - "ls | grep purchase", - mem: "mem [script name] [-t] [num threads]
" + - "Displays the amount of RAM needed to run the specified script with a single thread. The command can also be used to print " + - "the amount of RAM needed to run a script with multiple threads using the '-t' flag. If the '-t' flag is specified, then " + - "an argument for the number of threads must be passed in afterwards. Examples:

" + - "mem foo.script
" + - "mem foo.script -t 50
" + - "The first example above will print the amount of RAM needed to run 'foo.script' with a single thread. The second example " + - "above will print the amount of RAM needed to run 'foo.script' with 50 threads.", - nano: "nano [script name]
" + - "Opens up the specified script in the Script Editor. If the script does not already exist, then a new, empty script " + - "will be created", - ps: "ps
" + - "Prints all scripts that are running on the current server", - rm: "rm [file]
" + - "Removes the specified file from the current server. A file can be a script, a program, or a message file.

" + - "WARNING: This is permanent and cannot be undone", - run: "run [file name] [-t] [num threads] [args...]
" + - "Execute a program or a script.

" + - "The '[-t]', '[num threads]', and '[args...]' arguments are only valid when running a script. The '-t' flag is used " + - "to indicate that the script should be run with the specified number of threads. If the flag is omitted, " + - "then the script will be run with a single thread by default. " + - "If the '-t' flag is used, then it MUST come immediately " + - "after the script name, and the [num threads] argument MUST come immediately afterwards.

" + - "[args...] represents a variable number of arguments that will be passed into the script. See the documentation " + - "about script arguments. Each specified argument must be separated by a space.

", - scan: "scan
" + - "Prints all immediately-available network connection. This will print a list of all servers that you can currently connect " + - "to using the 'connect' Terminal command.", - "scan-analyze": "scan-analyze [depth] [-a]
" + - "Prints detailed information about all servers up to [depth] nodes away on the network. Calling " + - "'scan-analyze 1' will display information for the same servers that are shown by the 'scan' Terminal " + - "command. This command also shows the relative paths to reach each server.

" + - "By default, the maximum depth that can be specified for 'scan-analyze' is 3. However, once you have " + - "the DeepscanV1.exe and DeepscanV2.exe programs, you can execute 'scan-analyze' with a depth up to " + - "5 and 10, respectively.

" + - "The information 'scan-analyze' displays about each server includes whether or not you have root access to it, " + - "its required hacking level, the number of open ports required to run NUKE.exe on it, and how much RAM " + - "it has.

" + - "By default, this command will not display servers that you have purchased. However, you can pass in the " + - "-a flag at the end of the command if you would like to enable that.", - scp: "scp [filename] [target server]
" + - "Copies the specified file from the current server to the target server. " + - "This command only works for script files (.script extension) and literature files (.lit extension). " + - "The second argument passed in must be the hostname or IP of the target server.", - sudov: "sudov
" + - "Prints whether or not you have root access to the current machine", - tail: "tail [script name] [args...]
" + - "Displays dynamic logs for the script specified by the script name and arguments. Each argument must be separated " + - "by a space. Remember that a running script is uniquely identified by both its name and the arguments that were used " + - "to run it. So, if a script was ran with the following arguments:

" + - "run foo.script 10 50000

" + - "Then in order to check its logs with 'tail' the same arguments must be used:

" + - "tail foo.script 10 50000", - theme: "theme [preset] | [#background #text #highlight]
" + - "Change the color of the game's user interface

" + - "This command can be called with a preset theme. Currently, the supported presets are 'default', 'muted', and 'solarized'. " + - "However, you can also specify your own color scheme using hex values. To do so, you must specify three hex color values " + - "for the background color, the text color, and the highlight color. These hex values must be preceded by a pound sign (#) and " + - "must be either 3 or 6 digits. Example:

" + - "theme #ffffff #385 #235012

" + - "A color picker such as " + - "Google's " + - "can be used to get your desired hex color values

" + - "Themes are not saved, so when the game is closed and then re-opened or reloaded then it will revert back to the default theme.", - top: "top
" + - "Prints a list of all scripts running on the current server as well as their thread count and how much " + - "RAM they are using in total.", - unalias: 'unalias "[alias name]"
' + - "Deletes the specified alias. Note that the double quotation marks are required.

" + - "As an example, if an alias was declared using:

" + - 'alias r="run"

' + - "Then it could be removed using:

" + - 'unalias "r"

' + - "It is not necessary to differentiate between global and non-global aliases when using 'unalias'", - -} - - - - -/***/ }), -/* 72 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/* @preserve @@ -98756,10 +98615,10 @@ module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(48), __webpack_require__(33), __webpack_require__(73).setImmediate)) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(48), __webpack_require__(32), __webpack_require__(71).setImmediate)) /***/ }), -/* 73 */ +/* 71 */ /***/ (function(module, exports, __webpack_require__) { var apply = Function.prototype.apply; @@ -98812,13 +98671,13 @@ exports._unrefActive = exports.active = function(item) { }; // setimmediate attaches itself to the global object -__webpack_require__(74); +__webpack_require__(72); exports.setImmediate = setImmediate; exports.clearImmediate = clearImmediate; /***/ }), -/* 74 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { @@ -99008,7 +98867,148 @@ exports.clearImmediate = clearImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self)); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33), __webpack_require__(48))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32), __webpack_require__(48))) + +/***/ }), +/* 73 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return purchaseServer; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return purchaseRamForHomeComputer; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Server_js__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__ = __webpack_require__(1); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_IPAddress_js__ = __webpack_require__(18); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_YesNoBox_js__ = __webpack_require__(17); + + + + + + + + +/* Functions to handle any server-related purchasing: + * Purchasing new servers + * Purchasing more RAM for home computer + */ +function purchaseServer(ram, cost) { + //Check if player has enough money + if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.lt(cost)) { + Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You don't have enough money to purchase this server!"); + return; + } + + //Maximum server limit + if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].purchasedServers.length >= __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit) { + Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You have reached the maximum limit of " + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit + " servers. " + + "You cannot purchase any more. You can " + + "delete some of your purchased servers using the deleteServer() Netscript function in a script"); + return; + } + + var hostname = Object(__WEBPACK_IMPORTED_MODULE_5__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])(); + if (hostname == "") { + Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You must enter a hostname for your new server!"); + return; + } + + //Create server + var newServ = new __WEBPACK_IMPORTED_MODULE_2__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_4__utils_IPAddress_js__["a" /* createRandomIp */])(), hostname, "", false, true, true, ram); + Object(__WEBPACK_IMPORTED_MODULE_2__Server_js__["a" /* AddToAllServers */])(newServ); + + //Add to Player's purchasedServers array + __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].purchasedServers.push(newServ.ip); + + //Connect new server to home computer + var homeComputer = __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer(); + homeComputer.serversOnNetwork.push(newServ.ip); + newServ.serversOnNetwork.push(homeComputer.ip); + + __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(cost); + + Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Server successfully purchased with hostname " + hostname); +} + + +function purchaseRamForHomeComputer(cost) { + if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.lt(cost)) { + Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase additional RAM for your home computer"); + return; + } + + var homeComputer = __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer(); + homeComputer.maxRam *= 2; + + __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(cost); + + Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); +} + + + + +/***/ }), +/* 74 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return factionInvitationBoxCreate; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_Faction_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_Player_js__ = __webpack_require__(0); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__ = __webpack_require__(2); + + + + +/* Faction Invitation Pop-up box */ +function factionInvitationBoxClose() { + var factionInvitationBox = document.getElementById("faction-invitation-box-container"); + factionInvitationBox.style.display = "none"; +} + +function factionInvitationBoxOpen() { + var factionInvitationBox = document.getElementById("faction-invitation-box-container"); + factionInvitationBox.style.display = "block"; +} + +function factionInvitationSetText(txt) { + var textBox = document.getElementById("faction-invitation-box-text"); + textBox.innerHTML = txt; +} + +function factionInvitationSetMessage(msg) { + var msgBox = document.getElementById("faction-invitation-box-message"); + msgBox.innerHTML = msg; +} + +//ram argument is in GB +function factionInvitationBoxCreate(faction) { + factionInvitationSetText("You have received a faction invitation from " + faction.name); + //TODO Faction invitation message + + var newYesButton = Object(__WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__["b" /* clearEventListeners */])("faction-invitation-box-yes"); + newYesButton.addEventListener("click", function() { + Object(__WEBPACK_IMPORTED_MODULE_0__src_Faction_js__["h" /* joinFaction */])(faction); + factionInvitationBoxClose(); + return false; + }); + + var noButton = Object(__WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__["b" /* clearEventListeners */])("faction-invitation-box-no"); + noButton.addEventListener("click", function() { + factionInvitationBoxClose(); + faction.alreadyInvited = true; + __WEBPACK_IMPORTED_MODULE_1__src_Player_js__["a" /* Player */].factionInvitations.push(faction.name); + return false; + }); + + factionInvitationBoxOpen(); +} + + + /***/ }), /* 75 */ @@ -99017,26 +99017,26 @@ exports.clearImmediate = clearImmediate; "use strict"; /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return saveObject; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return loadGame; }); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Alias_js__ = __webpack_require__(44); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Alias_js__ = __webpack_require__(45); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Company_js__ = __webpack_require__(21); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Constants_js__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__engine_js__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Faction_js__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Gang_js__ = __webpack_require__(34); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__HacknetNode_js__ = __webpack_require__(39); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Faction_js__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Gang_js__ = __webpack_require__(39); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__HacknetNode_js__ = __webpack_require__(38); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Message_js__ = __webpack_require__(24); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Player_js__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Script_js__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Server_js__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Settings_js__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Settings_js__ = __webpack_require__(15); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__StockMarket_js__ = __webpack_require__(29); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__StockMarket_js__ = __webpack_require__(28); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__utils_GameOptions_js__ = __webpack_require__(40); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__ = __webpack_require__(4); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js__ = __webpack_require__(28); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js__ = __webpack_require__(29); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_19__utils_decimal_js__); diff --git a/src/Gang.js b/src/Gang.js index dc086ffa2..13c7e4a04 100644 --- a/src/Gang.js +++ b/src/Gang.js @@ -1037,7 +1037,7 @@ function displayGangContent() { territorySubpage.appendChild(territoryBorder); } - document.getElementById("gang-container").style.visibility = "visible"; + document.getElementById("gang-container").style.display = "block"; updateGangContent(); }