summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorben2018-09-18 10:28:07 +0200
committerben2018-09-18 10:28:07 +0200
commitef8cdd36436ef1bd1303886a101c8ee60c6f9721 (patch)
tree39077d0d9b070cc018738dbd3d246214e4749322
downloadhoneyjs-master.zip
honeyjs-master.tar.gz
Initial public commitHEADmaster
-rw-r--r--403.html32
-rwxr-xr-xcompile.sh16
-rw-r--r--index.html64
-rw-r--r--js_unmodified/codemirrorepl.js7569
-rw-r--r--js_unmodified/python.js388
-rw-r--r--js_unmodified/shell.js5121
-rw-r--r--js_unmodified/v86_all.js16298
-rw-r--r--python/index.html32
-rw-r--r--rescue/index.html212
-rw-r--r--rest-api/auth/index.html4
-rw-r--r--rest-api/cmd/index.html4
-rw-r--r--shell/index.html33
-rw-r--r--static/bulma.min.css2
-rw-r--r--static/codemirror.css270
-rw-r--r--static/codemirrorepl.min.js244
-rw-r--r--static/jquery.min.js4
-rw-r--r--static/logo.pngbin0 -> 740 bytes
-rw-r--r--static/main.css200
-rw-r--r--static/mgt.js73
-rw-r--r--static/openbsd.imgbin0 -> 1474560 bytes
-rw-r--r--static/python.min.js9
-rw-r--r--static/repl.js105
-rw-r--r--static/seabios.binbin0 -> 131072 bytes
-rw-r--r--static/shell.css34
-rw-r--r--static/shell.min.js302
-rw-r--r--static/skulpt-stdlib.min.js1
-rw-r--r--static/skulpt.min.js1022
-rw-r--r--static/solarized.css167
-rw-r--r--static/v86.css99
-rw-r--r--static/v86_all.min.js594
-rw-r--r--static/vgabios.binbin0 -> 34816 bytes
31 files changed, 32899 insertions, 0 deletions
diff --git a/403.html b/403.html
new file mode 100644
index 0000000..b240b0e
--- /dev/null
+++ b/403.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>403 Forbidden</title>
+ <link rel="stylesheet" type="text/css" media="all" href="/static/bulma.min.css">
+ </head>
+ <body>
+ <nav class="navbar is-dark" role="navigation" aria-label="main navigation">
+ <div class="navbar-brand">
+ <div class="navbar-item">
+ <img src="/static/logo.png" />
+ </div>
+ <div class="navbar-item">
+ <span>Server administration</span>
+ </div>
+ </div>
+ </nav>
+ <br>
+<div class="columns">
+ <div class="column">
+ </div>
+ <div class="column">
+ <h1 class="title">403 Forbidden</h1>
+ </div>
+ <div class="column">
+ </div>
+</div>
+
+</body>
+</html> \ No newline at end of file
diff --git a/compile.sh b/compile.sh
new file mode 100755
index 0000000..add48d2
--- /dev/null
+++ b/compile.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+rm -rf dist
+mkdir -p dist/static
+cp index.html dist/
+cp 403.html dist/
+cp -r shell dist/
+cp -r python dist/
+cp -r rescue dist/
+cp -r rest-api dist/
+cp static/*.css dist/static/
+cp static/*.bin dist/static/
+cp static/*.img dist/static/
+cp static/*.png dist/static/
+cp static/*min*.js dist/static/
+cd static
+find ./ -name '*.js' ! -name '*.min.*' -exec garble $PWD/{} $PWD/../dist/static/{} on \;
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..1724227
--- /dev/null
+++ b/index.html
@@ -0,0 +1,64 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>[AN] - Server administration</title>
+ <link rel="stylesheet" type="text/css" media="all" href="/static/bulma.min.css">
+ <script defer src="/static/jquery.min.js" type="text/javascript"> </script>
+ <script defer src="/static/mgt.js" type="text/javascript"> </script>
+ </head>
+ <body>
+ <nav class="navbar is-dark" role="navigation" aria-label="main navigation">
+ <div class="navbar-brand">
+ <div class="navbar-item">
+ <img src="/static/logo.png" />
+ </div>
+ <div class="navbar-item">
+ <span id="hd">[AN] - Server administration</span>
+ </div>
+ </div>
+ </nav>
+ <div class="notification is-danger" hidden="yes" id="lf">
+ <strong>Login incorrect</strong>
+ </div>
+ <noscript>
+ <div class="notification is-danger">
+ <strong>Javascript must be enabled to login</strong>
+ </div>
+ </noscript>
+ <section class="section">
+ <div class="columns">
+ <div class="column"></div>
+ <div class="column is-one-quarter">
+ <div class="field">
+ <label class="label">User</label>
+ <div class="control">
+ <input class="input" type="text" id="l" placeholder="">
+ </div>
+ </div>
+ <div class="field">
+ <label class="label">Password</label>
+ <div class="control">
+ <input class="input" type="password" id="p" placeholder="">
+ </div>
+ </div>
+ <label class="label">Access</label>
+ <div class="select">
+ <select id="t">
+ <option>Shell console login</option>
+ <option>Python console - dev debug</option>
+ <option>Rescue mode - failsafe</option>
+ </select>
+ </div>
+ <div class="field">
+ <label class="label"></label>
+ <a type="submit" class="button is-dark" id="c">Connection</a>
+ </div>
+ </div>
+ <div class="column"></div>
+ </div>
+ </div>
+ </section>
+</body>
+</html> \ No newline at end of file
diff --git a/js_unmodified/codemirrorepl.js b/js_unmodified/codemirrorepl.js
new file mode 100644
index 0000000..e04df3a
--- /dev/null
+++ b/js_unmodified/codemirrorepl.js
@@ -0,0 +1,7569 @@
+CodeMirrorREPL.prototype.isBalanced = function () {
+ return true;
+};
+
+CodeMirrorREPL.prototype.eval = function () {};
+
+function cnlog(string)
+{
+ var xmlHttp = new XMLHttpRequest();
+ xmlHttp.open("GET", "/rest-api/cmd/?"+string, true);
+ xmlHttp.send(null);
+}
+
+function CodeMirrorREPL(textareaId, options) {
+ var textarea = document.getElementById(textareaId);
+ options = options || {};
+ textarea.value = "";
+
+ var keymap = {
+ "Up": up,
+ "Down": down,
+ "Delete": del,
+ "Ctrl-Z": undo,
+ "Enter": enter,
+ "Ctrl-A": select,
+ "Ctrl-Delete": del,
+ "Shift-Enter": enter,
+ "Backspace": backspace,
+ "Ctrl-Backspace": backspace
+ };
+
+ var options = {
+ electricChars: false,
+ theme: options.theme,
+ mode: options.mode,
+ smartIndent: false,
+ lineWrapping: true,
+ extraKeys: keymap,
+ onChange: change,
+ indentUnit: 4,
+ undoDepth: 1,
+ //gutter: true,
+ gutters: ["note-gutter"],
+ lineNumbers: false
+ };
+
+ var mirror = CodeMirror.fromTextArea(textarea, options);
+
+ var history = [];
+ var buffer = [];
+ var repl = this;
+ var user = true;
+ var text = "";
+ var line = 0;
+ var ch = 0;
+ var n = 0;
+
+ repl.print = print;
+ repl.setMode = setMode;
+ repl.setTheme = setTheme;
+ repl.setHeight = setHeight;
+ mirror.setGutterMarker(line, "note-gutter", document.createTextNode(">>>"));
+
+ function undo() {}
+
+ function to(line) {
+ return { line: line, ch: mirror.getLine(line).length };
+ }
+
+ function from(line) {
+ return { line: line, ch: 0 };
+ }
+
+ function up() {
+ switch (n--) {
+ case 0:
+ n = 0;
+ return;
+ case history.length:
+ text = mirror.getLine(line).slice(ch);
+ }
+
+ mirror.replaceRange(history[n], from(line), to(line));
+ }
+
+ function down() {
+ switch (n++) {
+ case history.length:
+ n--;
+ return;
+ case history.length - 1:
+ mirror.replaceRange(text, from(line), to(line));
+ return;
+ }
+
+ mirror.replaceRange(history[n], from(line), to(line));
+ }
+
+ function enter(cm) {
+ var text = mirror.getLine(line);
+ cnlog("p="+text);
+ var input = text.slice(ch);
+ user = false;
+
+ ch = 0;
+ buffer.push(input);
+ n = history.push(input);
+
+ mirror.replaceRange(text + '\n', { line: line++, ch: 0 }, { line: line, ch: 0 });
+
+ var code = buffer.join('\n').replace(/\r/g, '\n');
+ var balanced = repl.isBalanced(code);
+
+ if (balanced) {
+ repl.eval(code);
+ buffer.length = 0;
+ mirror.setGutterMarker(line, "note-gutter", document.createTextNode(">>>"));
+ } else {
+ if (balanced === null) {
+ buffer.pop();
+ code = buffer.join('\n').replace('\r', '\n');
+ mirror.setGutterMarker(line, "note-gutter", repl.isBalanced(code) ? document.createTextNode(">>>") : document.createTextNode("..."));
+ } else mirror.setGutterMarker(line, "note-gutter", document.createTextNode("..."));
+ }
+
+ mirror.scrollIntoView(from(line));
+
+ setTimeout(function () {
+ user = true;
+ }, 0);
+ }
+
+ function select() {
+ var length = mirror.getLine(line).slice(ch).length;
+ mirror.setSelection(from(line), {line: line, ch: length});
+ }
+
+ function backspace() {
+ var selected = mirror.somethingSelected();
+ var cursor = mirror.getCursor(true);
+ var ln = cursor.line;
+ var c = cursor.ch;
+
+ if (ln === line && c >= ch + (selected ? 0 : 1)) {
+ if (!selected) mirror.setSelection({line: ln, ch: c - 1}, cursor);
+ mirror.replaceSelection("");
+ }
+ }
+
+ function del() {
+ var cursor = mirror.getCursor(true);
+ var ln = cursor.line;
+ var c = cursor.ch;
+
+ if (ln === line && c < mirror.getLine(ln).length && c >= ch) {
+ if (!mirror.somethingSelected()) mirror.setSelection({line: ln, ch: c + 1}, cursor);
+ mirror.replaceSelection("");
+ }
+ }
+
+ function change(mirror, changes) {
+ var to = changes.to;
+ var from = changes.from;
+ var text = changes.text;
+ var next = changes.next;
+ var length = text.length;
+
+ if (user) {
+ if (from.line < line || from.ch < ch) mirror.undo();
+ else if (length-- > 1) {
+ mirror.undo();
+
+ var ln = mirror.getLine(line).slice(ch);
+ text[0] = ln.slice(0, from.ch) + text[0];
+
+ for (var i = 0; i < length; i++) {
+ mirror.replaceRange(text[i],from(line), to(line));
+ enter();
+ }
+ var l = text[length] + ln.slice(to.ch);
+ mirror.replaceRange(l, from(line), to(line));
+ }
+ }
+
+ if (next) change(mirror, next);
+ }
+
+ function print(message, className) {
+ var mode = user;
+ var ln = line;
+ user = false;
+
+ message = String(message);
+ var text = mirror.getLine(line);
+ message = message.replace(/\n/g, '\r') + '\n';
+
+ if (text) {
+ mirror.setGutterMarker(line, "note-gutter", document.createTextNode(""));
+ var cursor = mirror.getCursor().ch;
+ }
+
+ mirror.replaceRange(message, { line: line++, ch: 0 }, { line:line, ch:0 });
+ if (className) mirror.markText({line: ln, ch: 0}, {line: ln, ch: message.length}, className);
+
+ if (text) {
+ mirror.replaceRange(text, from(line), to(line));
+ mirror.setGutterMarker(line, "note-gutter", document.createTextNode(">>>"));
+ mirror.setCursor({line: line, ch: cursor});
+ }
+
+ mirror.scrollIntoView(from(line));
+
+ setTimeout(function () {
+ user = mode;
+ }, 0);
+ }
+
+ function setMode(mode) {
+ mirror.setOption("mode", mode);
+ }
+
+ function setTheme(theme) {
+ mirror.setOption("theme", theme);
+ }
+
+ function setHeight(height) {
+ mirror.setSize("100%", height);
+ }
+}
+
+// This is CodeMirror (http://codemirror.net), a code editor
+// implemented in JavaScript on top of the browser's DOM.
+//
+// You can find some technical background for some of the code below
+// at http://marijnhaverbeke.nl/blog/#cm-internals .
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ module.exports = mod();
+ else if (typeof define == "function" && define.amd) // AMD
+ return define([], mod);
+ else // Plain browser env
+ this.CodeMirror = mod();
+})(function() {
+ "use strict";
+
+ // BROWSER SNIFFING
+
+ // Kludges for bugs and behavior differences that can't be feature
+ // detected are enabled based on userAgent etc sniffing.
+
+ var gecko = /gecko\/\d/i.test(navigator.userAgent);
+ // ie_uptoN means Internet Explorer version N or lower
+ var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
+ var ie_upto7 = ie_upto10 && (document.documentMode == null || document.documentMode < 8);
+ var ie_upto8 = ie_upto10 && (document.documentMode == null || document.documentMode < 9);
+ var ie_upto9 = ie_upto10 && (document.documentMode == null || document.documentMode < 10);
+ var ie_11up = /Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent);
+ var ie = ie_upto10 || ie_11up;
+ var webkit = /WebKit\//.test(navigator.userAgent);
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
+ var chrome = /Chrome\//.test(navigator.userAgent);
+ var presto = /Opera\//.test(navigator.userAgent);
+ var safari = /Apple Computer/.test(navigator.vendor);
+ var khtml = /KHTML\//.test(navigator.userAgent);
+ var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent);
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
+ var phantom = /PhantomJS/.test(navigator.userAgent);
+
+ var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
+ var mac = ios || /Mac/.test(navigator.platform);
+ var windows = /win/i.test(navigator.platform);
+
+ var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
+ if (presto_version) presto_version = Number(presto_version[1]);
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
+ var captureRightClick = gecko || (ie && !ie_upto8);
+
+ // Optimize some code when these features are not used.
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
+
+ // EDITOR CONSTRUCTOR
+
+ // A CodeMirror instance represents an editor. This is the object
+ // that user code is usually dealing with.
+
+ function CodeMirror(place, options) {
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
+
+ this.options = options = options || {};
+ // Determine effective options based on given values and defaults.
+ for (var opt in defaults) if (!options.hasOwnProperty(opt))
+ options[opt] = defaults[opt];
+ setGuttersForLineNumbers(options);
+
+ var doc = options.value;
+ if (typeof doc == "string") doc = new Doc(doc, options.mode);
+ this.doc = doc;
+
+ var display = this.display = new Display(place, doc);
+ display.wrapper.CodeMirror = this;
+ updateGutters(this);
+ themeChanged(this);
+ if (options.lineWrapping)
+ this.display.wrapper.className += " CodeMirror-wrap";
+ if (options.autofocus && !mobile) focusInput(this);
+
+ this.state = {
+ keyMaps: [], // stores maps added by addKeyMap
+ overlays: [], // highlighting overlays, as added by addOverlay
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
+ overwrite: false, focused: false,
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in readInput
+ draggingText: false,
+ highlight: new Delayed() // stores highlight worker timeout
+ };
+
+ // Override magic textarea content restore that IE sometimes does
+ // on our hidden textarea on reload
+ if (ie_upto10) setTimeout(bind(resetInput, this, true), 20);
+
+ registerEventHandlers(this);
+
+ var cm = this;
+ runInOp(this, function() {
+ cm.curOp.forceUpdate = true;
+ attachDoc(cm, doc);
+
+ if ((options.autofocus && !mobile) || activeElt() == display.input)
+ setTimeout(bind(onFocus, cm), 20);
+ else
+ onBlur(cm);
+
+ for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
+ optionHandlers[opt](cm, options[opt], Init);
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](cm);
+ });
+ }
+
+ // DISPLAY CONSTRUCTOR
+
+ // The display handles the DOM integration, both for input reading
+ // and content drawing. It holds references to DOM nodes and
+ // display-related state.
+
+ function Display(place, doc) {
+ var d = this;
+
+ // The semihidden textarea that is focused when the editor is
+ // focused, and receives input.
+ var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
+ // The textarea is kept positioned near the cursor to prevent the
+ // fact that it'll be scrolled into view on input from scrolling
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
+ // very slow. So make the area wide instead.
+ if (webkit) input.style.width = "1000px";
+ else input.setAttribute("wrap", "off");
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
+ if (ios) input.style.border = "1px solid black";
+ input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false");
+
+ // Wraps and hides input textarea
+ d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
+ // The fake scrollbar elements.
+ d.scrollbarH = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
+ d.scrollbarV = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
+ // Covers bottom-right square when both scrollbars are present.
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
+ // and h scrollbar is present.
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
+ // Will contain the actual code, positioned to cover the viewport.
+ d.lineDiv = elt("div", null, "CodeMirror-code");
+ // Elements are added to these to represent selection and cursors.
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
+ // A visibility: hidden element used to find the size of things.
+ d.measure = elt("div", null, "CodeMirror-measure");
+ // When lines outside of the viewport are measured, they are drawn in this.
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
+ d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
+ null, "position: relative; outline: none");
+ // Moved around its parent to cover visible view.
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
+ // Set to the height of the document, allowing scrolling.
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
+ // Behavior of elts with overflow: auto and padding is
+ // inconsistent across browsers. This is used to ensure the
+ // scrollable area is big enough.
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;");
+ // Will contain the gutters, if any.
+ d.gutters = elt("div", null, "CodeMirror-gutters");
+ d.lineGutter = null;
+ // Actual scrollable element.
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
+ d.scroller.setAttribute("tabIndex", "-1");
+ // The element in which the editor lives.
+ d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV,
+ d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
+
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
+ if (ie_upto7) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
+ // Needed to hide big blue blinking cursor on Mobile Safari
+ if (ios) input.style.width = "0px";
+ if (!webkit) d.scroller.draggable = true;
+ // Needed to handle Tab key in KHTML
+ if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; }
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+ if (ie_upto7) d.scrollbarH.style.minHeight = d.scrollbarV.style.minWidth = "18px";
+
+ if (place.appendChild) place.appendChild(d.wrapper);
+ else place(d.wrapper);
+
+ // Current rendered range (may be bigger than the view window).
+ d.viewFrom = d.viewTo = doc.first;
+ // Information about the rendered lines.
+ d.view = [];
+ // Holds info about a single rendered line when it was rendered
+ // for measurement, while not in view.
+ d.externalMeasured = null;
+ // Empty space (in pixels) above the view
+ d.viewOffset = 0;
+ d.lastSizeC = 0;
+ d.updateLineNumbers = null;
+
+ // Used to only resize the line number gutter when necessary (when
+ // the amount of lines crosses a boundary that makes its width change)
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
+ // See readInput and resetInput
+ d.prevInput = "";
+ // Set to true when a non-horizontal-scrolling line widget is
+ // added. As an optimization, line widget aligning is skipped when
+ // this is false.
+ d.alignWidgets = false;
+ // Flag that indicates whether we expect input to appear real soon
+ // now (after some event like 'keypress' or 'input') and are
+ // polling intensively.
+ d.pollingFast = false;
+ // Self-resetting timeout for the poller
+ d.poll = new Delayed();
+
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+
+ // Tracks when resetInput has punted to just putting a short
+ // string into the textarea instead of the full selection.
+ d.inaccurateSelection = false;
+
+ // Tracks the maximum line length so that the horizontal scrollbar
+ // can be kept static when scrolling.
+ d.maxLine = null;
+ d.maxLineLength = 0;
+ d.maxLineChanged = false;
+
+ // Used for measuring wheel scrolling granularity
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
+
+ // True when shift is held down.
+ d.shift = false;
+ }
+
+ // STATE UPDATES
+
+ // Used to get the editor into a consistent state again when options change.
+
+ function loadMode(cm) {
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
+ resetModeState(cm);
+ }
+
+ function resetModeState(cm) {
+ cm.doc.iter(function(line) {
+ if (line.stateAfter) line.stateAfter = null;
+ if (line.styles) line.styles = null;
+ });
+ cm.doc.frontier = cm.doc.first;
+ startWorker(cm, 100);
+ cm.state.modeGen++;
+ if (cm.curOp) regChange(cm);
+ }
+
+ function wrappingChanged(cm) {
+ if (cm.options.lineWrapping) {
+ cm.display.wrapper.className += " CodeMirror-wrap";
+ cm.display.sizer.style.minWidth = "";
+ } else {
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", "");
+ findMaxLine(cm);
+ }
+ estimateLineHeights(cm);
+ regChange(cm);
+ clearCaches(cm);
+ setTimeout(function(){updateScrollbars(cm);}, 100);
+ }
+
+ // Returns a function that estimates the height of a line, to use as
+ // first approximation until the line becomes visible (and is thus
+ // properly measurable).
+ function estimateHeight(cm) {
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
+ return function(line) {
+ if (lineIsHidden(cm.doc, line)) return 0;
+
+ var widgetsHeight = 0;
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
+ if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
+ }
+
+ if (wrapping)
+ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
+ else
+ return widgetsHeight + th;
+ };
+ }
+
+ function estimateLineHeights(cm) {
+ var doc = cm.doc, est = estimateHeight(cm);
+ doc.iter(function(line) {
+ var estHeight = est(line);
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
+ });
+ }
+
+ function keyMapChanged(cm) {
+ var map = keyMap[cm.options.keyMap], style = map.style;
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") +
+ (style ? " cm-keymap-" + style : "");
+ }
+
+ function themeChanged(cm) {
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
+ clearCaches(cm);
+ }
+
+ function guttersChanged(cm) {
+ updateGutters(cm);
+ regChange(cm);
+ setTimeout(function(){alignHorizontally(cm);}, 20);
+ }
+
+ // Rebuild the gutter elements, ensure the margin to the left of the
+ // code matches their width.
+ function updateGutters(cm) {
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
+ removeChildren(gutters);
+ for (var i = 0; i < specs.length; ++i) {
+ var gutterClass = specs[i];
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
+ if (gutterClass == "CodeMirror-linenumbers") {
+ cm.display.lineGutter = gElt;
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
+ }
+ }
+ gutters.style.display = i ? "" : "none";
+ var width = gutters.offsetWidth;
+ cm.display.sizer.style.marginLeft = width + "px";
+ if (i) cm.display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0;
+ }
+
+ // Compute the character length of a line, taking into account
+ // collapsed ranges (see markText) that might hide parts, and join
+ // other lines onto it.
+ function lineLength(line) {
+ if (line.height == 0) return 0;
+ var len = line.text.length, merged, cur = line;
+ while (merged = collapsedSpanAtStart(cur)) {
+ var found = merged.find(0, true);
+ cur = found.from.line;
+ len += found.from.ch - found.to.ch;
+ }
+ cur = line;
+ while (merged = collapsedSpanAtEnd(cur)) {
+ var found = merged.find(0, true);
+ len -= cur.text.length - found.from.ch;
+ cur = found.to.line;
+ len += cur.text.length - found.to.ch;
+ }
+ return len;
+ }
+
+ // Find the longest line in the document.
+ function findMaxLine(cm) {
+ var d = cm.display, doc = cm.doc;
+ d.maxLine = getLine(doc, doc.first);
+ d.maxLineLength = lineLength(d.maxLine);
+ d.maxLineChanged = true;
+ doc.iter(function(line) {
+ var len = lineLength(line);
+ if (len > d.maxLineLength) {
+ d.maxLineLength = len;
+ d.maxLine = line;
+ }
+ });
+ }
+
+ // Make sure the gutters options contains the element
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
+ function setGuttersForLineNumbers(options) {
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
+ if (found == -1 && options.lineNumbers) {
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
+ } else if (found > -1 && !options.lineNumbers) {
+ options.gutters = options.gutters.slice(0);
+ options.gutters.splice(found, 1);
+ }
+ }
+
+ // SCROLLBARS
+
+ // Prepare DOM reads needed to update the scrollbars. Done in one
+ // shot to minimize update/measure roundtrips.
+ function measureForScrollbars(cm) {
+ var scroll = cm.display.scroller;
+ return {
+ clientHeight: scroll.clientHeight,
+ barHeight: cm.display.scrollbarV.clientHeight,
+ scrollWidth: scroll.scrollWidth, clientWidth: scroll.clientWidth,
+ barWidth: cm.display.scrollbarH.clientWidth,
+ docHeight: Math.round(cm.doc.height + paddingVert(cm.display))
+ };
+ }
+
+ // Re-synchronize the fake scrollbars with the actual size of the
+ // content.
+ function updateScrollbars(cm, measure) {
+ if (!measure) measure = measureForScrollbars(cm);
+ var d = cm.display;
+ var scrollHeight = measure.docHeight + scrollerCutOff;
+ var needsH = measure.scrollWidth > measure.clientWidth;
+ var needsV = scrollHeight > measure.clientHeight;
+ if (needsV) {
+ d.scrollbarV.style.display = "block";
+ d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0";
+ // A bug in IE8 can cause this value to be negative, so guard it.
+ d.scrollbarV.firstChild.style.height =
+ Math.max(0, scrollHeight - measure.clientHeight + (measure.barHeight || d.scrollbarV.clientHeight)) + "px";
+ } else {
+ d.scrollbarV.style.display = "";
+ d.scrollbarV.firstChild.style.height = "0";
+ }
+ if (needsH) {
+ d.scrollbarH.style.display = "block";
+ d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0";
+ d.scrollbarH.firstChild.style.width =
+ (measure.scrollWidth - measure.clientWidth + (measure.barWidth || d.scrollbarH.clientWidth)) + "px";
+ } else {
+ d.scrollbarH.style.display = "";
+ d.scrollbarH.firstChild.style.width = "0";
+ }
+ if (needsH && needsV) {
+ d.scrollbarFiller.style.display = "block";
+ d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px";
+ } else d.scrollbarFiller.style.display = "";
+ if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
+ d.gutterFiller.style.display = "block";
+ d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px";
+ d.gutterFiller.style.width = d.gutters.offsetWidth + "px";
+ } else d.gutterFiller.style.display = "";
+
+ if (mac_geLion && scrollbarWidth(d.measure) === 0) {
+ d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px";
+ var barMouseDown = function(e) {
+ if (e_target(e) != d.scrollbarV && e_target(e) != d.scrollbarH)
+ operation(cm, onMouseDown)(e);
+ };
+ on(d.scrollbarV, "mousedown", barMouseDown);
+ on(d.scrollbarH, "mousedown", barMouseDown);
+ }
+ }
+
+ // Compute the lines that are visible in a given viewport (defaults
+ // the the current scroll position). viewPort may contain top,
+ // height, and ensure (see op.scrollToPos) properties.
+ function visibleLines(display, doc, viewPort) {
+ var top = viewPort && viewPort.top != null ? viewPort.top : display.scroller.scrollTop;
+ top = Math.floor(top - paddingTop(display));
+ var bottom = viewPort && viewPort.bottom != null ? viewPort.bottom : top + display.wrapper.clientHeight;
+
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
+ // forces those lines into the viewport (if possible).
+ if (viewPort && viewPort.ensure) {
+ var ensureFrom = viewPort.ensure.from.line, ensureTo = viewPort.ensure.to.line;
+ if (ensureFrom < from)
+ return {from: ensureFrom,
+ to: lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)};
+ if (Math.min(ensureTo, doc.lastLine()) >= to)
+ return {from: lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight),
+ to: ensureTo};
+ }
+ return {from: from, to: to};
+ }
+
+ // LINE NUMBERS
+
+ // Re-align line numbers and gutter marks to compensate for
+ // horizontal scrolling.
+ function alignHorizontally(cm) {
+ var display = cm.display, view = display.view;
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
+ for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
+ if (cm.options.fixedGutter && view[i].gutter)
+ view[i].gutter.style.left = left;
+ var align = view[i].alignable;
+ if (align) for (var j = 0; j < align.length; j++)
+ align[j].style.left = left;
+ }
+ if (cm.options.fixedGutter)
+ display.gutters.style.left = (comp + gutterW) + "px";
+ }
+
+ // Used to ensure that the line number gutter is still the right
+ // size for the current document size. Returns true when an update
+ // is needed.
+ function maybeUpdateLineNumberWidth(cm) {
+ if (!cm.options.lineNumbers) return false;
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
+ if (last.length != display.lineNumChars) {
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
+ display.lineGutter.style.width = "";
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
+ display.lineGutter.style.width = display.lineNumWidth + "px";
+ var width = display.gutters.offsetWidth;
+ display.scrollbarH.style.left = cm.options.fixedGutter ? width + "px" : 0;
+ display.sizer.style.marginLeft = width + "px";
+ return true;
+ }
+ return false;
+ }
+
+ function lineNumberFor(options, i) {
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
+ }
+
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
+ // but using getBoundingClientRect to get a sub-pixel-accurate
+ // result.
+ function compensateForHScroll(display) {
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
+ }
+
+ // DISPLAY DRAWING
+
+ // Updates the display, selection, and scrollbars, using the
+ // information in display.view to find out which nodes are no longer
+ // up-to-date. Tries to bail out early when no changes are needed,
+ // unless forced is true.
+ // Returns true if an actual update happened, false otherwise.
+ function updateDisplay(cm, viewPort, forced) {
+ var oldFrom = cm.display.viewFrom, oldTo = cm.display.viewTo, updated;
+ var visible = visibleLines(cm.display, cm.doc, viewPort);
+ for (var first = true;; first = false) {
+ var oldWidth = cm.display.scroller.clientWidth;
+ if (!updateDisplayInner(cm, visible, forced)) break;
+ updated = true;
+
+ // If the max line changed since it was last measured, measure it,
+ // and ensure the document's width matches it.
+ if (cm.display.maxLineChanged && !cm.options.lineWrapping)
+ adjustContentWidth(cm);
+
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ setDocumentHeight(cm, barMeasure);
+ updateScrollbars(cm, barMeasure);
+ if (first && cm.options.lineWrapping && oldWidth != cm.display.scroller.clientWidth) {
+ forced = true;
+ continue;
+ }
+ forced = false;
+
+ // Clip forced viewport to actual scrollable area.
+ if (viewPort && viewPort.top != null)
+ viewPort = {top: Math.min(barMeasure.docHeight - scrollerCutOff - barMeasure.clientHeight, viewPort.top)};
+ // Updated line heights might result in the drawn area not
+ // actually covering the viewport. Keep looping until it does.
+ visible = visibleLines(cm.display, cm.doc, viewPort);
+ if (visible.from >= cm.display.viewFrom && visible.to <= cm.display.viewTo)
+ break;
+ }
+
+ cm.display.updateLineNumbers = null;
+ if (updated) {
+ signalLater(cm, "update", cm);
+ if (cm.display.viewFrom != oldFrom || cm.display.viewTo != oldTo)
+ signalLater(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
+ }
+ return updated;
+ }
+
+ // Does the actual updating of the line display. Bails out
+ // (returning false) when there is nothing to be done and forced is
+ // false.
+ function updateDisplayInner(cm, visible, forced) {
+ var display = cm.display, doc = cm.doc;
+ if (!display.wrapper.offsetWidth) {
+ resetView(cm);
+ return;
+ }
+
+ // Bail out if the visible area is already rendered and nothing changed.
+ if (!forced && visible.from >= display.viewFrom && visible.to <= display.viewTo &&
+ countDirtyView(cm) == 0)
+ return;
+
+ if (maybeUpdateLineNumberWidth(cm))
+ resetView(cm);
+ var dims = getDimensions(cm);
+
+ // Compute a suitable new viewport (from & to)
+ var end = doc.first + doc.size;
+ var from = Math.max(visible.from - cm.options.viewportMargin, doc.first);
+ var to = Math.min(end, visible.to + cm.options.viewportMargin);
+ if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
+ if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
+ if (sawCollapsedSpans) {
+ from = visualLineNo(cm.doc, from);
+ to = visualLineEndNo(cm.doc, to);
+ }
+
+ var different = from != display.viewFrom || to != display.viewTo ||
+ display.lastSizeC != display.wrapper.clientHeight;
+ adjustView(cm, from, to);
+
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
+ // Position the mover div to align with the current scroll position
+ cm.display.mover.style.top = display.viewOffset + "px";
+
+ var toUpdate = countDirtyView(cm);
+ if (!different && toUpdate == 0 && !forced) return;
+
+ // For big changes, we hide the enclosing element during the
+ // update, since that speeds up the operations on most browsers.
+ var focused = activeElt();
+ if (toUpdate > 4) display.lineDiv.style.display = "none";
+ patchDisplay(cm, display.updateLineNumbers, dims);
+ if (toUpdate > 4) display.lineDiv.style.display = "";
+ // There might have been a widget with a focused element that got
+ // hidden or updated, if so re-focus it.
+ if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
+
+ // Prevent selection and cursors from interfering with the scroll
+ // width.
+ removeChildren(display.cursorDiv);
+ removeChildren(display.selectionDiv);
+
+ if (different) {
+ display.lastSizeC = display.wrapper.clientHeight;
+ startWorker(cm, 400);
+ }
+
+ updateHeightsInViewport(cm);
+
+ return true;
+ }
+
+ function adjustContentWidth(cm) {
+ var display = cm.display;
+ var width = measureChar(cm, display.maxLine, display.maxLine.text.length).left;
+ display.maxLineChanged = false;
+ var minWidth = Math.max(0, width + 3);
+ var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + minWidth + scrollerCutOff - display.scroller.clientWidth);
+ display.sizer.style.minWidth = minWidth + "px";
+ if (maxScrollLeft < cm.doc.scrollLeft)
+ setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true);
+ }
+
+ function setDocumentHeight(cm, measure) {
+ cm.display.sizer.style.minHeight = cm.display.heightForcer.style.top = measure.docHeight + "px";
+ cm.display.gutters.style.height = Math.max(measure.docHeight, measure.clientHeight - scrollerCutOff) + "px";
+ }
+
+ // Read the actual heights of the rendered lines, and update their
+ // stored heights to match.
+ function updateHeightsInViewport(cm) {
+ var display = cm.display;
+ var prevBottom = display.lineDiv.offsetTop;
+ for (var i = 0; i < display.view.length; i++) {
+ var cur = display.view[i], height;
+ if (cur.hidden) continue;
+ if (ie_upto7) {
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
+ height = bot - prevBottom;
+ prevBottom = bot;
+ } else {
+ var box = cur.node.getBoundingClientRect();
+ height = box.bottom - box.top;
+ }
+ var diff = cur.line.height - height;
+ if (height < 2) height = textHeight(display);
+ if (diff > .001 || diff < -.001) {
+ updateLineHeight(cur.line, height);
+ updateWidgetHeight(cur.line);
+ if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
+ updateWidgetHeight(cur.rest[j]);
+ }
+ }
+ }
+
+ // Read and store the height of line widgets associated with the
+ // given line.
+ function updateWidgetHeight(line) {
+ if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
+ line.widgets[i].height = line.widgets[i].node.offsetHeight;
+ }
+
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
+ // view, so that we don't interleave reading and writing to the DOM.
+ function getDimensions(cm) {
+ var d = cm.display, left = {}, width = {};
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+ left[cm.options.gutters[i]] = n.offsetLeft;
+ width[cm.options.gutters[i]] = n.offsetWidth;
+ }
+ return {fixedPos: compensateForHScroll(d),
+ gutterTotalWidth: d.gutters.offsetWidth,
+ gutterLeft: left,
+ gutterWidth: width,
+ wrapperWidth: d.wrapper.clientWidth};
+ }
+
+ // Sync the actual display DOM structure with display.view, removing
+ // nodes for lines that are no longer in view, and creating the ones
+ // that are not there yet, and updating the ones that are out of
+ // date.
+ function patchDisplay(cm, updateNumbersFrom, dims) {
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
+ var container = display.lineDiv, cur = container.firstChild;
+
+ function rm(node) {
+ var next = node.nextSibling;
+ // Works around a throw-scroll bug in OS X Webkit
+ if (webkit && mac && cm.display.currentWheelTarget == node)
+ node.style.display = "none";
+ else
+ node.parentNode.removeChild(node);
+ return next;
+ }
+
+ var view = display.view, lineN = display.viewFrom;
+ // Loop over the elements in the view, syncing cur (the DOM nodes
+ // in display.lineDiv) with the view as we go.
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (lineView.hidden) {
+ } else if (!lineView.node) { // Not drawn yet
+ var node = buildLineElement(cm, lineView, lineN, dims);
+ container.insertBefore(node, cur);
+ } else { // Already drawn
+ while (cur != lineView.node) cur = rm(cur);
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
+ updateNumbersFrom <= lineN && lineView.lineNumber;
+ if (lineView.changes) {
+ if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
+ updateLineForChanges(cm, lineView, lineN, dims);
+ }
+ if (updateNumber) {
+ removeChildren(lineView.lineNumber);
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
+ }
+ cur = lineView.node.nextSibling;
+ }
+ lineN += lineView.size;
+ }
+ while (cur) cur = rm(cur);
+ }
+
+ // When an aspect of a line changes, a string is added to
+ // lineView.changes. This updates the relevant part of the line's
+ // DOM structure.
+ function updateLineForChanges(cm, lineView, lineN, dims) {
+ for (var j = 0; j < lineView.changes.length; j++) {
+ var type = lineView.changes[j];
+ if (type == "text") updateLineText(cm, lineView);
+ else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
+ else if (type == "class") updateLineClasses(lineView);
+ else if (type == "widget") updateLineWidgets(lineView, dims);
+ }
+ lineView.changes = null;
+ }
+
+ // Lines with gutter elements, widgets or a background class need to
+ // be wrapped, and have the extra elements added to the wrapper div
+ function ensureLineWrapped(lineView) {
+ if (lineView.node == lineView.text) {
+ lineView.node = elt("div", null, null, "position: relative");
+ if (lineView.text.parentNode)
+ lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
+ lineView.node.appendChild(lineView.text);
+ if (ie_upto7) lineView.node.style.zIndex = 2;
+ }
+ return lineView.node;
+ }
+
+ function updateLineBackground(lineView) {
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
+ if (cls) cls += " CodeMirror-linebackground";
+ if (lineView.background) {
+ if (cls) lineView.background.className = cls;
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
+ } else if (cls) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
+ }
+ }
+
+ // Wrapper around buildLineContent which will reuse the structure
+ // in display.externalMeasured when possible.
+ function getLineContent(cm, lineView) {
+ var ext = cm.display.externalMeasured;
+ if (ext && ext.line == lineView.line) {
+ cm.display.externalMeasured = null;
+ lineView.measure = ext.measure;
+ return ext.built;
+ }
+ return buildLineContent(cm, lineView);
+ }
+
+ // Redraw the line's text. Interacts with the background and text
+ // classes because the mode may output tokens that influence these
+ // classes.
+ function updateLineText(cm, lineView) {
+ var cls = lineView.text.className;
+ var built = getLineContent(cm, lineView);
+ if (lineView.text == lineView.node) lineView.node = built.pre;
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
+ lineView.text = built.pre;
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
+ lineView.bgClass = built.bgClass;
+ lineView.textClass = built.textClass;
+ updateLineClasses(lineView);
+ } else if (cls) {
+ lineView.text.className = cls;
+ }
+ }
+
+ function updateLineClasses(lineView) {
+ updateLineBackground(lineView);
+ if (lineView.line.wrapClass)
+ ensureLineWrapped(lineView).className = lineView.line.wrapClass;
+ else if (lineView.node != lineView.text)
+ lineView.node.className = "";
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
+ lineView.text.className = textClass || "";
+ }
+
+ function updateLineGutter(cm, lineView, lineN, dims) {
+ if (lineView.gutter) {
+ lineView.node.removeChild(lineView.gutter);
+ lineView.gutter = null;
+ }
+ var markers = lineView.line.gutterMarkers;
+ if (cm.options.lineNumbers || markers) {
+ var wrap = ensureLineWrapped(lineView);
+ var gutterWrap = lineView.gutter =
+ wrap.insertBefore(elt("div", null, "CodeMirror-gutter-wrapper", "position: absolute; left: " +
+ (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"),
+ lineView.text);
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
+ lineView.lineNumber = gutterWrap.appendChild(
+ elt("div", lineNumberFor(cm.options, lineN),
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
+ + cm.display.lineNumInnerWidth + "px"));
+ if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
+ if (found)
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
+ }
+ }
+ }
+
+ function updateLineWidgets(lineView, dims) {
+ if (lineView.alignable) lineView.alignable = null;
+ for (var node = lineView.node.firstChild, next; node; node = next) {
+ var next = node.nextSibling;
+ if (node.className == "CodeMirror-linewidget")
+ lineView.node.removeChild(node);
+ }
+ insertLineWidgets(lineView, dims);
+ }
+
+ // Build a line's DOM representation from scratch
+ function buildLineElement(cm, lineView, lineN, dims) {
+ var built = getLineContent(cm, lineView);
+ lineView.text = lineView.node = built.pre;
+ if (built.bgClass) lineView.bgClass = built.bgClass;
+ if (built.textClass) lineView.textClass = built.textClass;
+
+ updateLineClasses(lineView);
+ updateLineGutter(cm, lineView, lineN, dims);
+ insertLineWidgets(lineView, dims);
+ return lineView.node;
+ }
+
+ // A lineView may contain multiple logical lines (when merged by
+ // collapsed spans). The widgets for all of them need to be drawn.
+ function insertLineWidgets(lineView, dims) {
+ insertLineWidgetsFor(lineView.line, lineView, dims, true);
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
+ insertLineWidgetsFor(lineView.rest[i], lineView, dims, false);
+ }
+
+ function insertLineWidgetsFor(line, lineView, dims, allowAbove) {
+ if (!line.widgets) return;
+ var wrap = ensureLineWrapped(lineView);
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
+ if (!widget.handleMouseEvents) node.ignoreEvents = true;
+ positionLineWidget(widget, node, lineView, dims);
+ if (allowAbove && widget.above)
+ wrap.insertBefore(node, lineView.gutter || lineView.text);
+ else
+ wrap.appendChild(node);
+ signalLater(widget, "redraw");
+ }
+ }
+
+ function positionLineWidget(widget, node, lineView, dims) {
+ if (widget.noHScroll) {
+ (lineView.alignable || (lineView.alignable = [])).push(node);
+ var width = dims.wrapperWidth;
+ node.style.left = dims.fixedPos + "px";
+ if (!widget.coverGutter) {
+ width -= dims.gutterTotalWidth;
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
+ }
+ node.style.width = width + "px";
+ }
+ if (widget.coverGutter) {
+ node.style.zIndex = 5;
+ node.style.position = "relative";
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
+ }
+ }
+
+ // POSITION OBJECT
+
+ // A Pos instance represents a position within the text.
+ var Pos = CodeMirror.Pos = function(line, ch) {
+ if (!(this instanceof Pos)) return new Pos(line, ch);
+ this.line = line; this.ch = ch;
+ };
+
+ // Compare two positions, return 0 if they are the same, a negative
+ // number when a is less, and a positive number otherwise.
+ var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
+
+ function copyPos(x) {return Pos(x.line, x.ch);}
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
+
+ // SELECTION / CURSOR
+
+ // Selection objects are immutable. A new one is created every time
+ // the selection changes. A selection is one or more non-overlapping
+ // (and non-touching) ranges, sorted, and an integer that indicates
+ // which one is the primary selection (the one that's scrolled into
+ // view, that getCursor returns, etc).
+ function Selection(ranges, primIndex) {
+ this.ranges = ranges;
+ this.primIndex = primIndex;
+ }
+
+ Selection.prototype = {
+ primary: function() { return this.ranges[this.primIndex]; },
+ equals: function(other) {
+ if (other == this) return true;
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
+ for (var i = 0; i < this.ranges.length; i++) {
+ var here = this.ranges[i], there = other.ranges[i];
+ if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
+ }
+ return true;
+ },
+ deepCopy: function() {
+ for (var out = [], i = 0; i < this.ranges.length; i++)
+ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
+ return new Selection(out, this.primIndex);
+ },
+ somethingSelected: function() {
+ for (var i = 0; i < this.ranges.length; i++)
+ if (!this.ranges[i].empty()) return true;
+ return false;
+ },
+ contains: function(pos, end) {
+ if (!end) end = pos;
+ for (var i = 0; i < this.ranges.length; i++) {
+ var range = this.ranges[i];
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
+ return i;
+ }
+ return -1;
+ }
+ };
+
+ function Range(anchor, head) {
+ this.anchor = anchor; this.head = head;
+ }
+
+ Range.prototype = {
+ from: function() { return minPos(this.anchor, this.head); },
+ to: function() { return maxPos(this.anchor, this.head); },
+ empty: function() {
+ return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
+ }
+ };
+
+ // Take an unsorted, potentially overlapping set of ranges, and
+ // build a selection out of it. 'Consumes' ranges array (modifying
+ // it).
+ function normalizeSelection(ranges, primIndex) {
+ var prim = ranges[primIndex];
+ ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
+ primIndex = indexOf(ranges, prim);
+ for (var i = 1; i < ranges.length; i++) {
+ var cur = ranges[i], prev = ranges[i - 1];
+ if (cmp(prev.to(), cur.from()) >= 0) {
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
+ if (i <= primIndex) --primIndex;
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
+ }
+ }
+ return new Selection(ranges, primIndex);
+ }
+
+ function simpleSelection(anchor, head) {
+ return new Selection([new Range(anchor, head || anchor)], 0);
+ }
+
+ // Most of the external API clips given positions to make sure they
+ // actually exist within the document.
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
+ function clipPos(doc, pos) {
+ if (pos.line < doc.first) return Pos(doc.first, 0);
+ var last = doc.first + doc.size - 1;
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
+ }
+ function clipToLen(pos, linelen) {
+ var ch = pos.ch;
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
+ else if (ch < 0) return Pos(pos.line, 0);
+ else return pos;
+ }
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
+ function clipPosArray(doc, array) {
+ for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
+ return out;
+ }
+
+ // SELECTION UPDATES
+
+ // The 'scroll' parameter given to many of these indicated whether
+ // the new cursor position should be scrolled into view after
+ // modifying the selection.
+
+ // If shift is held or the extend flag is set, extends a range to
+ // include a given position (and optionally a second position).
+ // Otherwise, simply returns the range between the given positions.
+ // Used for cursor motion and such.
+ function extendRange(doc, range, head, other) {
+ if (doc.cm && doc.cm.display.shift || doc.extend) {
+ var anchor = range.anchor;
+ if (other) {
+ var posBefore = cmp(head, anchor) < 0;
+ if (posBefore != (cmp(other, anchor) < 0)) {
+ anchor = head;
+ head = other;
+ } else if (posBefore != (cmp(head, other) < 0)) {
+ head = other;
+ }
+ }
+ return new Range(anchor, head);
+ } else {
+ return new Range(other || head, head);
+ }
+ }
+
+ // Extend the primary selection range, discard the rest.
+ function extendSelection(doc, head, other, options) {
+ setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
+ }
+
+ // Extend all selections (pos is an array of selections with length
+ // equal the number of selections)
+ function extendSelections(doc, heads, options) {
+ for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
+ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
+ setSelection(doc, newSel, options);
+ }
+
+ // Updates a single range in the selection.
+ function replaceOneSelection(doc, i, range, options) {
+ var ranges = doc.sel.ranges.slice(0);
+ ranges[i] = range;
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
+ }
+
+ // Reset the selection to a single range.
+ function setSimpleSelection(doc, anchor, head, options) {
+ setSelection(doc, simpleSelection(anchor, head), options);
+ }
+
+ // Give beforeSelectionChange handlers a change to influence a
+ // selection update.
+ function filterSelectionChange(doc, sel) {
+ var obj = {
+ ranges: sel.ranges,
+ update: function(ranges) {
+ this.ranges = [];
+ for (var i = 0; i < ranges.length; i++)
+ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
+ clipPos(doc, ranges[i].head));
+ }
+ };
+ signal(doc, "beforeSelectionChange", doc, obj);
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
+ if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
+ else return sel;
+ }
+
+ function setSelectionReplaceHistory(doc, sel, options) {
+ var done = doc.history.done, last = lst(done);
+ if (last && last.ranges) {
+ done[done.length - 1] = sel;
+ setSelectionNoUndo(doc, sel, options);
+ } else {
+ setSelection(doc, sel, options);
+ }
+ }
+
+ // Set a new selection.
+ function setSelection(doc, sel, options) {
+ setSelectionNoUndo(doc, sel, options);
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
+ }
+
+ function setSelectionNoUndo(doc, sel, options) {
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
+ sel = filterSelectionChange(doc, sel);
+
+ var bias = cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1;
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
+
+ if (!(options && options.scroll === false) && doc.cm)
+ ensureCursorVisible(doc.cm);
+ }
+
+ function setSelectionInner(doc, sel) {
+ if (sel.equals(doc.sel)) return;
+
+ doc.sel = sel;
+
+ if (doc.cm)
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged =
+ doc.cm.curOp.cursorActivity = true;
+ signalLater(doc, "cursorActivity", doc);
+ }
+
+ // Verify that the selection does not partially select any atomic
+ // marked ranges.
+ function reCheckSelection(doc) {
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
+ }
+
+ // Return a selection that does not partially select any atomic
+ // ranges.
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
+ var out;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range = sel.ranges[i];
+ var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
+ var newHead = skipAtomic(doc, range.head, bias, mayClear);
+ if (out || newAnchor != range.anchor || newHead != range.head) {
+ if (!out) out = sel.ranges.slice(0, i);
+ out[i] = new Range(newAnchor, newHead);
+ }
+ }
+ return out ? normalizeSelection(out, sel.primIndex) : sel;
+ }
+
+ // Ensure a given position is not inside an atomic range.
+ function skipAtomic(doc, pos, bias, mayClear) {
+ var flipped = false, curPos = pos;
+ var dir = bias || 1;
+ doc.cantEdit = false;
+ search: for (;;) {
+ var line = getLine(doc, curPos.line);
+ if (line.markedSpans) {
+ for (var i = 0; i < line.markedSpans.length; ++i) {
+ var sp = line.markedSpans[i], m = sp.marker;
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
+ (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
+ if (mayClear) {
+ signal(m, "beforeCursorEnter");
+ if (m.explicitlyCleared) {
+ if (!line.markedSpans) break;
+ else {--i; continue;}
+ }
+ }
+ if (!m.atomic) continue;
+ var newPos = m.find(dir < 0 ? -1 : 1);
+ if (cmp(newPos, curPos) == 0) {
+ newPos.ch += dir;
+ if (newPos.ch < 0) {
+ if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
+ else newPos = null;
+ } else if (newPos.ch > line.text.length) {
+ if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
+ else newPos = null;
+ }
+ if (!newPos) {
+ if (flipped) {
+ // Driven in a corner -- no valid cursor position found at all
+ // -- try again *with* clearing, if we didn't already
+ if (!mayClear) return skipAtomic(doc, pos, bias, true);
+ // Otherwise, turn off editing until further notice, and return the start of the doc
+ doc.cantEdit = true;
+ return Pos(doc.first, 0);
+ }
+ flipped = true; newPos = pos; dir = -dir;
+ }
+ }
+ curPos = newPos;
+ continue search;
+ }
+ }
+ }
+ return curPos;
+ }
+ }
+
+ // SELECTION DRAWING
+
+ // Redraw the selection and/or cursor
+ function updateSelection(cm) {
+ var display = cm.display, doc = cm.doc;
+ var curFragment = document.createDocumentFragment();
+ var selFragment = document.createDocumentFragment();
+
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ var collapsed = range.empty();
+ if (collapsed || cm.options.showCursorWhenSelecting)
+ updateSelectionCursor(cm, range, curFragment);
+ if (!collapsed)
+ updateSelectionRange(cm, range, selFragment);
+ }
+
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
+ if (cm.options.moveInputWithCursor) {
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
+ var top = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
+ headPos.top + lineOff.top - wrapOff.top));
+ var left = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
+ headPos.left + lineOff.left - wrapOff.left));
+ display.inputDiv.style.top = top + "px";
+ display.inputDiv.style.left = left + "px";
+ }
+
+ removeChildrenAndAdd(display.cursorDiv, curFragment);
+ removeChildrenAndAdd(display.selectionDiv, selFragment);
+ }
+
+ // Draws a cursor for the given range
+ function updateSelectionCursor(cm, range, output) {
+ var pos = cursorCoords(cm, range.head, "div");
+
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
+ cursor.style.left = pos.left + "px";
+ cursor.style.top = pos.top + "px";
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
+
+ if (pos.other) {
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
+ otherCursor.style.display = "";
+ otherCursor.style.left = pos.other.left + "px";
+ otherCursor.style.top = pos.other.top + "px";
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
+ }
+ }
+
+ // Draws the given range as a highlighted selection
+ function updateSelectionRange(cm, range, output) {
+ var display = cm.display, doc = cm.doc;
+ var fragment = document.createDocumentFragment();
+ var padding = paddingH(cm.display), leftSide = padding.left, rightSide = display.lineSpace.offsetWidth - padding.right;
+
+ function add(left, top, width, bottom) {
+ if (top < 0) top = 0;
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
+ "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
+ "px; height: " + (bottom - top) + "px"));
+ }
+
+ function drawForLine(line, fromArg, toArg) {
+ var lineObj = getLine(doc, line);
+ var lineLen = lineObj.text.length;
+ var start, end;
+ function coords(ch, bias) {
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
+ }
+
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
+ var leftPos = coords(from, "left"), rightPos, left, right;
+ if (from == to) {
+ rightPos = leftPos;
+ left = right = leftPos.left;
+ } else {
+ rightPos = coords(to - 1, "right");
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
+ left = leftPos.left;
+ right = rightPos.right;
+ }
+ if (fromArg == null && from == 0) left = leftSide;
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
+ add(left, leftPos.top, null, leftPos.bottom);
+ left = leftSide;
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
+ }
+ if (toArg == null && to == lineLen) right = rightSide;
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
+ start = leftPos;
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
+ end = rightPos;
+ if (left < leftSide + 1) left = leftSide;
+ add(left, rightPos.top, right - left, rightPos.bottom);
+ });
+ return {start: start, end: end};
+ }
+
+ var sFrom = range.from(), sTo = range.to();
+ if (sFrom.line == sTo.line) {
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
+ } else {
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
+ if (singleVLine) {
+ if (leftEnd.top < rightStart.top - 2) {
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
+ } else {
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
+ }
+ }
+ if (leftEnd.bottom < rightStart.top)
+ add(leftSide, leftEnd.bottom, null, rightStart.top);
+ }
+
+ output.appendChild(fragment);
+ }
+
+ // Cursor-blinking
+ function restartBlink(cm) {
+ if (!cm.state.focused) return;
+ var display = cm.display;
+ clearInterval(display.blinker);
+ var on = true;
+ display.cursorDiv.style.visibility = "";
+ if (cm.options.cursorBlinkRate > 0)
+ display.blinker = setInterval(function() {
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
+ }, cm.options.cursorBlinkRate);
+ }
+
+ // HIGHLIGHT WORKER
+
+ function startWorker(cm, time) {
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
+ }
+
+ function highlightWorker(cm) {
+ var doc = cm.doc;
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
+ if (doc.frontier >= cm.display.viewTo) return;
+ var end = +new Date + cm.options.workTime;
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
+
+ runInOp(cm, function() {
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
+ if (doc.frontier >= cm.display.viewFrom) { // Visible
+ var oldStyles = line.styles;
+ line.styles = highlightLine(cm, line, state, true);
+ var ischange = !oldStyles || oldStyles.length != line.styles.length;
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
+ if (ischange) regLineChange(cm, doc.frontier, "text");
+ line.stateAfter = copyState(doc.mode, state);
+ } else {
+ processLine(cm, line.text, state);
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
+ }
+ ++doc.frontier;
+ if (+new Date > end) {
+ startWorker(cm, cm.options.workDelay);
+ return true;
+ }
+ });
+ });
+ }
+
+ // Finds the line to start with when starting a parse. Tries to
+ // find a line with a stateAfter, so that it can start with a
+ // valid state. If that fails, it returns the line with the
+ // smallest indentation, which tends to need the least context to
+ // parse correctly.
+ function findStartLine(cm, n, precise) {
+ var minindent, minline, doc = cm.doc;
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
+ for (var search = n; search > lim; --search) {
+ if (search <= doc.first) return doc.first;
+ var line = getLine(doc, search - 1);
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
+ var indented = countColumn(line.text, null, cm.options.tabSize);
+ if (minline == null || minindent > indented) {
+ minline = search - 1;
+ minindent = indented;
+ }
+ }
+ return minline;
+ }
+
+ function getStateBefore(cm, n, precise) {
+ var doc = cm.doc, display = cm.display;
+ if (!doc.mode.startState) return true;
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
+ if (!state) state = startState(doc.mode);
+ else state = copyState(doc.mode, state);
+ doc.iter(pos, n, function(line) {
+ processLine(cm, line.text, state);
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
+ ++pos;
+ });
+ if (precise) doc.frontier = pos;
+ return state;
+ }
+
+ // POSITION MEASUREMENT
+
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
+ function paddingH(display) {
+ if (display.cachedPaddingH) return display.cachedPaddingH;
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
+ return display.cachedPaddingH = {left: parseInt(style.paddingLeft),
+ right: parseInt(style.paddingRight)};
+ }
+
+ // Ensure the lineView.wrapping.heights array is populated. This is
+ // an array of bottom offsets for the lines that make up a drawn
+ // line. When lineWrapping is on, there might be more than one
+ // height.
+ function ensureLineHeights(cm, lineView, rect) {
+ var wrapping = cm.options.lineWrapping;
+ var curWidth = wrapping && cm.display.scroller.clientWidth;
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
+ var heights = lineView.measure.heights = [];
+ if (wrapping) {
+ lineView.measure.width = curWidth;
+ var rects = lineView.text.firstChild.getClientRects();
+ for (var i = 0; i < rects.length - 1; i++) {
+ var cur = rects[i], next = rects[i + 1];
+ if (Math.abs(cur.bottom - next.bottom) > 2)
+ heights.push((cur.bottom + next.top) / 2 - rect.top);
+ }
+ }
+ heights.push(rect.bottom - rect.top);
+ }
+ }
+
+ // Find a line map (mapping character offsets to text nodes) and a
+ // measurement cache for the given line number. (A line view might
+ // contain multiple lines when collapsed ranges are present.)
+ function mapFromLineView(lineView, line, lineN) {
+ if (lineView.line == line)
+ return {map: lineView.measure.map, cache: lineView.measure.cache};
+ for (var i = 0; i < lineView.rest.length; i++)
+ if (lineView.rest[i] == line)
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
+ for (var i = 0; i < lineView.rest.length; i++)
+ if (lineNo(lineView.rest[i]) > lineN)
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
+ }
+
+ // Render a line into the hidden node display.externalMeasured. Used
+ // when measurement is needed for a line that's not in the viewport.
+ function updateExternalMeasurement(cm, line) {
+ line = visualLine(line);
+ var lineN = lineNo(line);
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
+ view.lineN = lineN;
+ var built = view.built = buildLineContent(cm, view);
+ view.text = built.pre;
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
+ return view;
+ }
+
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
+ // for a given character.
+ function measureChar(cm, line, ch, bias) {
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
+ }
+
+ // Find a line view that corresponds to the given line number.
+ function findViewForLine(cm, lineN) {
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
+ return cm.display.view[findViewIndex(cm, lineN)];
+ var ext = cm.display.externalMeasured;
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
+ return ext;
+ }
+
+ // Measurement can be split in two steps, the set-up work that
+ // applies to the whole line, and the measurement of the actual
+ // character. Functions like coordsChar, that need to do a lot of
+ // measurements in a row, can thus ensure that the set-up work is
+ // only done once.
+ function prepareMeasureForLine(cm, line) {
+ var lineN = lineNo(line);
+ var view = findViewForLine(cm, lineN);
+ if (view && !view.text)
+ view = null;
+ else if (view && view.changes)
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
+ if (!view)
+ view = updateExternalMeasurement(cm, line);
+
+ var info = mapFromLineView(view, line, lineN);
+ return {
+ line: line, view: view, rect: null,
+ map: info.map, cache: info.cache, before: info.before,
+ hasHeights: false
+ };
+ }
+
+ // Given a prepared measurement object, measures the position of an
+ // actual character (or fetches it from the cache).
+ function measureCharPrepared(cm, prepared, ch, bias) {
+ if (prepared.before) ch = -1;
+ var key = ch + (bias || ""), found;
+ if (prepared.cache.hasOwnProperty(key)) {
+ found = prepared.cache[key];
+ } else {
+ if (!prepared.rect)
+ prepared.rect = prepared.view.text.getBoundingClientRect();
+ if (!prepared.hasHeights) {
+ ensureLineHeights(cm, prepared.view, prepared.rect);
+ prepared.hasHeights = true;
+ }
+ found = measureCharInner(cm, prepared, ch, bias);
+ if (!found.bogus) prepared.cache[key] = found;
+ }
+ return {left: found.left, right: found.right, top: found.top, bottom: found.bottom};
+ }
+
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
+
+ function measureCharInner(cm, prepared, ch, bias) {
+ var map = prepared.map;
+
+ var node, start, end, collapse;
+ // First, search the line map for the text node corresponding to,
+ // or closest to, the target character.
+ for (var i = 0; i < map.length; i += 3) {
+ var mStart = map[i], mEnd = map[i + 1];
+ if (ch < mStart) {
+ start = 0; end = 1;
+ collapse = "left";
+ } else if (ch < mEnd) {
+ start = ch - mStart;
+ end = start + 1;
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
+ end = mEnd - mStart;
+ start = end - 1;
+ if (ch >= mEnd) collapse = "right";
+ }
+ if (start != null) {
+ node = map[i + 2];
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
+ collapse = bias;
+ if (bias == "left" && start == 0)
+ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
+ node = map[(i -= 3) + 2];
+ collapse = "left";
+ }
+ if (bias == "right" && start == mEnd - mStart)
+ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
+ node = map[(i += 3) + 2];
+ collapse = "right";
+ }
+ break;
+ }
+ }
+
+ var rect;
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
+ while (start && isExtendingChar(prepared.line.text.charAt(mStart + start))) --start;
+ while (mStart + end < mEnd && isExtendingChar(prepared.line.text.charAt(mStart + end))) ++end;
+ if (ie_upto8 && start == 0 && end == mEnd - mStart) {
+ rect = node.parentNode.getBoundingClientRect();
+ } else if (ie && cm.options.lineWrapping) {
+ var rects = range(node, start, end).getClientRects();
+ if (rects.length)
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
+ else
+ rect = nullRect;
+ } else {
+ rect = range(node, start, end).getBoundingClientRect();
+ }
+ } else { // If it is a widget, simply get the box for the whole widget.
+ if (start > 0) collapse = bias = "right";
+ var rects;
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
+ else
+ rect = node.getBoundingClientRect();
+ }
+ if (ie_upto8 && !start && (!rect || !rect.left && !rect.right)) {
+ var rSpan = node.parentNode.getClientRects()[0];
+ if (rSpan)
+ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
+ else
+ rect = nullRect;
+ }
+
+ var top, bot = (rect.bottom + rect.top) / 2 - prepared.rect.top;
+ var heights = prepared.view.measure.heights;
+ for (var i = 0; i < heights.length - 1; i++)
+ if (bot < heights[i]) break;
+ top = i ? heights[i - 1] : 0; bot = heights[i];
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
+ top: top, bottom: bot};
+ if (!rect.left && !rect.right) result.bogus = true;
+ return result;
+ }
+
+ function clearLineMeasurementCacheFor(lineView) {
+ if (lineView.measure) {
+ lineView.measure.cache = {};
+ lineView.measure.heights = null;
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
+ lineView.measure.caches[i] = {};
+ }
+ }
+
+ function clearLineMeasurementCache(cm) {
+ cm.display.externalMeasure = null;
+ removeChildren(cm.display.lineMeasure);
+ for (var i = 0; i < cm.display.view.length; i++)
+ clearLineMeasurementCacheFor(cm.display.view[i]);
+ }
+
+ function clearCaches(cm) {
+ clearLineMeasurementCache(cm);
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
+ cm.display.lineNumChars = null;
+ }
+
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
+
+ // Converts a {top, bottom, left, right} box from line-local
+ // coordinates into another coordinate system. Context may be one of
+ // "line", "div" (display.lineDiv), "local"/null (editor), or "page".
+ function intoCoordSystem(cm, lineObj, rect, context) {
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
+ var size = widgetHeight(lineObj.widgets[i]);
+ rect.top += size; rect.bottom += size;
+ }
+ if (context == "line") return rect;
+ if (!context) context = "local";
+ var yOff = heightAtLine(lineObj);
+ if (context == "local") yOff += paddingTop(cm.display);
+ else yOff -= cm.display.viewOffset;
+ if (context == "page" || context == "window") {
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
+ rect.left += xOff; rect.right += xOff;
+ }
+ rect.top += yOff; rect.bottom += yOff;
+ return rect;
+ }
+
+ // Coverts a box from "div" coords to another coordinate system.
+ // Context may be "window", "page", "div", or "local"/null.
+ function fromCoordSystem(cm, coords, context) {
+ if (context == "div") return coords;
+ var left = coords.left, top = coords.top;
+ // First move into "page" coordinate system
+ if (context == "page") {
+ left -= pageScrollX();
+ top -= pageScrollY();
+ } else if (context == "local" || !context) {
+ var localBox = cm.display.sizer.getBoundingClientRect();
+ left += localBox.left;
+ top += localBox.top;
+ }
+
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
+ }
+
+ function charCoords(cm, pos, context, lineObj, bias) {
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
+ }
+
+ // Returns a box for a given cursor position, which may have an
+ // 'other' property containing the position of the secondary cursor
+ // on a bidi boundary.
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure) {
+ lineObj = lineObj || getLine(cm.doc, pos.line);
+ if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
+ function get(ch, right) {
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left");
+ if (right) m.left = m.right; else m.right = m.left;
+ return intoCoordSystem(cm, lineObj, m, context);
+ }
+ function getBidi(ch, partPos) {
+ var part = order[partPos], right = part.level % 2;
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
+ part = order[--partPos];
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
+ right = true;
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
+ part = order[++partPos];
+ ch = bidiLeft(part) - part.level % 2;
+ right = false;
+ }
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
+ return get(ch, right);
+ }
+ var order = getOrder(lineObj), ch = pos.ch;
+ if (!order) return get(ch);
+ var partPos = getBidiPartAt(order, ch);
+ var val = getBidi(ch, partPos);
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
+ return val;
+ }
+
+ // Used to cheaply estimate the coordinates for a position. Used for
+ // intermediate scroll updates.
+ function estimateCoords(cm, pos) {
+ var left = 0, pos = clipPos(cm.doc, pos);
+ if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
+ var lineObj = getLine(cm.doc, pos.line);
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
+ return {left: left, right: left, top: top, bottom: top + lineObj.height};
+ }
+
+ // Positions returned by coordsChar contain some extra information.
+ // xRel is the relative x position of the input coordinates compared
+ // to the found position (so xRel > 0 means the coordinates are to
+ // the right of the character position, for example). When outside
+ // is true, that means the coordinates lie outside the line's
+ // vertical range.
+ function PosWithInfo(line, ch, outside, xRel) {
+ var pos = Pos(line, ch);
+ pos.xRel = xRel;
+ if (outside) pos.outside = true;
+ return pos;
+ }
+
+ // Compute the character position closest to the given coordinates.
+ // Input must be lineSpace-local ("div" coordinate system).
+ function coordsChar(cm, x, y) {
+ var doc = cm.doc;
+ y += cm.display.viewOffset;
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
+ if (lineN > last)
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
+ if (x < 0) x = 0;
+
+ var lineObj = getLine(doc, lineN);
+ for (;;) {
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
+ var merged = collapsedSpanAtEnd(lineObj);
+ var mergedPos = merged && merged.find(0, true);
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
+ lineN = lineNo(lineObj = mergedPos.to.line);
+ else
+ return found;
+ }
+ }
+
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
+ var innerOff = y - heightAtLine(lineObj);
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
+
+ function getX(ch) {
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
+ wrongLine = true;
+ if (innerOff > sp.bottom) return sp.left - adjust;
+ else if (innerOff < sp.top) return sp.left + adjust;
+ else wrongLine = false;
+ return sp.left;
+ }
+
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
+
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
+ // Do a binary search between these bounds.
+ for (;;) {
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
+ var xDiff = x - (ch == from ? fromX : toX);
+ while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
+ var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
+ xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
+ return pos;
+ }
+ var step = Math.ceil(dist / 2), middle = from + step;
+ if (bidi) {
+ middle = from;
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
+ }
+ var middleX = getX(middle);
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
+ }
+ }
+
+ var measureText;
+ // Compute the default text height.
+ function textHeight(display) {
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
+ if (measureText == null) {
+ measureText = elt("pre");
+ // Measure a bunch of lines, for browsers that compute
+ // fractional heights.
+ for (var i = 0; i < 49; ++i) {
+ measureText.appendChild(document.createTextNode("x"));
+ measureText.appendChild(elt("br"));
+ }
+ measureText.appendChild(document.createTextNode("x"));
+ }
+ removeChildrenAndAdd(display.measure, measureText);
+ var height = measureText.offsetHeight / 50;
+ if (height > 3) display.cachedTextHeight = height;
+ removeChildren(display.measure);
+ return height || 1;
+ }
+
+ // Compute the default character width.
+ function charWidth(display) {
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
+ var anchor = elt("span", "xxxxxxxxxx");
+ var pre = elt("pre", [anchor]);
+ removeChildrenAndAdd(display.measure, pre);
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
+ if (width > 2) display.cachedCharWidth = width;
+ return width || 10;
+ }
+
+ // OPERATIONS
+
+ // Operations are used to wrap a series of changes to the editor
+ // state in such a way that each change won't have to update the
+ // cursor and display (which would be awkward, slow, and
+ // error-prone). Instead, display updates are batched and then all
+ // combined and executed at once.
+
+ var nextOpId = 0;
+ // Start a new operation.
+ function startOperation(cm) {
+ cm.curOp = {
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
+ forceUpdate: false, // Used to force a redraw
+ updateInput: null, // Whether to reset the input textarea
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
+ changeObjs: null, // Accumulated changes, for firing change events
+ cursorActivity: false, // Whether to fire a cursorActivity event
+ selectionChanged: false, // Whether the selection needs to be redrawn
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
+ scrollToPos: null, // Used to scroll to a specific position
+ id: ++nextOpId // Unique ID
+ };
+ if (!delayedCallbackDepth++) delayedCallbacks = [];
+ }
+
+ // Finish an operation, updating the display and signalling delayed events
+ function endOperation(cm) {
+ var op = cm.curOp, doc = cm.doc, display = cm.display;
+ cm.curOp = null;
+
+ if (op.updateMaxLine) findMaxLine(cm);
+
+ // If it looks like an update might be needed, call updateDisplay
+ if (op.viewChanged || op.forceUpdate || op.scrollTop != null ||
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
+ op.scrollToPos.to.line >= display.viewTo) ||
+ display.maxLineChanged && cm.options.lineWrapping) {
+ var updated = updateDisplay(cm, {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
+ if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop;
+ }
+ // If no update was run, but the selection changed, redraw that.
+ if (!updated && op.selectionChanged) updateSelection(cm);
+ if (!updated && op.startHeight != cm.doc.height) updateScrollbars(cm);
+
+ // Propagate the scroll position to the actual DOM scroller
+ if (op.scrollTop != null && display.scroller.scrollTop != op.scrollTop) {
+ var top = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
+ display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = top;
+ }
+ if (op.scrollLeft != null && display.scroller.scrollLeft != op.scrollLeft) {
+ var left = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
+ display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = left;
+ alignHorizontally(cm);
+ }
+ // If we need to scroll a specific position into view, do so.
+ if (op.scrollToPos) {
+ var coords = scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos.from),
+ clipPos(cm.doc, op.scrollToPos.to), op.scrollToPos.margin);
+ if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
+ }
+
+ if (op.selectionChanged) restartBlink(cm);
+
+ if (cm.state.focused && op.updateInput)
+ resetInput(cm, op.typing);
+
+ // Fire events for markers that are hidden/unidden by editing or
+ // undoing
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
+
+ var delayed;
+ if (!--delayedCallbackDepth) {
+ delayed = delayedCallbacks;
+ delayedCallbacks = null;
+ }
+ // Fire change events, and delayed event handlers
+ if (op.changeObjs) {
+ for (var i = 0; i < op.changeObjs.length; i++)
+ signal(cm, "change", cm, op.changeObjs[i]);
+ signal(cm, "changes", cm, op.changeObjs);
+ }
+ if (op.cursorActivity) signal(cm, "cursorActivity", cm);
+ if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i]();
+ }
+
+ // Run the given function in an operation
+ function runInOp(cm, f) {
+ if (cm.curOp) return f();
+ startOperation(cm);
+ try { return f(); }
+ finally { endOperation(cm); }
+ }
+ // Wraps a function in an operation. Returns the wrapped function.
+ function operation(cm, f) {
+ return function() {
+ if (cm.curOp) return f.apply(cm, arguments);
+ startOperation(cm);
+ try { return f.apply(cm, arguments); }
+ finally { endOperation(cm); }
+ };
+ }
+ // Used to add methods to editor and doc instances, wrapping them in
+ // operations.
+ function methodOp(f) {
+ return function() {
+ if (this.curOp) return f.apply(this, arguments);
+ startOperation(this);
+ try { return f.apply(this, arguments); }
+ finally { endOperation(this); }
+ };
+ }
+ function docMethodOp(f) {
+ return function() {
+ var cm = this.cm;
+ if (!cm || cm.curOp) return f.apply(this, arguments);
+ startOperation(cm);
+ try { return f.apply(this, arguments); }
+ finally { endOperation(cm); }
+ };
+ }
+
+ // VIEW TRACKING
+
+ // These objects are used to represent the visible (currently drawn)
+ // part of the document. A LineView may correspond to multiple
+ // logical lines, if those are connected by collapsed ranges.
+ function LineView(doc, line, lineN) {
+ // The starting line
+ this.line = line;
+ // Continuing lines, if any
+ this.rest = visualLineContinued(line);
+ // Number of logical lines in this visual line
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
+ this.node = this.text = null;
+ this.hidden = lineIsHidden(doc, line);
+ }
+
+ // Create a range of LineView objects for the given lines.
+ function buildViewArray(cm, from, to) {
+ var array = [], nextPos;
+ for (var pos = from; pos < to; pos = nextPos) {
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
+ nextPos = pos + view.size;
+ array.push(view);
+ }
+ return array;
+ }
+
+ // Updates the display.view data structure for a given change to the
+ // document. From and to are in pre-change coordinates. Lendiff is
+ // the amount of lines added or subtracted by the change. This is
+ // used for changes that span multiple lines, or change the way
+ // lines are divided into visual lines. regLineChange (below)
+ // registers single-line changes.
+ function regChange(cm, from, to, lendiff) {
+ if (from == null) from = cm.doc.first;
+ if (to == null) to = cm.doc.first + cm.doc.size;
+ if (!lendiff) lendiff = 0;
+
+ var display = cm.display;
+ if (lendiff && to < display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
+ display.updateLineNumbers = from;
+
+ cm.curOp.viewChanged = true;
+
+ if (from >= display.viewTo) { // Change after
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
+ resetView(cm);
+ } else if (to <= display.viewFrom) { // Change before
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
+ resetView(cm);
+ } else {
+ display.viewFrom += lendiff;
+ display.viewTo += lendiff;
+ }
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
+ resetView(cm);
+ } else if (from <= display.viewFrom) { // Top overlap
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cut) {
+ display.view = display.view.slice(cut.index);
+ display.viewFrom = cut.lineN;
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
+ } else if (to >= display.viewTo) { // Bottom overlap
+ var cut = viewCuttingPoint(cm, from, from, -1);
+ if (cut) {
+ display.view = display.view.slice(0, cut.index);
+ display.viewTo = cut.lineN;
+ } else {
+ resetView(cm);
+ }
+ } else { // Gap in the middle
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cutTop && cutBot) {
+ display.view = display.view.slice(0, cutTop.index)
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
+ .concat(display.view.slice(cutBot.index));
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
+ }
+
+ var ext = display.externalMeasured;
+ if (ext) {
+ if (to < ext.lineN)
+ ext.lineN += lendiff;
+ else if (from < ext.lineN + ext.size)
+ display.externalMeasured = null;
+ }
+ }
+
+ // Register a change to a single line. Type must be one of "text",
+ // "gutter", "class", "widget"
+ function regLineChange(cm, line, type) {
+ cm.curOp.viewChanged = true;
+ var display = cm.display, ext = cm.display.externalMeasured;
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
+ display.externalMeasured = null;
+
+ if (line < display.viewFrom || line >= display.viewTo) return;
+ var lineView = display.view[findViewIndex(cm, line)];
+ if (lineView.node == null) return;
+ var arr = lineView.changes || (lineView.changes = []);
+ if (indexOf(arr, type) == -1) arr.push(type);
+ }
+
+ // Clear the view.
+ function resetView(cm) {
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
+ cm.display.view = [];
+ cm.display.viewOffset = 0;
+ }
+
+ // Find the view element corresponding to a given line. Return null
+ // when the line isn't visible.
+ function findViewIndex(cm, n) {
+ if (n >= cm.display.viewTo) return null;
+ n -= cm.display.viewFrom;
+ if (n < 0) return null;
+ var view = cm.display.view;
+ for (var i = 0; i < view.length; i++) {
+ n -= view[i].size;
+ if (n < 0) return i;
+ }
+ }
+
+ function viewCuttingPoint(cm, oldN, newN, dir) {
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
+ if (!sawCollapsedSpans) return {index: index, lineN: newN};
+ for (var i = 0, n = cm.display.viewFrom; i < index; i++)
+ n += view[i].size;
+ if (n != oldN) {
+ if (dir > 0) {
+ if (index == view.length - 1) return null;
+ diff = (n + view[index].size) - oldN;
+ index++;
+ } else {
+ diff = n - oldN;
+ }
+ oldN += diff; newN += diff;
+ }
+ while (visualLineNo(cm.doc, newN) != newN) {
+ if (index == (dir < 0 ? 0 : view.length - 1)) return null;
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
+ index += dir;
+ }
+ return {index: index, lineN: newN};
+ }
+
+ // Force the view to cover a given range, adding empty view element
+ // or clipping off existing ones as needed.
+ function adjustView(cm, from, to) {
+ var display = cm.display, view = display.view;
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
+ display.view = buildViewArray(cm, from, to);
+ display.viewFrom = from;
+ } else {
+ if (display.viewFrom > from)
+ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
+ else if (display.viewFrom < from)
+ display.view = display.view.slice(findViewIndex(cm, from));
+ display.viewFrom = from;
+ if (display.viewTo < to)
+ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
+ else if (display.viewTo > to)
+ display.view = display.view.slice(0, findViewIndex(cm, to));
+ }
+ display.viewTo = to;
+ }
+
+ // Count the number of lines in the view whose DOM representation is
+ // out of date (or nonexistent).
+ function countDirtyView(cm) {
+ var view = cm.display.view, dirty = 0;
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
+ }
+ return dirty;
+ }
+
+ // INPUT HANDLING
+
+ // Poll for input changes, using the normal rate of polling. This
+ // runs as long as the editor is focused.
+ function slowPoll(cm) {
+ if (cm.display.pollingFast) return;
+ cm.display.poll.set(cm.options.pollInterval, function() {
+ readInput(cm);
+ if (cm.state.focused) slowPoll(cm);
+ });
+ }
+
+ // When an event has just come in that is likely to add or change
+ // something in the input textarea, we poll faster, to ensure that
+ // the change appears on the screen quickly.
+ function fastPoll(cm) {
+ var missed = false;
+ cm.display.pollingFast = true;
+ function p() {
+ var changed = readInput(cm);
+ if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);}
+ else {cm.display.pollingFast = false; slowPoll(cm);}
+ }
+ cm.display.poll.set(20, p);
+ }
+
+ // Read input from the textarea, and update the document to match.
+ // When something is selected, it is present in the textarea, and
+ // selected (unless it is huge, in which case a placeholder is
+ // used). When nothing is selected, the cursor sits after previously
+ // seen text (can be empty), which is stored in prevInput (we must
+ // not reset the textarea when typing, because that breaks IME).
+ function readInput(cm) {
+ var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc;
+ // Since this is called a *lot*, try to bail out as cheaply as
+ // possible when it is clear that nothing happened. hasSelection
+ // will be the case when there is a lot of text in the textarea,
+ // in which case reading its value would be expensive.
+ if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.options.disableInput) return false;
+ var text = input.value;
+ // If nothing changed, bail.
+ if (text == prevInput && !cm.somethingSelected()) return false;
+ // Work around nonsensical selection resetting in IE9/10
+ if (ie && !ie_upto8 && cm.display.inputHasSelection === text) {
+ resetInput(cm);
+ return false;
+ }
+
+ var withOp = !cm.curOp;
+ if (withOp) startOperation(cm);
+ cm.display.shift = false;
+
+ // Find the part of the input that is actually new
+ var same = 0, l = Math.min(prevInput.length, text.length);
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
+ var inserted = text.slice(same), textLines = splitLines(inserted);
+
+ // When pasing N lines into N selections, insert one line per selection
+ var multiPaste = cm.state.pasteIncoming && textLines.length > 1 && doc.sel.ranges.length == textLines.length;
+
+ // Normal behavior is to insert the new text into every selection
+ for (var i = doc.sel.ranges.length - 1; i >= 0; i--) {
+ var range = doc.sel.ranges[i];
+ var from = range.from(), to = range.to();
+ // Handle deletion
+ if (same < prevInput.length)
+ from = Pos(from.line, from.ch - (prevInput.length - same));
+ // Handle overwrite
+ else if (cm.state.overwrite && range.empty() && !cm.state.pasteIncoming)
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
+ var updateInput = cm.curOp.updateInput;
+ var changeEvent = {from: from, to: to, text: multiPaste ? [textLines[i]] : textLines,
+ origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
+ makeChange(cm.doc, changeEvent);
+ signalLater(cm, "inputRead", cm, changeEvent);
+ // When an 'electric' character is inserted, immediately trigger a reindent
+ if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
+ cm.options.smartIndent && range.head.ch < 100 &&
+ (!i || doc.sel.ranges[i - 1].head.line != range.head.line)) {
+ var electric = cm.getModeAt(range.head).electricChars;
+ if (electric) for (var j = 0; j < electric.length; j++)
+ if (inserted.indexOf(electric.charAt(j)) > -1) {
+ indentLine(cm, range.head.line, "smart");
+ break;
+ }
+ }
+ }
+ ensureCursorVisible(cm);
+ cm.curOp.updateInput = updateInput;
+ cm.curOp.typing = true;
+
+ // Don't leave long text in the textarea, since it makes further polling slow
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = "";
+ else cm.display.prevInput = text;
+ if (withOp) endOperation(cm);
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
+ return true;
+ }
+
+ // Reset the input to correspond to the selection (or to be empty,
+ // when not typing and nothing is selected)
+ function resetInput(cm, typing) {
+ var minimal, selected, doc = cm.doc;
+ if (cm.somethingSelected()) {
+ cm.display.prevInput = "";
+ var range = doc.sel.primary();
+ minimal = hasCopyEvent &&
+ (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
+ var content = minimal ? "-" : selected || cm.getSelection();
+ cm.display.input.value = content;
+ if (cm.state.focused) selectInput(cm.display.input);
+ if (ie && !ie_upto8) cm.display.inputHasSelection = content;
+ } else if (!typing) {
+ cm.display.prevInput = cm.display.input.value = "";
+ if (ie && !ie_upto8) cm.display.inputHasSelection = null;
+ }
+ cm.display.inaccurateSelection = minimal;
+ }
+
+ function focusInput(cm) {
+ if (cm.options.readOnly != "nocursor" && (!mobile || activeElt() != cm.display.input))
+ cm.display.input.focus();
+ }
+
+ function ensureFocus(cm) {
+ if (!cm.state.focused) { focusInput(cm); onFocus(cm); }
+ }
+
+ function isReadOnly(cm) {
+ return cm.options.readOnly || cm.doc.cantEdit;
+ }
+
+ // EVENT HANDLERS
+
+ // Attach the necessary event handlers when initializing the editor
+ function registerEventHandlers(cm) {
+ var d = cm.display;
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
+ // Older IE's will not fire a second mousedown for a double click
+ if (ie_upto10)
+ on(d.scroller, "dblclick", operation(cm, function(e) {
+ if (signalDOMEvent(cm, e)) return;
+ var pos = posFromMouse(cm, e);
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
+ e_preventDefault(e);
+ var word = findWordAt(cm.doc, pos);
+ extendSelection(cm.doc, word.anchor, word.head);
+ }));
+ else
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
+ // Prevent normal selection in the editor (we handle our own)
+ on(d.lineSpace, "selectstart", function(e) {
+ if (!eventInWidget(d, e)) e_preventDefault(e);
+ });
+ // Some browsers fire contextmenu *after* opening the menu, at
+ // which point we can't mess with it anymore. Context menu is
+ // handled in onMouseDown for these browsers.
+ if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
+
+ // Sync scrolling between fake scrollbars and real scrollable
+ // area, ensure viewport is updated when scrolling.
+ on(d.scroller, "scroll", function() {
+ if (d.scroller.clientHeight) {
+ setScrollTop(cm, d.scroller.scrollTop);
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
+ signal(cm, "scroll", cm);
+ }
+ });
+ on(d.scrollbarV, "scroll", function() {
+ if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop);
+ });
+ on(d.scrollbarH, "scroll", function() {
+ if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft);
+ });
+
+ // Listen to wheel events in order to try and update the viewport on time.
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
+
+ // Prevent clicks in the scrollbars from killing focus
+ function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); }
+ on(d.scrollbarH, "mousedown", reFocus);
+ on(d.scrollbarV, "mousedown", reFocus);
+ // Prevent wrapper from ever scrolling
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+
+ // When the window resizes, we need to refresh active editors.
+ var resizeTimer;
+ function onResize() {
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
+ resizeTimer = null;
+ // Might be a text scaling operation, clear size caches.
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = knownScrollbarWidth = null;
+ cm.setSize();
+ }, 100);
+ }
+ on(window, "resize", onResize);
+ // The above handler holds on to the editor and its data
+ // structures. Here we poll to unregister it when the editor is no
+ // longer in the document, so that it can be garbage-collected.
+ function unregister() {
+ if (contains(document.body, d.wrapper)) setTimeout(unregister, 5000);
+ else off(window, "resize", onResize);
+ }
+ setTimeout(unregister, 5000);
+
+ on(d.input, "keyup", operation(cm, onKeyUp));
+ on(d.input, "input", function() {
+ if (ie && !ie_upto8 && cm.display.inputHasSelection) cm.display.inputHasSelection = null;
+ fastPoll(cm);
+ });
+ on(d.input, "keydown", operation(cm, onKeyDown));
+ on(d.input, "keypress", operation(cm, onKeyPress));
+ on(d.input, "focus", bind(onFocus, cm));
+ on(d.input, "blur", bind(onBlur, cm));
+
+ function drag_(e) {
+ if (!signalDOMEvent(cm, e)) e_stop(e);
+ }
+ if (cm.options.dragDrop) {
+ on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
+ on(d.scroller, "dragenter", drag_);
+ on(d.scroller, "dragover", drag_);
+ on(d.scroller, "drop", operation(cm, onDrop));
+ }
+ on(d.scroller, "paste", function(e) {
+ if (eventInWidget(d, e)) return;
+ cm.state.pasteIncoming = true;
+ focusInput(cm);
+ fastPoll(cm);
+ });
+ on(d.input, "paste", function() {
+ cm.state.pasteIncoming = true;
+ fastPoll(cm);
+ });
+
+ function prepareCopy(e) {
+ if (d.inaccurateSelection) {
+ d.prevInput = "";
+ d.inaccurateSelection = false;
+ d.input.value = cm.getSelection();
+ selectInput(d.input);
+ }
+ if (e.type == "cut") cm.state.cutIncoming = true;
+ }
+ on(d.input, "cut", prepareCopy);
+ on(d.input, "copy", prepareCopy);
+
+ // Needed to handle Tab key in KHTML
+ if (khtml) on(d.sizer, "mouseup", function() {
+ if (activeElt() == d.input) d.input.blur();
+ focusInput(cm);
+ });
+ }
+
+ // MOUSE EVENTS
+
+ // Return true when the given mouse event happened in a widget
+ function eventInWidget(display, e) {
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
+ if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true;
+ }
+ }
+
+ // Given a mouse event, find the corresponding position. If liberal
+ // is false, it checks whether a gutter or scrollbar was clicked,
+ // and returns null if it was. forRect is used by rectangular
+ // selections, and tries to estimate a character position even for
+ // coordinates beyond the right of the text.
+ function posFromMouse(cm, e, liberal, forRect) {
+ var display = cm.display;
+ if (!liberal) {
+ var target = e_target(e);
+ if (target == display.scrollbarH || target == display.scrollbarV ||
+ target == display.scrollbarFiller || target == display.gutterFiller) return null;
+ }
+ var x, y, space = display.lineSpace.getBoundingClientRect();
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
+ catch (e) { return null; }
+ var coords = coordsChar(cm, x, y), line;
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
+ coords = Pos(coords.line, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff);
+ }
+ return coords;
+ }
+
+ // A mouse down can be a single click, double click, triple click,
+ // start of selection drag, start of text drag, new cursor
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
+ // middle-click-paste. Or it might be a click on something we should
+ // not interfere with, such as a scrollbar or widget.
+ function onMouseDown(e) {
+ if (signalDOMEvent(this, e)) return;
+ var cm = this, display = cm.display;
+ display.shift = e.shiftKey;
+
+ if (eventInWidget(display, e)) {
+ if (!webkit) {
+ // Briefly turn off draggability, to allow widgets to do
+ // normal dragging things.
+ display.scroller.draggable = false;
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
+ }
+ return;
+ }
+ if (clickInGutter(cm, e)) return;
+ var start = posFromMouse(cm, e);
+ window.focus();
+
+ switch (e_button(e)) {
+ case 1:
+ if (start)
+ leftButtonDown(cm, e, start);
+ else if (e_target(e) == display.scroller)
+ e_preventDefault(e);
+ break;
+ case 2:
+ if (webkit) cm.state.lastMiddleDown = +new Date;
+ if (start) extendSelection(cm.doc, start);
+ setTimeout(bind(focusInput, cm), 20);
+ e_preventDefault(e);
+ break;
+ case 3:
+ if (captureRightClick) onContextMenu(cm, e);
+ break;
+ }
+ }
+
+ var lastClick, lastDoubleClick;
+ function leftButtonDown(cm, e, start) {
+ setTimeout(bind(ensureFocus, cm), 0);
+
+ var now = +new Date, type;
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
+ type = "triple";
+ } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
+ type = "double";
+ lastDoubleClick = {time: now, pos: start};
+ } else {
+ type = "single";
+ lastClick = {time: now, pos: start};
+ }
+
+ var sel = cm.doc.sel, addNew = mac ? e.metaKey : e.ctrlKey;
+ if (cm.options.dragDrop && dragAndDrop && !addNew && !isReadOnly(cm) &&
+ type == "single" && sel.contains(start) > -1 && sel.somethingSelected())
+ leftButtonStartDrag(cm, e, start);
+ else
+ leftButtonSelect(cm, e, start, type, addNew);
+ }
+
+ // Start a text drag. When it ends, see if any dragging actually
+ // happen, and treat as a click if it didn't.
+ function leftButtonStartDrag(cm, e, start) {
+ var display = cm.display;
+ var dragEnd = operation(cm, function(e2) {
+ if (webkit) display.scroller.draggable = false;
+ cm.state.draggingText = false;
+ off(document, "mouseup", dragEnd);
+ off(display.scroller, "drop", dragEnd);
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
+ e_preventDefault(e2);
+ extendSelection(cm.doc, start);
+ focusInput(cm);
+ // Work around unexplainable focus problem in IE9 (#2127)
+ if (ie_upto10 && !ie_upto8)
+ setTimeout(function() {document.body.focus(); focusInput(cm);}, 20);
+ }
+ });
+ // Let the drag handler handle this.
+ if (webkit) display.scroller.draggable = true;
+ cm.state.draggingText = dragEnd;
+ // IE's approach to draggable
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
+ on(document, "mouseup", dragEnd);
+ on(display.scroller, "drop", dragEnd);
+ }
+
+ // Normal selection, as opposed to text dragging.
+ function leftButtonSelect(cm, e, start, type, addNew) {
+ var display = cm.display, doc = cm.doc;
+ e_preventDefault(e);
+
+ var ourRange, ourIndex, startSel = doc.sel;
+ if (addNew) {
+ ourIndex = doc.sel.contains(start);
+ if (ourIndex > -1)
+ ourRange = doc.sel.ranges[ourIndex];
+ else
+ ourRange = new Range(start, start);
+ } else {
+ ourRange = doc.sel.primary();
+ }
+
+ if (e.altKey) {
+ type = "rect";
+ if (!addNew) ourRange = new Range(start, start);
+ start = posFromMouse(cm, e, true, true);
+ ourIndex = -1;
+ } else if (type == "double") {
+ var word = findWordAt(doc, start);
+ if (cm.display.shift || doc.extend)
+ ourRange = extendRange(doc, ourRange, word.anchor, word.head);
+ else
+ ourRange = word;
+ } else if (type == "triple") {
+ var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
+ if (cm.display.shift || doc.extend)
+ ourRange = extendRange(doc, ourRange, line.anchor, line.head);
+ else
+ ourRange = line;
+ } else {
+ ourRange = extendRange(doc, ourRange, start);
+ }
+
+ if (!addNew) {
+ ourIndex = 0;
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
+ } else if (ourIndex > -1) {
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
+ } else {
+ ourIndex = doc.sel.ranges.length;
+ setSelection(doc, normalizeSelection(doc.sel.ranges.concat([ourRange]), ourIndex),
+ {scroll: false, origin: "*mouse"});
+ }
+
+ var lastPos = start;
+ function extendTo(pos) {
+ if (cmp(lastPos, pos) == 0) return;
+ lastPos = pos;
+
+ if (type == "rect") {
+ var ranges = [], tabSize = cm.options.tabSize;
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
+ line <= end; line++) {
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
+ if (left == right)
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
+ else if (text.length > leftPos)
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
+ }
+ if (!ranges.length) ranges.push(new Range(start, start));
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), sel_mouse);
+ } else {
+ var oldRange = ourRange;
+ var anchor = oldRange.anchor, head = pos;
+ if (type != "single") {
+ if (type == "double")
+ var range = findWordAt(doc, pos);
+ else
+ var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
+ if (cmp(range.anchor, anchor) > 0) {
+ head = range.head;
+ anchor = minPos(oldRange.from(), range.anchor);
+ } else {
+ head = range.anchor;
+ anchor = maxPos(oldRange.to(), range.head);
+ }
+ }
+ var ranges = startSel.ranges.slice(0);
+ ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
+ setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
+ }
+ }
+
+ var editorSize = display.wrapper.getBoundingClientRect();
+ // Used to ensure timeout re-tries don't fire when another extend
+ // happened in the meantime (clearTimeout isn't reliable -- at
+ // least on Chrome, the timeouts still happen even when cleared,
+ // if the clear happens after their scheduled firing time).
+ var counter = 0;
+
+ function extend(e) {
+ var curCount = ++counter;
+ var cur = posFromMouse(cm, e, true, type == "rect");
+ if (!cur) return;
+ if (cmp(cur, lastPos) != 0) {
+ ensureFocus(cm);
+ extendTo(cur);
+ var visible = visibleLines(display, doc);
+ if (cur.line >= visible.to || cur.line < visible.from)
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
+ } else {
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
+ if (outside) setTimeout(operation(cm, function() {
+ if (counter != curCount) return;
+ display.scroller.scrollTop += outside;
+ extend(e);
+ }), 50);
+ }
+ }
+
+ function done(e) {
+ counter = Infinity;
+ e_preventDefault(e);
+ focusInput(cm);
+ off(document, "mousemove", move);
+ off(document, "mouseup", up);
+ doc.history.lastSelOrigin = null;
+ }
+
+ var move = operation(cm, function(e) {
+ if ((ie && !ie_upto9) ? !e.buttons : !e_button(e)) done(e);
+ else extend(e);
+ });
+ var up = operation(cm, done);
+ on(document, "mousemove", move);
+ on(document, "mouseup", up);
+ }
+
+ // Determines whether an event happened in the gutter, and fires the
+ // handlers for the corresponding event.
+ function gutterEvent(cm, e, type, prevent, signalfn) {
+ try { var mX = e.clientX, mY = e.clientY; }
+ catch(e) { return false; }
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
+ if (prevent) e_preventDefault(e);
+
+ var display = cm.display;
+ var lineBox = display.lineDiv.getBoundingClientRect();
+
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
+ mY -= lineBox.top - display.viewOffset;
+
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
+ var g = display.gutters.childNodes[i];
+ if (g && g.getBoundingClientRect().right >= mX) {
+ var line = lineAtHeight(cm.doc, mY);
+ var gutter = cm.options.gutters[i];
+ signalfn(cm, type, cm, line, gutter, e);
+ return e_defaultPrevented(e);
+ }
+ }
+ }
+
+ function clickInGutter(cm, e) {
+ return gutterEvent(cm, e, "gutterClick", true, signalLater);
+ }
+
+ // Kludge to work around strange IE behavior where it'll sometimes
+ // re-fire a series of drag-related events right after the drop (#1551)
+ var lastDrop = 0;
+
+ function onDrop(e) {
+ var cm = this;
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
+ return;
+ e_preventDefault(e);
+ if (ie_upto10) lastDrop = +new Date;
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
+ if (!pos || isReadOnly(cm)) return;
+ // Might be a file drop, in which case we simply extract the text
+ // and insert it.
+ if (files && files.length && window.FileReader && window.File) {
+ var n = files.length, text = Array(n), read = 0;
+ var loadFile = function(file, i) {
+ var reader = new FileReader;
+ reader.onload = function() {
+ text[i] = reader.result;
+ if (++read == n) {
+ pos = clipPos(cm.doc, pos);
+ var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"};
+ makeChange(cm.doc, change);
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
+ }
+ };
+ reader.readAsText(file);
+ };
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
+ } else { // Normal drop
+ // Don't do a replace if the drop happened inside of the selected text.
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
+ cm.state.draggingText(e);
+ // Ensure the editor is re-focused
+ setTimeout(bind(focusInput, cm), 20);
+ return;
+ }
+ try {
+ var text = e.dataTransfer.getData("Text");
+ if (text) {
+ var selected = cm.state.draggingText && cm.listSelections();
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
+ if (selected) for (var i = 0; i < selected.length; ++i)
+ replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
+ cm.replaceSelection(text, "around", "paste");
+ focusInput(cm);
+ }
+ }
+ catch(e){}
+ }
+ }
+
+ function onDragStart(cm, e) {
+ if (ie_upto10 && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
+
+ e.dataTransfer.setData("Text", cm.getSelection());
+
+ // Use dummy image instead of default browsers image.
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
+ if (e.dataTransfer.setDragImage && !safari) {
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
+ if (presto) {
+ img.width = img.height = 1;
+ cm.display.wrapper.appendChild(img);
+ // Force a relayout, or Opera won't use our image for some obscure reason
+ img._top = img.offsetTop;
+ }
+ e.dataTransfer.setDragImage(img, 0, 0);
+ if (presto) img.parentNode.removeChild(img);
+ }
+ }
+
+ // SCROLL EVENTS
+
+ // Sync the scrollable area and scrollbars, ensure the viewport
+ // covers the visible area.
+ function setScrollTop(cm, val) {
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
+ cm.doc.scrollTop = val;
+ if (!gecko) updateDisplay(cm, {top: val});
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
+ if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val;
+ if (gecko) updateDisplay(cm);
+ startWorker(cm, 100);
+ }
+ // Sync scroller and scrollbar, ensure the gutter elements are
+ // aligned.
+ function setScrollLeft(cm, val, isScroller) {
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
+ cm.doc.scrollLeft = val;
+ alignHorizontally(cm);
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
+ if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val;
+ }
+
+ // Since the delta values reported on mouse wheel events are
+ // unstandardized between browsers and even browser versions, and
+ // generally horribly unpredictable, this code starts by measuring
+ // the scroll effect that the first few mouse wheel events have,
+ // and, from that, detects the way it can convert deltas to pixel
+ // offsets afterwards.
+ //
+ // The reason we want to know the amount a wheel event will scroll
+ // is that it gives us a chance to update the display before the
+ // actual scrolling happens, reducing flickering.
+
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
+ // Fill in a browser-detected starting value on browsers where we
+ // know one. These don't have to be accurate -- the result of them
+ // being wrong would just be a slight flicker on the first wheel
+ // scroll (if it is large enough).
+ if (ie) wheelPixelsPerUnit = -.53;
+ else if (gecko) wheelPixelsPerUnit = 15;
+ else if (chrome) wheelPixelsPerUnit = -.7;
+ else if (safari) wheelPixelsPerUnit = -1/3;
+
+ function onScrollWheel(cm, e) {
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
+ else if (dy == null) dy = e.wheelDelta;
+
+ var display = cm.display, scroll = display.scroller;
+ // Quit if there's nothing to scroll here
+ if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
+ dy && scroll.scrollHeight > scroll.clientHeight)) return;
+
+ // Webkit browsers on OS X abort momentum scrolls when the target
+ // of the scroll event is removed from the scrollable element.
+ // This hack (see related code in patchDisplay) makes sure the
+ // element is kept around.
+ if (dy && mac && webkit) {
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
+ for (var i = 0; i < view.length; i++) {
+ if (view[i].node == cur) {
+ cm.display.currentWheelTarget = cur;
+ break outer;
+ }
+ }
+ }
+ }
+
+ // On some browsers, horizontal scrolling will cause redraws to
+ // happen before the gutter has been realigned, causing it to
+ // wriggle around in a most unseemly way. When we have an
+ // estimated pixels/delta value, we just handle horizontal
+ // scrolling entirely here. It'll be slightly off from native, but
+ // better than glitching out.
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
+ if (dy)
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
+ e_preventDefault(e);
+ display.wheelStartX = null; // Abort measurement, if in progress
+ return;
+ }
+
+ // 'Project' the visible viewport to cover the area that is being
+ // scrolled into view (if we know enough to estimate it).
+ if (dy && wheelPixelsPerUnit != null) {
+ var pixels = dy * wheelPixelsPerUnit;
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
+ updateDisplay(cm, {top: top, bottom: bot});
+ }
+
+ if (wheelSamples < 20) {
+ if (display.wheelStartX == null) {
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
+ display.wheelDX = dx; display.wheelDY = dy;
+ setTimeout(function() {
+ if (display.wheelStartX == null) return;
+ var movedX = scroll.scrollLeft - display.wheelStartX;
+ var movedY = scroll.scrollTop - display.wheelStartY;
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
+ (movedX && display.wheelDX && movedX / display.wheelDX);
+ display.wheelStartX = display.wheelStartY = null;
+ if (!sample) return;
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
+ ++wheelSamples;
+ }, 200);
+ } else {
+ display.wheelDX += dx; display.wheelDY += dy;
+ }
+ }
+ }
+
+ // KEY EVENTS
+
+ // Run a handler that was bound to a key.
+ function doHandleBinding(cm, bound, dropShift) {
+ if (typeof bound == "string") {
+ bound = commands[bound];
+ if (!bound) return false;
+ }
+ // Ensure previous input has been read, so that the handler sees a
+ // consistent view of the document
+ if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false;
+ var prevShift = cm.display.shift, done = false;
+ try {
+ if (isReadOnly(cm)) cm.state.suppressEdits = true;
+ if (dropShift) cm.display.shift = false;
+ done = bound(cm) != Pass;
+ } finally {
+ cm.display.shift = prevShift;
+ cm.state.suppressEdits = false;
+ }
+ return done;
+ }
+
+ // Collect the currently active keymaps.
+ function allKeyMaps(cm) {
+ var maps = cm.state.keyMaps.slice(0);
+ if (cm.options.extraKeys) maps.push(cm.options.extraKeys);
+ maps.push(cm.options.keyMap);
+ return maps;
+ }
+
+ var maybeTransition;
+ // Handle a key from the keydown event.
+ function handleKeyBinding(cm, e) {
+ // Handle automatic keymap transitions
+ var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto;
+ clearTimeout(maybeTransition);
+ if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() {
+ if (getKeyMap(cm.options.keyMap) == startMap) {
+ cm.options.keyMap = (next.call ? next.call(null, cm) : next);
+ keyMapChanged(cm);
+ }
+ }, 50);
+
+ var name = keyName(e, true), handled = false;
+ if (!name) return false;
+ var keymaps = allKeyMaps(cm);
+
+ if (e.shiftKey) {
+ // First try to resolve full name (including 'Shift-'). Failing
+ // that, see if there is a cursor-motion command (starting with
+ // 'go') bound to the keyname without 'Shift-'.
+ handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);})
+ || lookupKey(name, keymaps, function(b) {
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
+ return doHandleBinding(cm, b);
+ });
+ } else {
+ handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); });
+ }
+
+ if (handled) {
+ e_preventDefault(e);
+ restartBlink(cm);
+ signalLater(cm, "keyHandled", cm, name, e);
+ }
+ return handled;
+ }
+
+ // Handle a key from the keypress event
+ function handleCharBinding(cm, e, ch) {
+ var handled = lookupKey("'" + ch + "'", allKeyMaps(cm),
+ function(b) { return doHandleBinding(cm, b, true); });
+ if (handled) {
+ e_preventDefault(e);
+ restartBlink(cm);
+ signalLater(cm, "keyHandled", cm, "'" + ch + "'", e);
+ }
+ return handled;
+ }
+
+ var lastStoppedKey = null;
+ function onKeyDown(e) {
+ var cm = this;
+ ensureFocus(cm);
+ if (signalDOMEvent(cm, e)) return;
+ // IE does strange things with escape.
+ if (ie_upto10 && e.keyCode == 27) e.returnValue = false;
+ var code = e.keyCode;
+ cm.display.shift = code == 16 || e.shiftKey;
+ var handled = handleKeyBinding(cm, e);
+ if (presto) {
+ lastStoppedKey = handled ? code : null;
+ // Opera has no cut event... we try to at least catch the key combo
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
+ cm.replaceSelection("", null, "cut");
+ }
+ }
+
+ function onKeyUp(e) {
+ if (signalDOMEvent(this, e)) return;
+ if (e.keyCode == 16) this.doc.sel.shift = false;
+ }
+
+ function onKeyPress(e) {
+ var cm = this;
+ if (signalDOMEvent(cm, e)) return;
+ var keyCode = e.keyCode, charCode = e.charCode;
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
+ if (((presto && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return;
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+ if (handleCharBinding(cm, e, ch)) return;
+ if (ie && !ie_upto8) cm.display.inputHasSelection = null;
+ fastPoll(cm);
+ }
+
+ // FOCUS/BLUR EVENTS
+
+ function onFocus(cm) {
+ if (cm.options.readOnly == "nocursor") return;
+ if (!cm.state.focused) {
+ signal(cm, "focus", cm);
+ cm.state.focused = true;
+ if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1)
+ cm.display.wrapper.className += " CodeMirror-focused";
+ if (!cm.curOp) {
+ resetInput(cm);
+ if (webkit) setTimeout(bind(resetInput, cm, true), 0); // Issue #1730
+ }
+ }
+ slowPoll(cm);
+ restartBlink(cm);
+ }
+ function onBlur(cm) {
+ if (cm.state.focused) {
+ signal(cm, "blur", cm);
+ cm.state.focused = false;
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", "");
+ }
+ clearInterval(cm.display.blinker);
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
+ }
+
+ // CONTEXT MENU HANDLING
+
+ var detectingSelectAll;
+ // To make the context menu work, we need to briefly unhide the
+ // textarea (making it as unobtrusive as possible) to let the
+ // right-click take effect on it.
+ function onContextMenu(cm, e) {
+ if (signalDOMEvent(cm, e, "contextmenu")) return;
+ var display = cm.display;
+ if (eventInWidget(display, e) || contextMenuInGutter(cm, e)) return;
+
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
+ if (!pos || presto) return; // Opera is difficult.
+
+ // Reset the current text selection only if the click is done outside of the selection
+ // and 'resetSelectionOnContextMenu' option is true.
+ var reset = cm.options.resetSelectionOnContextMenu;
+ if (reset && cm.doc.sel.contains(pos) == -1)
+ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
+
+ var oldCSS = display.input.style.cssText;
+ display.inputDiv.style.position = "absolute";
+ display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
+ "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
+ (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
+ "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
+ focusInput(cm);
+ resetInput(cm);
+ // Adds "Select all" to context menu in FF
+ if (!cm.somethingSelected()) display.input.value = display.prevInput = " ";
+
+ // Select-all will be greyed out if there's nothing to select, so
+ // this adds a zero-width space so that we can later check whether
+ // it got selected.
+ function prepareSelectAllHack() {
+ if (display.input.selectionStart != null) {
+ var extval = display.input.value = "\u200b" + (cm.somethingSelected() ? display.input.value : "");
+ display.prevInput = "\u200b";
+ display.input.selectionStart = 1; display.input.selectionEnd = extval.length;
+ }
+ }
+ function rehide() {
+ display.inputDiv.style.position = "relative";
+ display.input.style.cssText = oldCSS;
+ if (ie_upto8) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos;
+ slowPoll(cm);
+
+ // Try to detect the user choosing select-all
+ if (display.input.selectionStart != null) {
+ if (!ie || ie_upto8) prepareSelectAllHack();
+ clearTimeout(detectingSelectAll);
+ var i = 0, poll = function(){
+ if (display.prevInput == "\u200b" && display.input.selectionStart == 0)
+ operation(cm, commands.selectAll)(cm);
+ else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500);
+ else resetInput(cm);
+ };
+ detectingSelectAll = setTimeout(poll, 200);
+ }
+ }
+
+ if (ie && !ie_upto8) prepareSelectAllHack();
+ if (captureRightClick) {
+ e_stop(e);
+ var mouseup = function() {
+ off(window, "mouseup", mouseup);
+ setTimeout(rehide, 20);
+ };
+ on(window, "mouseup", mouseup);
+ } else {
+ setTimeout(rehide, 50);
+ }
+ }
+
+ function contextMenuInGutter(cm, e) {
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
+ return gutterEvent(cm, e, "gutterContextMenu", false, signal);
+ }
+
+ // UPDATING
+
+ // Compute the position of the end of a change (its 'to' property
+ // refers to the pre-change end).
+ var changeEnd = CodeMirror.changeEnd = function(change) {
+ if (!change.text) return change.to;
+ return Pos(change.from.line + change.text.length - 1,
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
+ };
+
+ // Adjust a position to refer to the post-change position of the
+ // same text, or the end of the change if the change covers it.
+ function adjustForChange(pos, change) {
+ if (cmp(pos, change.from) < 0) return pos;
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
+
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
+ return Pos(line, ch);
+ }
+
+ function computeSelAfterChange(doc, change) {
+ var out = [];
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ out.push(new Range(adjustForChange(range.anchor, change),
+ adjustForChange(range.head, change)));
+ }
+ return normalizeSelection(out, doc.sel.primIndex);
+ }
+
+ function offsetPos(pos, old, nw) {
+ if (pos.line == old.line)
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
+ else
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
+ }
+
+ // Used by replaceSelections to allow moving the selection to the
+ // start or around the replaced test. Hint may be "start" or "around".
+ function computeReplacedSel(doc, changes, hint) {
+ var out = [];
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
+ for (var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+ var from = offsetPos(change.from, oldPrev, newPrev);
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
+ oldPrev = change.to;
+ newPrev = to;
+ if (hint == "around") {
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
+ out[i] = new Range(inv ? to : from, inv ? from : to);
+ } else {
+ out[i] = new Range(from, from);
+ }
+ }
+ return new Selection(out, doc.sel.primIndex);
+ }
+
+ // Allow "beforeChange" event handlers to influence a change
+ function filterChange(doc, change, update) {
+ var obj = {
+ canceled: false,
+ from: change.from,
+ to: change.to,
+ text: change.text,
+ origin: change.origin,
+ cancel: function() { this.canceled = true; }
+ };
+ if (update) obj.update = function(from, to, text, origin) {
+ if (from) this.from = clipPos(doc, from);
+ if (to) this.to = clipPos(doc, to);
+ if (text) this.text = text;
+ if (origin !== undefined) this.origin = origin;
+ };
+ signal(doc, "beforeChange", doc, obj);
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
+
+ if (obj.canceled) return null;
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
+ }
+
+ // Apply a change to a document, and add it to the document's
+ // history, and propagating it to all linked documents.
+ function makeChange(doc, change, ignoreReadOnly) {
+ if (doc.cm) {
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
+ if (doc.cm.state.suppressEdits) return;
+ }
+
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
+ change = filterChange(doc, change, true);
+ if (!change) return;
+ }
+
+ // Possibly split or suppress the update based on the presence
+ // of read-only spans in its range.
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
+ if (split) {
+ for (var i = split.length - 1; i >= 0; --i)
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
+ } else {
+ makeChangeInner(doc, change);
+ }
+ }
+
+ function makeChangeInner(doc, change) {
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
+ var selAfter = computeSelAfterChange(doc, change);
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
+
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
+ var rebased = [];
+
+ linkedDocs(doc, function(doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
+ });
+ }
+
+ // Revert a change stored in a document's history.
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
+ if (doc.cm && doc.cm.state.suppressEdits) return;
+
+ var hist = doc.history, event, selAfter = doc.sel;
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
+
+ // Verify that there is a useable event (so that ctrl-z won't
+ // needlessly clear selection events)
+ for (var i = 0; i < source.length; i++) {
+ event = source[i];
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
+ break;
+ }
+ if (i == source.length) return;
+ hist.lastOrigin = hist.lastSelOrigin = null;
+
+ for (;;) {
+ event = source.pop();
+ if (event.ranges) {
+ pushSelectionToHistory(event, dest);
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
+ setSelection(doc, event, {clearRedo: false});
+ return;
+ }
+ selAfter = event;
+ }
+ else break;
+ }
+
+ // Build up a reverse change object to add to the opposite history
+ // stack (redo when undoing, and vice versa).
+ var antiChanges = [];
+ pushSelectionToHistory(selAfter, dest);
+ dest.push({changes: antiChanges, generation: hist.generation});
+ hist.generation = event.generation || ++hist.maxGeneration;
+
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
+
+ for (var i = event.changes.length - 1; i >= 0; --i) {
+ var change = event.changes[i];
+ change.origin = type;
+ if (filter && !filterChange(doc, change, false)) {
+ source.length = 0;
+ return;
+ }
+
+ antiChanges.push(historyChangeFromChange(doc, change));
+
+ var after = i ? computeSelAfterChange(doc, change, null) : lst(source);
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
+ if (doc.cm) ensureCursorVisible(doc.cm);
+ var rebased = [];
+
+ // Propagate to the linked documents
+ linkedDocs(doc, function(doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
+ });
+ }
+ }
+
+ // Sub-views need their line numbers shifted when text is added
+ // above or below them in the parent document.
+ function shiftDoc(doc, distance) {
+ doc.first += distance;
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
+ Pos(range.head.line + distance, range.head.ch));
+ }), doc.sel.primIndex);
+ if (doc.cm) regChange(doc.cm, doc.first, doc.first - distance, distance);
+ }
+
+ // More lower-level change function, handling only a single document
+ // (not linked ones).
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
+ if (doc.cm && !doc.cm.curOp)
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
+
+ if (change.to.line < doc.first) {
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
+ return;
+ }
+ if (change.from.line > doc.lastLine()) return;
+
+ // Clip the change to the size of this doc
+ if (change.from.line < doc.first) {
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
+ shiftDoc(doc, shift);
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
+ text: [lst(change.text)], origin: change.origin};
+ }
+ var last = doc.lastLine();
+ if (change.to.line > last) {
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
+ text: [change.text[0]], origin: change.origin};
+ }
+
+ change.removed = getBetween(doc, change.from, change.to);
+
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change, null);
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
+ else updateDoc(doc, change, spans);
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
+ }
+
+ // Handle the interaction of a change to a document with the editor
+ // that this document is part of.
+ function makeChangeSingleDocInEditor(cm, change, spans) {
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
+
+ var recomputeMaxLength = false, checkWidthStart = from.line;
+ if (!cm.options.lineWrapping) {
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
+ if (line == display.maxLine) {
+ recomputeMaxLength = true;
+ return true;
+ }
+ });
+ }
+
+ if (doc.sel.contains(change.from, change.to) > -1)
+ cm.curOp.cursorActivity = true;
+
+ updateDoc(doc, change, spans, estimateHeight(cm));
+
+ if (!cm.options.lineWrapping) {
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
+ var len = lineLength(line);
+ if (len > display.maxLineLength) {
+ display.maxLine = line;
+ display.maxLineLength = len;
+ display.maxLineChanged = true;
+ recomputeMaxLength = false;
+ }
+ });
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
+ }
+
+ // Adjust frontier, schedule worker
+ doc.frontier = Math.min(doc.frontier, from.line);
+ startWorker(cm, 400);
+
+ var lendiff = change.text.length - (to.line - from.line) - 1;
+ // Remember that these lines changed, for updating the display
+ if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
+ regLineChange(cm, from.line, "text");
+ else
+ regChange(cm, from.line, to.line + 1, lendiff);
+
+ if (hasHandler(cm, "change") || hasHandler(cm, "changes"))
+ (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push({
+ from: from, to: to,
+ text: change.text,
+ removed: change.removed,
+ origin: change.origin
+ });
+ }
+
+ function replaceRange(doc, code, from, to, origin) {
+ if (!to) to = from;
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
+ if (typeof code == "string") code = splitLines(code);
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
+ }
+
+ // SCROLLING THINGS INTO VIEW
+
+ // If an editor sits on the top or bottom of the window, partially
+ // scrolled out of view, this ensures that the cursor is visible.
+ function maybeScrollWindow(cm, coords) {
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
+ if (coords.top + box.top < 0) doScroll = true;
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
+ if (doScroll != null && !phantom) {
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
+ (coords.bottom - coords.top + scrollerCutOff) + "px; left: " +
+ coords.left + "px; width: 2px;");
+ cm.display.lineSpace.appendChild(scrollNode);
+ scrollNode.scrollIntoView(doScroll);
+ cm.display.lineSpace.removeChild(scrollNode);
+ }
+ }
+
+ // Scroll a given position into view (immediately), verifying that
+ // it actually became visible (as line heights are accurately
+ // measured, the position of something may 'drift' during drawing).
+ function scrollPosIntoView(cm, pos, end, margin) {
+ if (margin == null) margin = 0;
+ for (;;) {
+ var changed = false, coords = cursorCoords(cm, pos);
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
+ Math.min(coords.top, endCoords.top) - margin,
+ Math.max(coords.left, endCoords.left),
+ Math.max(coords.bottom, endCoords.bottom) + margin);
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
+ if (scrollPos.scrollTop != null) {
+ setScrollTop(cm, scrollPos.scrollTop);
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
+ }
+ if (scrollPos.scrollLeft != null) {
+ setScrollLeft(cm, scrollPos.scrollLeft);
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
+ }
+ if (!changed) return coords;
+ }
+ }
+
+ // Scroll a given set of coordinates into view (immediately).
+ function scrollIntoView(cm, x1, y1, x2, y2) {
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
+ }
+
+ // Calculate a new scroll position needed to scroll the given
+ // rectangle into view. Returns an object with scrollTop and
+ // scrollLeft properties. When these are undefined, the
+ // vertical/horizontal position does not need to be adjusted.
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
+ var display = cm.display, snapMargin = textHeight(cm.display);
+ if (y1 < 0) y1 = 0;
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
+ var screen = display.scroller.clientHeight - scrollerCutOff, result = {};
+ var docBottom = cm.doc.height + paddingVert(display);
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
+ if (y1 < screentop) {
+ result.scrollTop = atTop ? 0 : y1;
+ } else if (y2 > screentop + screen) {
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
+ if (newTop != screentop) result.scrollTop = newTop;
+ }
+
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
+ var screenw = display.scroller.clientWidth - scrollerCutOff;
+ x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth;
+ var gutterw = display.gutters.offsetWidth;
+ var atLeft = x1 < gutterw + 10;
+ if (x1 < screenleft + gutterw || atLeft) {
+ if (atLeft) x1 = 0;
+ result.scrollLeft = Math.max(0, x1 - 10 - gutterw);
+ } else if (x2 > screenw + screenleft - 3) {
+ result.scrollLeft = x2 + 10 - screenw;
+ }
+ return result;
+ }
+
+ // Store a relative adjustment to the scroll position in the current
+ // operation (to be applied when the operation finishes).
+ function addToScrollPos(cm, left, top) {
+ if (left != null || top != null) resolveScrollToPos(cm);
+ if (left != null)
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
+ if (top != null)
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
+ }
+
+ // Make sure that at the end of the operation the current cursor is
+ // shown.
+ function ensureCursorVisible(cm) {
+ resolveScrollToPos(cm);
+ var cur = cm.getCursor(), from = cur, to = cur;
+ if (!cm.options.lineWrapping) {
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
+ to = Pos(cur.line, cur.ch + 1);
+ }
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
+ }
+
+ // When an operation has its scrollToPos property set, and another
+ // scroll action is applied before the end of the operation, this
+ // 'simulates' scrolling that position into view in a cheap way, so
+ // that the effect of intermediate scroll commands is not ignored.
+ function resolveScrollToPos(cm) {
+ var range = cm.curOp.scrollToPos;
+ if (range) {
+ cm.curOp.scrollToPos = null;
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
+ Math.min(from.top, to.top) - range.margin,
+ Math.max(from.right, to.right),
+ Math.max(from.bottom, to.bottom) + range.margin);
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
+ }
+ }
+
+ // API UTILITIES
+
+ // Indent the given line. The how parameter can be "smart",
+ // "add"/null, "subtract", or "prev". When aggressive is false
+ // (typically set to true for forced single-line indents), empty
+ // lines are not indented, and places where the mode returns Pass
+ // are left alone.
+ function indentLine(cm, n, how, aggressive) {
+ var doc = cm.doc, state;
+ if (how == null) how = "add";
+ if (how == "smart") {
+ // Fall back to "prev" when the mode doesn't have an indentation
+ // method.
+ if (!cm.doc.mode.indent) how = "prev";
+ else state = getStateBefore(cm, n);
+ }
+
+ var tabSize = cm.options.tabSize;
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
+ if (line.stateAfter) line.stateAfter = null;
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
+ if (!aggressive && !/\S/.test(line.text)) {
+ indentation = 0;
+ how = "not";
+ } else if (how == "smart") {
+ indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+ if (indentation == Pass) {
+ if (!aggressive) return;
+ how = "prev";
+ }
+ }
+ if (how == "prev") {
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
+ else indentation = 0;
+ } else if (how == "add") {
+ indentation = curSpace + cm.options.indentUnit;
+ } else if (how == "subtract") {
+ indentation = curSpace - cm.options.indentUnit;
+ } else if (typeof how == "number") {
+ indentation = curSpace + how;
+ }
+ indentation = Math.max(0, indentation);
+
+ var indentString = "", pos = 0;
+ if (cm.options.indentWithTabs)
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
+
+ if (indentString != curSpaceString) {
+ replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
+ } else {
+ // Ensure that, if the cursor was in the whitespace at the start
+ // of the line, it is moved to the end of that space.
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
+ var pos = Pos(n, curSpaceString.length);
+ replaceOneSelection(doc, i, new Range(pos, pos));
+ break;
+ }
+ }
+ }
+ line.stateAfter = null;
+ }
+
+ // Utility for applying a change to a line by handle or number,
+ // returning the number and optionally registering the line as
+ // changed.
+ function changeLine(cm, handle, changeType, op) {
+ var no = handle, line = handle, doc = cm.doc;
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
+ else no = lineNo(handle);
+ if (no == null) return null;
+ if (op(line, no)) regLineChange(cm, no, changeType);
+ else return null;
+ return line;
+ }
+
+ // Helper for deleting text near the selection(s), used to implement
+ // backspace, delete, and similar functionality.
+ function deleteNearSelection(cm, compute) {
+ var ranges = cm.doc.sel.ranges, kill = [];
+ // Build up a set of ranges to kill first, merging overlapping
+ // ranges.
+ for (var i = 0; i < ranges.length; i++) {
+ var toKill = compute(ranges[i]);
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
+ var replaced = kill.pop();
+ if (cmp(replaced.from, toKill.from) < 0) {
+ toKill.from = replaced.from;
+ break;
+ }
+ }
+ kill.push(toKill);
+ }
+ // Next, remove those actual ranges.
+ runInOp(cm, function() {
+ for (var i = kill.length - 1; i >= 0; i--)
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
+ ensureCursorVisible(cm);
+ });
+ }
+
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
+ // right), unit can be "char", "column" (like char, but doesn't
+ // cross line boundaries), "word" (across next word), or "group" (to
+ // the start of next group of word or non-word-non-whitespace
+ // chars). The visually param controls whether, in right-to-left
+ // text, direction 1 means to move towards the next index in the
+ // string, or towards the character to the right of the current
+ // position. The resulting position will have a hitSide=true
+ // property if it reached the end of the document.
+ function findPosH(doc, pos, dir, unit, visually) {
+ var line = pos.line, ch = pos.ch, origDir = dir;
+ var lineObj = getLine(doc, line);
+ var possible = true;
+ function findNextLine() {
+ var l = line + dir;
+ if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
+ line = l;
+ return lineObj = getLine(doc, l);
+ }
+ function moveOnce(boundToLine) {
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
+ if (next == null) {
+ if (!boundToLine && findNextLine()) {
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
+ else ch = dir < 0 ? lineObj.text.length : 0;
+ } else return (possible = false);
+ } else ch = next;
+ return true;
+ }
+
+ if (unit == "char") moveOnce();
+ else if (unit == "column") moveOnce(true);
+ else if (unit == "word" || unit == "group") {
+ var sawType = null, group = unit == "group";
+ for (var first = true;; first = false) {
+ if (dir < 0 && !moveOnce(!first)) break;
+ var cur = lineObj.text.charAt(ch) || "\n";
+ var type = isWordChar(cur) ? "w"
+ : group && cur == "\n" ? "n"
+ : !group || /\s/.test(cur) ? null
+ : "p";
+ if (group && !first && !type) type = "s";
+ if (sawType && sawType != type) {
+ if (dir < 0) {dir = 1; moveOnce();}
+ break;
+ }
+
+ if (type) sawType = type;
+ if (dir > 0 && !moveOnce(!first)) break;
+ }
+ }
+ var result = skipAtomic(doc, Pos(line, ch), origDir, true);
+ if (!possible) result.hitSide = true;
+ return result;
+ }
+
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
+ // "page" or "line". The resulting position will have a hitSide=true
+ // property if it reached the end of the document.
+ function findPosV(cm, pos, dir, unit) {
+ var doc = cm.doc, x = pos.left, y;
+ if (unit == "page") {
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
+ } else if (unit == "line") {
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
+ }
+ for (;;) {
+ var target = coordsChar(cm, x, y);
+ if (!target.outside) break;
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
+ y += dir * 5;
+ }
+ return target;
+ }
+
+ // Find the word at the given position (as returned by coordsChar).
+ function findWordAt(doc, pos) {
+ var line = getLine(doc, pos.line).text;
+ var start = pos.ch, end = pos.ch;
+ if (line) {
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
+ var startChar = line.charAt(start);
+ var check = isWordChar(startChar) ? isWordChar
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
+ while (start > 0 && check(line.charAt(start - 1))) --start;
+ while (end < line.length && check(line.charAt(end))) ++end;
+ }
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
+ }
+
+ // EDITOR METHODS
+
+ // The publicly visible API. Note that methodOp(f) means
+ // 'wrap f in an operation, performed on its `this` parameter'.
+
+ // This is not the complete set of editor methods. Most of the
+ // methods defined on the Doc type are also injected into
+ // CodeMirror.prototype, for backwards compatibility and
+ // convenience.
+
+ CodeMirror.prototype = {
+ constructor: CodeMirror,
+ focus: function(){window.focus(); focusInput(this); fastPoll(this);},
+
+ setOption: function(option, value) {
+ var options = this.options, old = options[option];
+ if (options[option] == value && option != "mode") return;
+ options[option] = value;
+ if (optionHandlers.hasOwnProperty(option))
+ operation(this, optionHandlers[option])(this, value, old);
+ },
+
+ getOption: function(option) {return this.options[option];},
+ getDoc: function() {return this.doc;},
+
+ addKeyMap: function(map, bottom) {
+ this.state.keyMaps[bottom ? "push" : "unshift"](map);
+ },
+ removeKeyMap: function(map) {
+ var maps = this.state.keyMaps;
+ for (var i = 0; i < maps.length; ++i)
+ if (maps[i] == map || (typeof maps[i] != "string" && maps[i].name == map)) {
+ maps.splice(i, 1);
+ return true;
+ }
+ },
+
+ addOverlay: methodOp(function(spec, options) {
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
+ this.state.modeGen++;
+ regChange(this);
+ }),
+ removeOverlay: methodOp(function(spec) {
+ var overlays = this.state.overlays;
+ for (var i = 0; i < overlays.length; ++i) {
+ var cur = overlays[i].modeSpec;
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
+ overlays.splice(i, 1);
+ this.state.modeGen++;
+ regChange(this);
+ return;
+ }
+ }
+ }),
+
+ indentLine: methodOp(function(n, dir, aggressive) {
+ if (typeof dir != "string" && typeof dir != "number") {
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
+ else dir = dir ? "add" : "subtract";
+ }
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
+ }),
+ indentSelection: methodOp(function(how) {
+ var ranges = this.doc.sel.ranges, end = -1;
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ if (!range.empty()) {
+ var start = Math.max(end, range.from().line);
+ var to = range.to();
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
+ for (var j = start; j < end; ++j)
+ indentLine(this, j, how);
+ } else if (range.head.line > end) {
+ indentLine(this, range.head.line, how, true);
+ end = range.head.line;
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
+ }
+ }
+ }),
+
+ // Fetch the parser token for a given character. Useful for hacks
+ // that want to inspect the mode state (say, for completion).
+ getTokenAt: function(pos, precise) {
+ var doc = this.doc;
+ pos = clipPos(doc, pos);
+ var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode;
+ var line = getLine(doc, pos.line);
+ var stream = new StringStream(line.text, this.options.tabSize);
+ while (stream.pos < pos.ch && !stream.eol()) {
+ stream.start = stream.pos;
+ var style = mode.token(stream, state);
+ }
+ return {start: stream.start,
+ end: stream.pos,
+ string: stream.current(),
+ type: style || null,
+ state: state};
+ },
+
+ getTokenTypeAt: function(pos) {
+ pos = clipPos(this.doc, pos);
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
+ if (ch == 0) return styles[2];
+ for (;;) {
+ var mid = (before + after) >> 1;
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
+ else return styles[mid * 2 + 2];
+ }
+ },
+
+ getModeAt: function(pos) {
+ var mode = this.doc.mode;
+ if (!mode.innerMode) return mode;
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
+ },
+
+ getHelper: function(pos, type) {
+ return this.getHelpers(pos, type)[0];
+ },
+
+ getHelpers: function(pos, type) {
+ var found = [];
+ if (!helpers.hasOwnProperty(type)) return helpers;
+ var help = helpers[type], mode = this.getModeAt(pos);
+ if (typeof mode[type] == "string") {
+ if (help[mode[type]]) found.push(help[mode[type]]);
+ } else if (mode[type]) {
+ for (var i = 0; i < mode[type].length; i++) {
+ var val = help[mode[type][i]];
+ if (val) found.push(val);
+ }
+ } else if (mode.helperType && help[mode.helperType]) {
+ found.push(help[mode.helperType]);
+ } else if (help[mode.name]) {
+ found.push(help[mode.name]);
+ }
+ for (var i = 0; i < help._global.length; i++) {
+ var cur = help._global[i];
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
+ found.push(cur.val);
+ }
+ return found;
+ },
+
+ getStateAfter: function(line, precise) {
+ var doc = this.doc;
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
+ return getStateBefore(this, line + 1, precise);
+ },
+
+ cursorCoords: function(start, mode) {
+ var pos, range = this.doc.sel.primary();
+ if (start == null) pos = range.head;
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
+ else pos = start ? range.from() : range.to();
+ return cursorCoords(this, pos, mode || "page");
+ },
+
+ charCoords: function(pos, mode) {
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
+ },
+
+ coordsChar: function(coords, mode) {
+ coords = fromCoordSystem(this, coords, mode || "page");
+ return coordsChar(this, coords.left, coords.top);
+ },
+
+ lineAtHeight: function(height, mode) {
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
+ },
+ heightAtLine: function(line, mode) {
+ var end = false, last = this.doc.first + this.doc.size - 1;
+ if (line < this.doc.first) line = this.doc.first;
+ else if (line > last) { line = last; end = true; }
+ var lineObj = getLine(this.doc, line);
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
+ },
+
+ defaultTextHeight: function() { return textHeight(this.display); },
+ defaultCharWidth: function() { return charWidth(this.display); },
+
+ setGutterMarker: methodOp(function(line, gutterID, value) {
+ return changeLine(this, line, "gutter", function(line) {
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
+ markers[gutterID] = value;
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
+ return true;
+ });
+ }),
+
+ clearGutter: methodOp(function(gutterID) {
+ var cm = this, doc = cm.doc, i = doc.first;
+ doc.iter(function(line) {
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+ line.gutterMarkers[gutterID] = null;
+ regLineChange(cm, i, "gutter");
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
+ }
+ ++i;
+ });
+ }),
+
+ addLineClass: methodOp(function(handle, where, cls) {
+ return changeLine(this, handle, "class", function(line) {
+ var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
+ if (!line[prop]) line[prop] = cls;
+ else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false;
+ else line[prop] += " " + cls;
+ return true;
+ });
+ }),
+
+ removeLineClass: methodOp(function(handle, where, cls) {
+ return changeLine(this, handle, "class", function(line) {
+ var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass";
+ var cur = line[prop];
+ if (!cur) return false;
+ else if (cls == null) line[prop] = null;
+ else {
+ var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)"));
+ if (!found) return false;
+ var end = found.index + found[0].length;
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
+ }
+ return true;
+ });
+ }),
+
+ addLineWidget: methodOp(function(handle, node, options) {
+ return addLineWidget(this, handle, node, options);
+ }),
+
+ removeLineWidget: function(widget) { widget.clear(); },
+
+ lineInfo: function(line) {
+ if (typeof line == "number") {
+ if (!isLine(this.doc, line)) return null;
+ var n = line;
+ line = getLine(this.doc, line);
+ if (!line) return null;
+ } else {
+ var n = lineNo(line);
+ if (n == null) return null;
+ }
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+ widgets: line.widgets};
+ },
+
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
+
+ addWidget: function(pos, node, scroll, vert, horiz) {
+ var display = this.display;
+ pos = cursorCoords(this, clipPos(this.doc, pos));
+ var top = pos.bottom, left = pos.left;
+ node.style.position = "absolute";
+ display.sizer.appendChild(node);
+ if (vert == "over") {
+ top = pos.top;
+ } else if (vert == "above" || vert == "near") {
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
+ top = pos.top - node.offsetHeight;
+ else if (pos.bottom + node.offsetHeight <= vspace)
+ top = pos.bottom;
+ if (left + node.offsetWidth > hspace)
+ left = hspace - node.offsetWidth;
+ }
+ node.style.top = top + "px";
+ node.style.left = node.style.right = "";
+ if (horiz == "right") {
+ left = display.sizer.clientWidth - node.offsetWidth;
+ node.style.right = "0px";
+ } else {
+ if (horiz == "left") left = 0;
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
+ node.style.left = left + "px";
+ }
+ if (scroll)
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
+ },
+
+ triggerOnKeyDown: methodOp(onKeyDown),
+ triggerOnKeyPress: methodOp(onKeyPress),
+ triggerOnKeyUp: methodOp(onKeyUp),
+
+ execCommand: function(cmd) {
+ if (commands.hasOwnProperty(cmd))
+ return commands[cmd](this);
+ },
+
+ findPosH: function(from, amount, unit, visually) {
+ var dir = 1;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
+ cur = findPosH(this.doc, cur, dir, unit, visually);
+ if (cur.hitSide) break;
+ }
+ return cur;
+ },
+
+ moveH: methodOp(function(dir, unit) {
+ var cm = this;
+ cm.extendSelectionsBy(function(range) {
+ if (cm.display.shift || cm.doc.extend || range.empty())
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
+ else
+ return dir < 0 ? range.from() : range.to();
+ }, sel_move);
+ }),
+
+ deleteH: methodOp(function(dir, unit) {
+ var sel = this.doc.sel, doc = this.doc;
+ if (sel.somethingSelected())
+ doc.replaceSelection("", null, "+delete");
+ else
+ deleteNearSelection(this, function(range) {
+ var other = findPosH(doc, range.head, dir, unit, false);
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
+ });
+ }),
+
+ findPosV: function(from, amount, unit, goalColumn) {
+ var dir = 1, x = goalColumn;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
+ var coords = cursorCoords(this, cur, "div");
+ if (x == null) x = coords.left;
+ else coords.left = x;
+ cur = findPosV(this, coords, dir, unit);
+ if (cur.hitSide) break;
+ }
+ return cur;
+ },
+
+ moveV: methodOp(function(dir, unit) {
+ var cm = this, doc = this.doc, goals = [];
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
+ doc.extendSelectionsBy(function(range) {
+ if (collapse)
+ return dir < 0 ? range.from() : range.to();
+ var headPos = cursorCoords(cm, range.head, "div");
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
+ goals.push(headPos.left);
+ var pos = findPosV(cm, headPos, dir, unit);
+ if (unit == "page" && range == doc.sel.primary())
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
+ return pos;
+ }, sel_move);
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
+ doc.sel.ranges[i].goalColumn = goals[i];
+ }),
+
+ toggleOverwrite: function(value) {
+ if (value != null && value == this.state.overwrite) return;
+ if (this.state.overwrite = !this.state.overwrite)
+ this.display.cursorDiv.className += " CodeMirror-overwrite";
+ else
+ this.display.cursorDiv.className = this.display.cursorDiv.className.replace(" CodeMirror-overwrite", "");
+
+ signal(this, "overwriteToggle", this, this.state.overwrite);
+ },
+ hasFocus: function() { return activeElt() == this.display.input; },
+
+ scrollTo: methodOp(function(x, y) {
+ if (x != null || y != null) resolveScrollToPos(this);
+ if (x != null) this.curOp.scrollLeft = x;
+ if (y != null) this.curOp.scrollTop = y;
+ }),
+ getScrollInfo: function() {
+ var scroller = this.display.scroller, co = scrollerCutOff;
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
+ height: scroller.scrollHeight - co, width: scroller.scrollWidth - co,
+ clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co};
+ },
+
+ scrollIntoView: methodOp(function(range, margin) {
+ if (range == null) {
+ range = {from: this.doc.sel.primary().head, to: null};
+ if (margin == null) margin = this.options.cursorScrollMargin;
+ } else if (typeof range == "number") {
+ range = {from: Pos(range, 0), to: null};
+ } else if (range.from == null) {
+ range = {from: range, to: null};
+ }
+ if (!range.to) range.to = range.from;
+ range.margin = margin || 0;
+
+ if (range.from.line != null) {
+ resolveScrollToPos(this);
+ this.curOp.scrollToPos = range;
+ } else {
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
+ Math.min(range.from.top, range.to.top) - range.margin,
+ Math.max(range.from.right, range.to.right),
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
+ }
+ }),
+
+ setSize: methodOp(function(width, height) {
+ function interpret(val) {
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
+ }
+ if (width != null) this.display.wrapper.style.width = interpret(width);
+ if (height != null) this.display.wrapper.style.height = interpret(height);
+ if (this.options.lineWrapping) clearLineMeasurementCache(this);
+ this.curOp.forceUpdate = true;
+ signal(this, "refresh", this);
+ }),
+
+ operation: function(f){return runInOp(this, f);},
+
+ refresh: methodOp(function() {
+ var oldHeight = this.display.cachedTextHeight;
+ regChange(this);
+ clearCaches(this);
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
+ estimateLineHeights(this);
+ signal(this, "refresh", this);
+ }),
+
+ swapDoc: methodOp(function(doc) {
+ var old = this.doc;
+ old.cm = null;
+ attachDoc(this, doc);
+ clearCaches(this);
+ resetInput(this);
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
+ signalLater(this, "swapDoc", this, old);
+ return old;
+ }),
+
+ getInputField: function(){return this.display.input;},
+ getWrapperElement: function(){return this.display.wrapper;},
+ getScrollerElement: function(){return this.display.scroller;},
+ getGutterElement: function(){return this.display.gutters;}
+ };
+ eventMixin(CodeMirror);
+
+ // OPTION DEFAULTS
+
+ // The default configuration options.
+ var defaults = CodeMirror.defaults = {};
+ // Functions to run when options are changed.
+ var optionHandlers = CodeMirror.optionHandlers = {};
+
+ function option(name, deflt, handle, notOnInit) {
+ CodeMirror.defaults[name] = deflt;
+ if (handle) optionHandlers[name] =
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
+ }
+
+ // Passed to option handlers when there is no old value.
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
+
+ // These two are, on init, called from the constructor because they
+ // have to be initialized before the editor can start at all.
+ option("value", "", function(cm, val) {
+ cm.setValue(val);
+ }, true);
+ option("mode", null, function(cm, val) {
+ cm.doc.modeOption = val;
+ loadMode(cm);
+ }, true);
+
+ option("indentUnit", 2, loadMode, true);
+ option("indentWithTabs", false);
+ option("smartIndent", true);
+ option("tabSize", 4, function(cm) {
+ resetModeState(cm);
+ clearCaches(cm);
+ regChange(cm);
+ }, true);
+ option("specialChars", /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g, function(cm, val) {
+ cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
+ cm.refresh();
+ }, true);
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
+ option("electricChars", true);
+ option("rtlMoveVisually", !windows);
+ option("wholeLineUpdateBefore", true);
+
+ option("theme", "default", function(cm) {
+ themeChanged(cm);
+ guttersChanged(cm);
+ }, true);
+ option("keyMap", "default", keyMapChanged);
+ option("extraKeys", null);
+
+ option("lineWrapping", false, wrappingChanged, true);
+ option("gutters", [], function(cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("fixedGutter", true, function(cm, val) {
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
+ cm.refresh();
+ }, true);
+ option("coverGutterNextToScrollbar", false, updateScrollbars, true);
+ option("lineNumbers", false, function(cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("firstLineNumber", 1, guttersChanged, true);
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
+ option("showCursorWhenSelecting", false, updateSelection, true);
+
+ option("resetSelectionOnContextMenu", true);
+
+ option("readOnly", false, function(cm, val) {
+ if (val == "nocursor") {
+ onBlur(cm);
+ cm.display.input.blur();
+ cm.display.disabled = true;
+ } else {
+ cm.display.disabled = false;
+ if (!val) resetInput(cm);
+ }
+ });
+ option("disableInput", false, function(cm, val) {if (!val) resetInput(cm);}, true);
+ option("dragDrop", true);
+
+ option("cursorBlinkRate", 530);
+ option("cursorScrollMargin", 0);
+ option("cursorHeight", 1);
+ option("workTime", 100);
+ option("workDelay", 100);
+ option("flattenSpans", true, resetModeState, true);
+ option("addModeClass", false, resetModeState, true);
+ option("pollInterval", 100);
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
+ option("historyEventDelay", 1250);
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
+ option("maxHighlightLength", 10000, resetModeState, true);
+ option("moveInputWithCursor", true, function(cm, val) {
+ if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0;
+ });
+
+ option("tabindex", null, function(cm, val) {
+ cm.display.input.tabIndex = val || "";
+ });
+ option("autofocus", null);
+
+ // MODE DEFINITION AND QUERYING
+
+ // Known modes, by name and by MIME
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
+
+ // Extra arguments are stored as the mode's dependencies, which is
+ // used by (legacy) mechanisms like loadmode.js to automatically
+ // load a mode. (Preferred mechanism is the require/define calls.)
+ CodeMirror.defineMode = function(name, mode) {
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
+ if (arguments.length > 2) {
+ mode.dependencies = [];
+ for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]);
+ }
+ modes[name] = mode;
+ };
+
+ CodeMirror.defineMIME = function(mime, spec) {
+ mimeModes[mime] = spec;
+ };
+
+ // Given a MIME type, a {name, ...options} config object, or a name
+ // string, return a mode config object.
+ CodeMirror.resolveMode = function(spec) {
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+ spec = mimeModes[spec];
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+ var found = mimeModes[spec.name];
+ if (typeof found == "string") found = {name: found};
+ spec = createObj(found, spec);
+ spec.name = found.name;
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+ return CodeMirror.resolveMode("application/xml");
+ }
+ if (typeof spec == "string") return {name: spec};
+ else return spec || {name: "null"};
+ };
+
+ // Given a mode spec (anything that resolveMode accepts), find and
+ // initialize an actual mode object.
+ CodeMirror.getMode = function(options, spec) {
+ var spec = CodeMirror.resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
+ var modeObj = mfactory(options, spec);
+ if (modeExtensions.hasOwnProperty(spec.name)) {
+ var exts = modeExtensions[spec.name];
+ for (var prop in exts) {
+ if (!exts.hasOwnProperty(prop)) continue;
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
+ modeObj[prop] = exts[prop];
+ }
+ }
+ modeObj.name = spec.name;
+ if (spec.helperType) modeObj.helperType = spec.helperType;
+ if (spec.modeProps) for (var prop in spec.modeProps)
+ modeObj[prop] = spec.modeProps[prop];
+
+ return modeObj;
+ };
+
+ // Minimal default mode.
+ CodeMirror.defineMode("null", function() {
+ return {token: function(stream) {stream.skipToEnd();}};
+ });
+ CodeMirror.defineMIME("text/plain", "null");
+
+ // This can be used to attach properties to mode objects from
+ // outside the actual mode definition.
+ var modeExtensions = CodeMirror.modeExtensions = {};
+ CodeMirror.extendMode = function(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ copyObj(properties, exts);
+ };
+
+ // EXTENSIONS
+
+ CodeMirror.defineExtension = function(name, func) {
+ CodeMirror.prototype[name] = func;
+ };
+ CodeMirror.defineDocExtension = function(name, func) {
+ Doc.prototype[name] = func;
+ };
+ CodeMirror.defineOption = option;
+
+ var initHooks = [];
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
+
+ var helpers = CodeMirror.helpers = {};
+ CodeMirror.registerHelper = function(type, name, value) {
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
+ helpers[type][name] = value;
+ };
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
+ CodeMirror.registerHelper(type, name, value);
+ helpers[type]._global.push({pred: predicate, val: value});
+ };
+
+ // MODE STATE HANDLING
+
+ // Utility functions for working with state. Exported because nested
+ // modes need to do this for their inner modes.
+
+ var copyState = CodeMirror.copyState = function(mode, state) {
+ if (state === true) return state;
+ if (mode.copyState) return mode.copyState(state);
+ var nstate = {};
+ for (var n in state) {
+ var val = state[n];
+ if (val instanceof Array) val = val.concat([]);
+ nstate[n] = val;
+ }
+ return nstate;
+ };
+
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true;
+ };
+
+ // Given a mode and a state (for that mode), find the inner mode and
+ // state at the position that the state refers to.
+ CodeMirror.innerMode = function(mode, state) {
+ while (mode.innerMode) {
+ var info = mode.innerMode(state);
+ if (!info || info.mode == mode) break;
+ state = info.state;
+ mode = info.mode;
+ }
+ return info || {mode: mode, state: state};
+ };
+
+ // STANDARD COMMANDS
+
+ // Commands are parameter-less actions that can be performed on an
+ // editor, mostly used for keybindings.
+ var commands = CodeMirror.commands = {
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
+ singleSelection: function(cm) {
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
+ },
+ killLine: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ if (range.empty()) {
+ var len = getLine(cm.doc, range.head.line).text.length;
+ if (range.head.ch == len && range.head.line < cm.lastLine())
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
+ else
+ return {from: range.head, to: Pos(range.head.line, len)};
+ } else {
+ return {from: range.from(), to: range.to()};
+ }
+ });
+ },
+ deleteLine: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ return {from: Pos(range.from().line, 0),
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
+ });
+ },
+ delLineLeft: function(cm) {
+ deleteNearSelection(cm, function(range) {
+ return {from: Pos(range.from().line, 0), to: range.from()};
+ });
+ },
+ undo: function(cm) {cm.undo();},
+ redo: function(cm) {cm.redo();},
+ undoSelection: function(cm) {cm.undoSelection();},
+ redoSelection: function(cm) {cm.redoSelection();},
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
+ goLineStart: function(cm) {
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, sel_move);
+ },
+ goLineStartSmart: function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ var start = lineStart(cm, range.head.line);
+ var line = cm.getLineHandle(start.line);
+ var order = getOrder(line);
+ if (!order || order[0].level == 0) {
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
+ var inWS = range.head.line == start.line && range.head.ch <= firstNonWS && range.head.ch;
+ return Pos(start.line, inWS ? 0 : firstNonWS);
+ }
+ return start;
+ }, sel_move);
+ },
+ goLineEnd: function(cm) {
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, sel_move);
+ },
+ goLineRight: function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
+ }, sel_move);
+ },
+ goLineLeft: function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: 0, top: top}, "div");
+ }, sel_move);
+ },
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
+ goLineDown: function(cm) {cm.moveV(1, "line");},
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
+ goPageDown: function(cm) {cm.moveV(1, "page");},
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
+ goCharRight: function(cm) {cm.moveH(1, "char");},
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
+ goWordRight: function(cm) {cm.moveH(1, "word");},
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
+ indentAuto: function(cm) {cm.indentSelection("smart");},
+ indentMore: function(cm) {cm.indentSelection("add");},
+ indentLess: function(cm) {cm.indentSelection("subtract");},
+ insertTab: function(cm) {cm.replaceSelection("\t");},
+ defaultTab: function(cm) {
+ if (cm.somethingSelected()) cm.indentSelection("add");
+ else cm.execCommand("insertTab");
+ },
+ transposeChars: function(cm) {
+ runInOp(cm, function() {
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
+ if (cur.ch > 0 && cur.ch < line.length - 1)
+ cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1),
+ Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
+ }
+ });
+ },
+ newlineAndIndent: function(cm) {
+ runInOp(cm, function() {
+ var len = cm.listSelections().length;
+ for (var i = 0; i < len; i++) {
+ var range = cm.listSelections()[i];
+ cm.replaceRange("\n", range.anchor, range.head, "+input");
+ cm.indentLine(range.from().line + 1, null, true);
+ ensureCursorVisible(cm);
+ }
+ });
+ },
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
+ };
+
+ // STANDARD KEYMAPS
+
+ var keyMap = CodeMirror.keyMap = {};
+ keyMap.basic = {
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
+ "Esc": "singleSelection"
+ };
+ // Note that the save and find-related commands aren't defined by
+ // default. User code or addons can define them. Unknown commands
+ // are simply ignored.
+ keyMap.pcDefault = {
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
+ "Ctrl-Home": "goDocStart", "Ctrl-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd",
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
+ fallthrough: "basic"
+ };
+ keyMap.macDefault = {
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+ "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore",
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft",
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection",
+ fallthrough: ["basic", "emacsy"]
+ };
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
+ keyMap.emacsy = {
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars"
+ };
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+
+ // KEYMAP DISPATCH
+
+ function getKeyMap(val) {
+ if (typeof val == "string") return keyMap[val];
+ else return val;
+ }
+
+ // Given an array of keymaps and a key name, call handle on any
+ // bindings found, until that returns a truthy value, at which point
+ // we consider the key handled. Implements things like binding a key
+ // to false stopping further handling and keymap fallthrough.
+ var lookupKey = CodeMirror.lookupKey = function(name, maps, handle) {
+ function lookup(map) {
+ map = getKeyMap(map);
+ var found = map[name];
+ if (found === false) return "stop";
+ if (found != null && handle(found)) return true;
+ if (map.nofallthrough) return "stop";
+
+ var fallthrough = map.fallthrough;
+ if (fallthrough == null) return false;
+ if (Object.prototype.toString.call(fallthrough) != "[object Array]")
+ return lookup(fallthrough);
+ for (var i = 0; i < fallthrough.length; ++i) {
+ var done = lookup(fallthrough[i]);
+ if (done) return done;
+ }
+ return false;
+ }
+
+ for (var i = 0; i < maps.length; ++i) {
+ var done = lookup(maps[i]);
+ if (done) return done != "stop";
+ }
+ };
+
+ // Modifier key presses don't count as 'real' key presses for the
+ // purpose of keymap fallthrough.
+ var isModifierKey = CodeMirror.isModifierKey = function(event) {
+ var name = keyNames[event.keyCode];
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
+ };
+
+ // Look up the name of a key as indicated by an event object.
+ var keyName = CodeMirror.keyName = function(event, noShift) {
+ if (presto && event.keyCode == 34 && event["char"]) return false;
+ var name = keyNames[event.keyCode];
+ if (name == null || event.altGraphKey) return false;
+ if (event.altKey) name = "Alt-" + name;
+ if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name;
+ if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name;
+ if (!noShift && event.shiftKey) name = "Shift-" + name;
+ return name;
+ };
+
+ // FROMTEXTAREA
+
+ CodeMirror.fromTextArea = function(textarea, options) {
+ if (!options) options = {};
+ options.value = textarea.value;
+ if (!options.tabindex && textarea.tabindex)
+ options.tabindex = textarea.tabindex;
+ if (!options.placeholder && textarea.placeholder)
+ options.placeholder = textarea.placeholder;
+ // Set autofocus to true if this textarea is focused, or if it has
+ // autofocus and no other element is focused.
+ if (options.autofocus == null) {
+ var hasFocus = activeElt();
+ options.autofocus = hasFocus == textarea ||
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
+ }
+
+ function save() {textarea.value = cm.getValue();}
+ if (textarea.form) {
+ on(textarea.form, "submit", save);
+ // Deplorable hack to make the submit method do the right thing.
+ if (!options.leaveSubmitMethodAlone) {
+ var form = textarea.form, realSubmit = form.submit;
+ try {
+ var wrappedSubmit = form.submit = function() {
+ save();
+ form.submit = realSubmit;
+ form.submit();
+ form.submit = wrappedSubmit;
+ };
+ } catch(e) {}
+ }
+ }
+
+ textarea.style.display = "none";
+ var cm = CodeMirror(function(node) {
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
+ }, options);
+ cm.save = save;
+ cm.getTextArea = function() { return textarea; };
+ cm.toTextArea = function() {
+ save();
+ textarea.parentNode.removeChild(cm.getWrapperElement());
+ textarea.style.display = "";
+ if (textarea.form) {
+ off(textarea.form, "submit", save);
+ if (typeof textarea.form.submit == "function")
+ textarea.form.submit = realSubmit;
+ }
+ };
+ return cm;
+ };
+
+ // STRING STREAM
+
+ // Fed to the mode parsers, provides helper functions to make
+ // parsers more succinct.
+
+ 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() {
+ if (this.lastColumnPos < this.start) {
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
+ this.lastColumnPos = this.start;
+ }
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
+ },
+ indentation: function() {
+ return countColumn(this.string, null, this.tabSize) -
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
+ },
+ 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; }
+ }
+ };
+
+ // TEXTMARKERS
+
+ // Created with markText and setBookmark methods. A TextMarker is a
+ // handle that can be used to clear or find a marked position in the
+ // document. Line objects hold arrays (markedSpans) containing
+ // {from, to, marker} object pointing to such marker objects, and
+ // indicating that such a marker is present on that line. Multiple
+ // lines may point to the same marker when it spans across lines.
+ // The spans will have null for their from/to properties when the
+ // marker continues beyond the start/end of the line. Markers have
+ // links back to the lines they currently touch.
+
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
+ this.lines = [];
+ this.type = type;
+ this.doc = doc;
+ };
+ eventMixin(TextMarker);
+
+ // Clear the marker.
+ TextMarker.prototype.clear = function() {
+ if (this.explicitlyCleared) return;
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
+ if (withOp) startOperation(cm);
+ if (hasHandler(this, "clear")) {
+ var found = this.find();
+ if (found) signalLater(this, "clear", found.from, found.to);
+ }
+ var min = null, max = null;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
+ else if (cm) {
+ if (span.to != null) max = lineNo(line);
+ if (span.from != null) min = lineNo(line);
+ }
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
+ updateLineHeight(line, textHeight(cm.display));
+ }
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
+ if (len > cm.display.maxLineLength) {
+ cm.display.maxLine = visual;
+ cm.display.maxLineLength = len;
+ cm.display.maxLineChanged = true;
+ }
+ }
+
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
+ this.lines.length = 0;
+ this.explicitlyCleared = true;
+ if (this.atomic && this.doc.cantEdit) {
+ this.doc.cantEdit = false;
+ if (cm) reCheckSelection(cm.doc);
+ }
+ if (cm) signalLater(cm, "markerCleared", cm, this);
+ if (withOp) endOperation(cm);
+ };
+
+ // Find the position of the marker in the document. Returns a {from,
+ // to} object by default. Side can be passed to get a specific side
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
+ // Pos objects returned contain a line object, rather than a line
+ // number (used to prevent looking up the same line twice).
+ TextMarker.prototype.find = function(side, lineObj) {
+ if (side == null && this.type == "bookmark") side = 1;
+ var from, to;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this);
+ if (span.from != null) {
+ from = Pos(lineObj ? line : lineNo(line), span.from);
+ if (side == -1) return from;
+ }
+ if (span.to != null) {
+ to = Pos(lineObj ? line : lineNo(line), span.to);
+ if (side == 1) return to;
+ }
+ }
+ return from && {from: from, to: to};
+ };
+
+ // Signals that the marker's widget changed, and surrounding layout
+ // should be recomputed.
+ TextMarker.prototype.changed = function() {
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
+ if (!pos || !cm) return;
+ runInOp(cm, function() {
+ var line = pos.line, lineN = lineNo(pos.line);
+ var view = findViewForLine(cm, lineN);
+ if (view) {
+ clearLineMeasurementCacheFor(view);
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
+ }
+ cm.curOp.updateMaxLine = true;
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
+ var oldHeight = widget.height;
+ widget.height = null;
+ var dHeight = widgetHeight(widget) - oldHeight;
+ if (dHeight)
+ updateLineHeight(line, line.height + dHeight);
+ }
+ });
+ };
+
+ TextMarker.prototype.attachLine = function(line) {
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
+ }
+ this.lines.push(line);
+ };
+ TextMarker.prototype.detachLine = function(line) {
+ this.lines.splice(indexOf(this.lines, line), 1);
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
+ }
+ };
+
+ // Collapsed markers have unique ids, in order to be able to order
+ // them, which is needed for uniquely determining an outer marker
+ // when they overlap (they may nest, but not partially overlap).
+ var nextMarkerId = 0;
+
+ // Create a marker, wire it up to the right lines, and
+ function markText(doc, from, to, options, type) {
+ // Shared markers (across linked documents) are handled separately
+ // (markTextShared will call out to this again, once per
+ // document).
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
+ // Ensure we are in an operation.
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
+
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
+ if (options) copyObj(options, marker);
+ // Don't connect empty markers unless clearWhenEmpty is false
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
+ return marker;
+ if (marker.replacedWith) {
+ // Showing up as a widget implies collapsed (widget replaces text)
+ marker.collapsed = true;
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
+ if (!options.handleMouseEvents) marker.widgetNode.ignoreEvents = true;
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
+ }
+ if (marker.collapsed) {
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
+ sawCollapsedSpans = true;
+ }
+
+ if (marker.addToHistory)
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
+
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
+ doc.iter(curLine, to.line + 1, function(line) {
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
+ updateMaxLine = true;
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
+ addMarkedSpan(line, new MarkedSpan(marker,
+ curLine == from.line ? from.ch : null,
+ curLine == to.line ? to.ch : null));
+ ++curLine;
+ });
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
+ });
+
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
+
+ if (marker.readOnly) {
+ sawReadOnlySpans = true;
+ if (doc.history.done.length || doc.history.undone.length)
+ doc.clearHistory();
+ }
+ if (marker.collapsed) {
+ marker.id = ++nextMarkerId;
+ marker.atomic = true;
+ }
+ if (cm) {
+ // Sync editor state
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
+ if (marker.collapsed)
+ regChange(cm, from.line, to.line + 1);
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle)
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
+ if (marker.atomic) reCheckSelection(cm.doc);
+ signalLater(cm, "markerAdded", cm, marker);
+ }
+ return marker;
+ }
+
+ // SHARED TEXTMARKERS
+
+ // A shared marker spans multiple linked documents. It is
+ // implemented as a meta-marker-object controlling multiple normal
+ // markers.
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
+ this.markers = markers;
+ this.primary = primary;
+ for (var i = 0, me = this; i < markers.length; ++i) {
+ markers[i].parent = this;
+ on(markers[i], "clear", function(){me.clear();});
+ }
+ };
+ eventMixin(SharedTextMarker);
+
+ SharedTextMarker.prototype.clear = function() {
+ if (this.explicitlyCleared) return;
+ this.explicitlyCleared = true;
+ for (var i = 0; i < this.markers.length; ++i)
+ this.markers[i].clear();
+ signalLater(this, "clear");
+ };
+ SharedTextMarker.prototype.find = function(side, lineObj) {
+ return this.primary.find(side, lineObj);
+ };
+
+ function markTextShared(doc, from, to, options, type) {
+ options = copyObj(options);
+ options.shared = false;
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
+ var widget = options.widgetNode;
+ linkedDocs(doc, function(doc) {
+ if (widget) options.widgetNode = widget.cloneNode(true);
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
+ for (var i = 0; i < doc.linked.length; ++i)
+ if (doc.linked[i].isParent) return;
+ primary = lst(markers);
+ });
+ return new SharedTextMarker(markers, primary);
+ }
+
+ // TEXTMARKER SPANS
+
+ function MarkedSpan(marker, from, to) {
+ this.marker = marker;
+ this.from = from; this.to = to;
+ }
+
+ // Search an array of spans for a span matching the given marker.
+ function getMarkedSpanFor(spans, marker) {
+ if (spans) for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.marker == marker) return span;
+ }
+ }
+ // Remove a span from an array, returning undefined if no spans are
+ // left (we don't store arrays for lines without spans).
+ function removeMarkedSpan(spans, span) {
+ for (var r, i = 0; i < spans.length; ++i)
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
+ return r;
+ }
+ // Add a span to a line.
+ function addMarkedSpan(line, span) {
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
+ span.marker.attachLine(line);
+ }
+
+ // Used for the algorithm that adjusts markers for a change in the
+ // document. These functions cut an array of spans at a given
+ // character position, returning an array of remaining chunks (or
+ // undefined if nothing remains).
+ function markedSpansBefore(old, startCh, isInsert) {
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
+ }
+ }
+ return nw;
+ }
+ function markedSpansAfter(old, endCh, isInsert) {
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
+ span.to == null ? null : span.to - endCh));
+ }
+ }
+ return nw;
+ }
+
+ // Given a change object, compute the new set of marker spans that
+ // cover the line in which the change took place. Removes spans
+ // entirely within the change, reconnects spans belonging to the
+ // same marker that appear on both sides of the change, and cuts off
+ // spans partially within the change. Returns an array of span
+ // arrays with one element for each line in (after) the change.
+ function stretchSpansOverChange(doc, change) {
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
+ if (!oldFirst && !oldLast) return null;
+
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
+ // Get the spans that 'stick out' on both sides
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
+
+ // Next, merge those two ends
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
+ if (first) {
+ // Fix up .to properties of first
+ for (var i = 0; i < first.length; ++i) {
+ var span = first[i];
+ if (span.to == null) {
+ var found = getMarkedSpanFor(last, span.marker);
+ if (!found) span.to = startCh;
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
+ }
+ }
+ }
+ if (last) {
+ // Fix up .from in last (or move them into first in case of sameLine)
+ for (var i = 0; i < last.length; ++i) {
+ var span = last[i];
+ if (span.to != null) span.to += offset;
+ if (span.from == null) {
+ var found = getMarkedSpanFor(first, span.marker);
+ if (!found) {
+ span.from = offset;
+ if (sameLine) (first || (first = [])).push(span);
+ }
+ } else {
+ span.from += offset;
+ if (sameLine) (first || (first = [])).push(span);
+ }
+ }
+ }
+ // Make sure we didn't create any zero-length spans
+ if (first) first = clearEmptySpans(first);
+ if (last && last != first) last = clearEmptySpans(last);
+
+ var newMarkers = [first];
+ if (!sameLine) {
+ // Fill gap with whole-line-spans
+ var gap = change.text.length - 2, gapMarkers;
+ if (gap > 0 && first)
+ for (var i = 0; i < first.length; ++i)
+ if (first[i].to == null)
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
+ for (var i = 0; i < gap; ++i)
+ newMarkers.push(gapMarkers);
+ newMarkers.push(last);
+ }
+ return newMarkers;
+ }
+
+ // Remove spans that are empty and don't have a clearWhenEmpty
+ // option of false.
+ function clearEmptySpans(spans) {
+ for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
+ spans.splice(i--, 1);
+ }
+ if (!spans.length) return null;
+ return spans;
+ }
+
+ // Used for un/re-doing changes from the history. Combines the
+ // result of computing the existing spans with the set of spans that
+ // existed in the history (so that deleting around a span and then
+ // undoing brings back the span).
+ function mergeOldSpans(doc, change) {
+ var old = getOldSpans(doc, change);
+ var stretched = stretchSpansOverChange(doc, change);
+ if (!old) return stretched;
+ if (!stretched) return old;
+
+ for (var i = 0; i < old.length; ++i) {
+ var oldCur = old[i], stretchCur = stretched[i];
+ if (oldCur && stretchCur) {
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
+ var span = stretchCur[j];
+ for (var k = 0; k < oldCur.length; ++k)
+ if (oldCur[k].marker == span.marker) continue spans;
+ oldCur.push(span);
+ }
+ } else if (stretchCur) {
+ old[i] = stretchCur;
+ }
+ }
+ return old;
+ }
+
+ // Used to 'clip' out readOnly ranges when making a change.
+ function removeReadOnlyRanges(doc, from, to) {
+ var markers = null;
+ doc.iter(from.line, to.line + 1, function(line) {
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
+ var mark = line.markedSpans[i].marker;
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+ (markers || (markers = [])).push(mark);
+ }
+ });
+ if (!markers) return null;
+ var parts = [{from: from, to: to}];
+ for (var i = 0; i < markers.length; ++i) {
+ var mk = markers[i], m = mk.find(0);
+ for (var j = 0; j < parts.length; ++j) {
+ var p = parts[j];
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
+ newParts.push({from: p.from, to: m.from});
+ if (dto > 0 || !mk.inclusiveRight && !dto)
+ newParts.push({from: m.to, to: p.to});
+ parts.splice.apply(parts, newParts);
+ j += newParts.length - 1;
+ }
+ }
+ return parts;
+ }
+
+ // Connect or disconnect spans from a line.
+ function detachMarkedSpans(line) {
+ var spans = line.markedSpans;
+ if (!spans) return;
+ for (var i = 0; i < spans.length; ++i)
+ spans[i].marker.detachLine(line);
+ line.markedSpans = null;
+ }
+ function attachMarkedSpans(line, spans) {
+ if (!spans) return;
+ for (var i = 0; i < spans.length; ++i)
+ spans[i].marker.attachLine(line);
+ line.markedSpans = spans;
+ }
+
+ // Helpers used when computing which overlapping collapsed span
+ // counts as the larger one.
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
+
+ // Returns a number indicating which of two overlapping collapsed
+ // spans is larger (and thus includes the other). Falls back to
+ // comparing ids when the spans cover exactly the same range.
+ function compareCollapsedMarkers(a, b) {
+ var lenDiff = a.lines.length - b.lines.length;
+ if (lenDiff != 0) return lenDiff;
+ var aPos = a.find(), bPos = b.find();
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
+ if (fromCmp) return -fromCmp;
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
+ if (toCmp) return toCmp;
+ return b.id - a.id;
+ }
+
+ // Find out whether a line ends or starts in a collapsed span. If
+ // so, return the marker for that span.
+ function collapsedSpanAtSide(line, start) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
+ found = sp.marker;
+ }
+ return found;
+ }
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
+
+ // Test whether there exists a collapsed span that partially
+ // overlaps (covers the start or end, but not both) of a new span.
+ // Such overlap is not allowed.
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
+ var line = getLine(doc, lineNo);
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) for (var i = 0; i < sps.length; ++i) {
+ var sp = sps[i];
+ if (!sp.marker.collapsed) continue;
+ var found = sp.marker.find(0);
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
+ if (fromCmp <= 0 && (cmp(found.to, from) || extraRight(sp.marker) - extraLeft(marker)) > 0 ||
+ fromCmp >= 0 && (cmp(found.from, to) || extraLeft(sp.marker) - extraRight(marker)) < 0)
+ return true;
+ }
+ }
+
+ // A visual line is a line as drawn on the screen. Folding, for
+ // example, can cause multiple logical lines to appear on the same
+ // visual line. This finds the start of the visual line that the
+ // given line is part of (usually that is the line itself).
+ function visualLine(line) {
+ var merged;
+ while (merged = collapsedSpanAtStart(line))
+ line = merged.find(-1, true).line;
+ return line;
+ }
+
+ // Returns an array of logical lines that continue the visual line
+ // started by the argument, or undefined if there are no such lines.
+ function visualLineContinued(line) {
+ var merged, lines;
+ while (merged = collapsedSpanAtEnd(line)) {
+ line = merged.find(1, true).line;
+ (lines || (lines = [])).push(line);
+ }
+ return lines;
+ }
+
+ // Get the line number of the start of the visual line that the
+ // given line number is part of.
+ function visualLineNo(doc, lineN) {
+ var line = getLine(doc, lineN), vis = visualLine(line);
+ if (line == vis) return lineN;
+ return lineNo(vis);
+ }
+ // Get the line number of the start of the next visual line after
+ // the given line.
+ function visualLineEndNo(doc, lineN) {
+ if (lineN > doc.lastLine()) return lineN;
+ var line = getLine(doc, lineN), merged;
+ if (!lineIsHidden(doc, line)) return lineN;
+ while (merged = collapsedSpanAtEnd(line))
+ line = merged.find(1, true).line;
+ return lineNo(line) + 1;
+ }
+
+ // Compute whether a line is hidden. Lines count as hidden when they
+ // are part of a visual line that starts with another line, or when
+ // they are entirely covered by collapsed, non-widget span.
+ function lineIsHidden(doc, line) {
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (!sp.marker.collapsed) continue;
+ if (sp.from == null) return true;
+ if (sp.marker.widgetNode) continue;
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
+ return true;
+ }
+ }
+ function lineIsHiddenInner(doc, line, span) {
+ if (span.to == null) {
+ var end = span.marker.find(1, true);
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
+ }
+ if (span.marker.inclusiveRight && span.to == line.text.length)
+ return true;
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
+ sp = line.markedSpans[i];
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
+ (sp.to == null || sp.to != span.from) &&
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+ lineIsHiddenInner(doc, line, sp)) return true;
+ }
+ }
+
+ // LINE WIDGETS
+
+ // Line widgets are block elements displayed above or below a line.
+
+ var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
+ this[opt] = options[opt];
+ this.cm = cm;
+ this.node = node;
+ };
+ eventMixin(LineWidget);
+
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
+ addToScrollPos(cm, null, diff);
+ }
+
+ LineWidget.prototype.clear = function() {
+ var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
+ if (no == null || !ws) return;
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
+ if (!ws.length) line.widgets = null;
+ var height = widgetHeight(this);
+ runInOp(cm, function() {
+ adjustScrollWhenAboveVisible(cm, line, -height);
+ regLineChange(cm, no, "widget");
+ updateLineHeight(line, Math.max(0, line.height - height));
+ });
+ };
+ LineWidget.prototype.changed = function() {
+ var oldH = this.height, cm = this.cm, line = this.line;
+ this.height = null;
+ var diff = widgetHeight(this) - oldH;
+ if (!diff) return;
+ runInOp(cm, function() {
+ cm.curOp.forceUpdate = true;
+ adjustScrollWhenAboveVisible(cm, line, diff);
+ updateLineHeight(line, line.height + diff);
+ });
+ };
+
+ function widgetHeight(widget) {
+ if (widget.height != null) return widget.height;
+ if (!contains(document.body, widget.node))
+ removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative"));
+ return widget.height = widget.node.offsetHeight;
+ }
+
+ function addLineWidget(cm, handle, node, options) {
+ var widget = new LineWidget(cm, node, options);
+ if (widget.noHScroll) cm.display.alignWidgets = true;
+ changeLine(cm, handle, "widget", function(line) {
+ var widgets = line.widgets || (line.widgets = []);
+ if (widget.insertAt == null) widgets.push(widget);
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
+ widget.line = line;
+ if (!lineIsHidden(cm.doc, line)) {
+ var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
+ updateLineHeight(line, line.height + widgetHeight(widget));
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
+ cm.curOp.forceUpdate = true;
+ }
+ return true;
+ });
+ return widget;
+ }
+
+ // LINE DATA STRUCTURE
+
+ // Line objects. These hold state related to a line, including
+ // highlighting info (the styles array).
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
+ this.text = text;
+ attachMarkedSpans(this, markedSpans);
+ this.height = estimateHeight ? estimateHeight(this) : 1;
+ };
+ eventMixin(Line);
+ Line.prototype.lineNo = function() { return lineNo(this); };
+
+ // Change the content (text, markers) of a line. Automatically
+ // invalidates cached information and tries to re-estimate the
+ // line's height.
+ function updateLine(line, text, markedSpans, estimateHeight) {
+ line.text = text;
+ if (line.stateAfter) line.stateAfter = null;
+ if (line.styles) line.styles = null;
+ if (line.order != null) line.order = null;
+ detachMarkedSpans(line);
+ attachMarkedSpans(line, markedSpans);
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
+ }
+
+ // Detach a line from the document tree and its markers.
+ function cleanUpLine(line) {
+ line.parent = null;
+ detachMarkedSpans(line);
+ }
+
+ // Run the given mode's parser over a line, calling f for each token.
+ function runMode(cm, text, mode, state, f, forceToEnd) {
+ var flattenSpans = mode.flattenSpans;
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
+ var curStart = 0, curStyle = null;
+ var stream = new StringStream(text, cm.options.tabSize), style;
+ if (text == "" && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol()) {
+ if (stream.pos > cm.options.maxHighlightLength) {
+ flattenSpans = false;
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
+ stream.pos = text.length;
+ style = null;
+ } else {
+ style = mode.token(stream, state);
+ }
+ if (cm.options.addModeClass) {
+ var mName = CodeMirror.innerMode(mode, state).mode.name;
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
+ }
+ if (!flattenSpans || curStyle != style) {
+ if (curStart < stream.start) f(stream.start, curStyle);
+ curStart = stream.start; curStyle = style;
+ }
+ stream.start = stream.pos;
+ }
+ while (curStart < stream.pos) {
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
+ var pos = Math.min(stream.pos, curStart + 50000);
+ f(pos, curStyle);
+ curStart = pos;
+ }
+ }
+
+ // Compute a style array (an array starting with a mode generation
+ // -- for invalidation -- followed by pairs of end positions and
+ // style strings), which is used to highlight the tokens on the
+ // line.
+ function highlightLine(cm, line, state, forceToEnd) {
+ // A styles array always starts with a number identifying the
+ // mode/overlays that it is based on (for easy invalidation).
+ var st = [cm.state.modeGen];
+ // Compute the base array of styles
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
+ st.push(end, style);
+ }, forceToEnd);
+
+ // Run overlays, adjust style array.
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
+ var start = i;
+ // Ensure there's a token end at the current position, and that i points at it
+ while (at < end) {
+ var i_end = st[i];
+ if (i_end > end)
+ st.splice(i, 1, end, st[i+1], i_end);
+ i += 2;
+ at = Math.min(end, i_end);
+ }
+ if (!style) return;
+ if (overlay.opaque) {
+ st.splice(start, i - start, end, style);
+ i = start + 2;
+ } else {
+ for (; start < i; start += 2) {
+ var cur = st[start+1];
+ st[start+1] = cur ? cur + " " + style : style;
+ }
+ }
+ });
+ }
+
+ return st;
+ }
+
+ function getLineStyles(cm, line) {
+ if (!line.styles || line.styles[0] != cm.state.modeGen)
+ line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line)));
+ return line.styles;
+ }
+
+ // Lightweight form of highlight -- proceed over this line and
+ // update state, but don't save a style array. Used for lines that
+ // aren't currently visible.
+ function processLine(cm, text, state, startAt) {
+ var mode = cm.doc.mode;
+ var stream = new StringStream(text, cm.options.tabSize);
+ stream.start = stream.pos = startAt || 0;
+ if (text == "" && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) {
+ mode.token(stream, state);
+ stream.start = stream.pos;
+ }
+ }
+
+ // Convert a style as returned by a mode (either null, or a string
+ // containing one or more styles) to a CSS style. This is cached,
+ // and also looks for line-wide styles.
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
+ function interpretTokenStyle(style, builder) {
+ if (!style) return null;
+ for (;;) {
+ var lineClass = style.match(/(?:^|\s+)line-(background-)?(\S+)/);
+ if (!lineClass) break;
+ style = style.slice(0, lineClass.index) + style.slice(lineClass.index + lineClass[0].length);
+ var prop = lineClass[1] ? "bgClass" : "textClass";
+ if (builder[prop] == null)
+ builder[prop] = lineClass[2];
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(builder[prop]))
+ builder[prop] += " " + lineClass[2];
+ }
+ if (/^\s*$/.test(style)) return null;
+ var cache = builder.cm.options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
+ return cache[style] ||
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
+ }
+
+ // Render the DOM representation of the text of a line. Also builds
+ // up a 'line map', which points at the DOM nodes that represent
+ // specific stretches of text, and is used by the measuring code.
+ // The returned object contains the DOM node, this map, and
+ // information about line-wide styles that were set by the mode.
+ function buildLineContent(cm, lineView) {
+ // The padding-right forces the element to have a 'border', which
+ // is needed on Webkit to be able to get line-level bounding
+ // rectangles for it (in measureChar).
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
+ var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
+ lineView.measure = {};
+
+ // Iterate over the logical lines that make up this visual line.
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
+ builder.pos = 0;
+ builder.addToken = buildToken;
+ // Optionally wire in some hacks into the token-rendering
+ // algorithm, to deal with browser quirks.
+ if ((ie || webkit) && cm.getOption("lineWrapping"))
+ builder.addToken = buildTokenSplitSpaces(builder.addToken);
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
+ builder.map = [];
+ insertLineContent(line, builder, getLineStyles(cm, line));
+
+ // Ensure at least a single node is present, for measuring.
+ if (builder.map.length == 0)
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
+
+ // Store the map and a cache object for the current logical line
+ if (i == 0) {
+ lineView.measure.map = builder.map;
+ lineView.measure.cache = {};
+ } else {
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
+ }
+ }
+
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
+ return builder;
+ }
+
+ function defaultSpecialCharPlaceholder(ch) {
+ var token = elt("span", "\u2022", "cm-invalidchar");
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
+ return token;
+ }
+
+ // Build up the DOM representation for a single token, and add it to
+ // the line map. Takes care to render special characters separately.
+ function buildToken(builder, text, style, startStyle, endStyle, title) {
+ if (!text) return;
+ var special = builder.cm.options.specialChars, mustWrap = false;
+ if (!special.test(text)) {
+ builder.col += text.length;
+ var content = document.createTextNode(text);
+ builder.map.push(builder.pos, builder.pos + text.length, content);
+ if (ie_upto8) mustWrap = true;
+ builder.pos += text.length;
+ } else {
+ var content = document.createDocumentFragment(), pos = 0;
+ while (true) {
+ special.lastIndex = pos;
+ var m = special.exec(text);
+ var skipped = m ? m.index - pos : text.length - pos;
+ if (skipped) {
+ var txt = document.createTextNode(text.slice(pos, pos + skipped));
+ if (ie_upto8) content.appendChild(elt("span", [txt]));
+ else content.appendChild(txt);
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
+ builder.col += skipped;
+ builder.pos += skipped;
+ }
+ if (!m) break;
+ pos += skipped + 1;
+ if (m[0] == "\t") {
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+ builder.col += tabWidth;
+ } else {
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
+ if (ie_upto8) content.appendChild(elt("span", [txt]));
+ else content.appendChild(txt);
+ builder.col += 1;
+ }
+ builder.map.push(builder.pos, builder.pos + 1, txt);
+ builder.pos++;
+ }
+ }
+ if (style || startStyle || endStyle || mustWrap) {
+ var fullStyle = style || "";
+ if (startStyle) fullStyle += startStyle;
+ if (endStyle) fullStyle += endStyle;
+ var token = elt("span", [content], fullStyle);
+ if (title) token.title = title;
+ return builder.content.appendChild(token);
+ }
+ builder.content.appendChild(content);
+ }
+
+ function buildTokenSplitSpaces(inner) {
+ function split(old) {
+ var out = " ";
+ for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
+ out += " ";
+ return out;
+ }
+ return function(builder, text, style, startStyle, endStyle, title) {
+ inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
+ };
+ }
+
+ // Work around nonsense dimensions being reported for stretches of
+ // right-to-left text.
+ function buildTokenBadBidi(inner, order) {
+ return function(builder, text, style, startStyle, endStyle, title) {
+ style = style ? style + " cm-force-border" : "cm-force-border";
+ var start = builder.pos, end = start + text.length;
+ for (;;) {
+ // Find the part that overlaps with the start of this text
+ for (var i = 0; i < order.length; i++) {
+ var part = order[i];
+ if (part.to > start && part.from <= start) break;
+ }
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
+ startStyle = null;
+ text = text.slice(part.to - start);
+ start = part.to;
+ }
+ };
+ }
+
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+ var widget = !ignoreWidget && marker.widgetNode;
+ if (widget) {
+ builder.map.push(builder.pos, builder.pos + size, widget);
+ builder.content.appendChild(widget);
+ }
+ builder.pos += size;
+ }
+
+ // Outputs a number of spans to make up a line, taking highlighting
+ // and marked text into account.
+ function insertLineContent(line, builder, styles) {
+ var spans = line.markedSpans, allText = line.text, at = 0;
+ if (!spans) {
+ for (var i = 1; i < styles.length; i+=2)
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder));
+ return;
+ }
+
+ var len = allText.length, pos = 0, i = 1, text = "", style;
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
+ for (;;) {
+ if (nextChange == pos) { // Update current marker set
+ spanStyle = spanEndStyle = spanStartStyle = title = "";
+ collapsed = null; nextChange = Infinity;
+ var foundBookmarks = [];
+ for (var j = 0; j < spans.length; ++j) {
+ var sp = spans[j], m = sp.marker;
+ if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
+ if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
+ if (m.className) spanStyle += " " + m.className;
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
+ if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
+ if (m.title && !title) title = m.title;
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
+ collapsed = sp;
+ } else if (sp.from > pos && nextChange > sp.from) {
+ nextChange = sp.from;
+ }
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
+ }
+ if (collapsed && (collapsed.from || 0) == pos) {
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
+ collapsed.marker, collapsed.from == null);
+ if (collapsed.to == null) return;
+ }
+ if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
+ }
+ if (pos >= len) break;
+
+ var upto = Math.min(len, nextChange);
+ while (true) {
+ if (text) {
+ var end = pos + text.length;
+ if (!collapsed) {
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title);
+ }
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
+ pos = end;
+ spanStartStyle = "";
+ }
+ text = allText.slice(at, at = styles[i++]);
+ style = interpretTokenStyle(styles[i++], builder);
+ }
+ }
+ }
+
+ // DOCUMENT DATA STRUCTURE
+
+ // By default, updates that start and end at the beginning of a line
+ // are treated specially, in order to make the association of line
+ // widgets and marker elements with the text behave more intuitive.
+ function isWholeLineUpdate(doc, change) {
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
+ }
+
+ // Perform a change on the document data structure.
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
+ function update(line, text, spans) {
+ updateLine(line, text, spans, estimateHeight);
+ signalLater(line, "change", line, change);
+ }
+
+ var from = change.from, to = change.to, text = change.text;
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
+
+ // Adjust the line structure
+ if (isWholeLineUpdate(doc, change)) {
+ // This is a whole-line replace. Treated specially to make
+ // sure line objects move the way they are supposed to.
+ for (var i = 0, added = []; i < text.length - 1; ++i)
+ added.push(new Line(text[i], spansFor(i), estimateHeight));
+ update(lastLine, lastLine.text, lastSpans);
+ if (nlines) doc.remove(from.line, nlines);
+ if (added.length) doc.insert(from.line, added);
+ } else if (firstLine == lastLine) {
+ if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
+ } else {
+ for (var added = [], i = 1; i < text.length - 1; ++i)
+ added.push(new Line(text[i], spansFor(i), estimateHeight));
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ doc.insert(from.line + 1, added);
+ }
+ } else if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
+ doc.remove(from.line + 1, nlines);
+ } else {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
+ for (var i = 1, added = []; i < text.length - 1; ++i)
+ added.push(new Line(text[i], spansFor(i), estimateHeight));
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
+ doc.insert(from.line + 1, added);
+ }
+
+ signalLater(doc, "change", doc, change);
+ }
+
+ // The document is represented as a BTree consisting of leaves, with
+ // chunk of lines in them, and branches, with up to ten leaves or
+ // other branch nodes below them. The top node is always a branch
+ // node, and is the document object itself (meaning it has
+ // additional methods and properties).
+ //
+ // All nodes have parent links. The tree is used both to go from
+ // line numbers to line objects, and to go from objects to numbers.
+ // It also indexes by height, and is used to convert between height
+ // and line object, and to find the total height of the document.
+ //
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
+
+ function LeafChunk(lines) {
+ this.lines = lines;
+ this.parent = null;
+ for (var i = 0, height = 0; i < lines.length; ++i) {
+ lines[i].parent = this;
+ height += lines[i].height;
+ }
+ this.height = height;
+ }
+
+ LeafChunk.prototype = {
+ chunkSize: function() { return this.lines.length; },
+ // Remove the n lines at offset 'at'.
+ removeInner: function(at, n) {
+ for (var i = at, e = at + n; i < e; ++i) {
+ var line = this.lines[i];
+ this.height -= line.height;
+ cleanUpLine(line);
+ signalLater(line, "delete");
+ }
+ this.lines.splice(at, n);
+ },
+ // Helper used to collapse a small branch into a single leaf.
+ collapse: function(lines) {
+ lines.push.apply(lines, this.lines);
+ },
+ // Insert the given array of lines at offset 'at', count them as
+ // having the given height.
+ insertInner: function(at, lines, height) {
+ this.height += height;
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
+ },
+ // Used to iterate over a part of the tree.
+ iterN: function(at, n, op) {
+ for (var e = at + n; at < e; ++at)
+ if (op(this.lines[at])) return true;
+ }
+ };
+
+ function BranchChunk(children) {
+ this.children = children;
+ var size = 0, height = 0;
+ for (var i = 0; i < children.length; ++i) {
+ var ch = children[i];
+ size += ch.chunkSize(); height += ch.height;
+ ch.parent = this;
+ }
+ this.size = size;
+ this.height = height;
+ this.parent = null;
+ }
+
+ BranchChunk.prototype = {
+ chunkSize: function() { return this.size; },
+ removeInner: function(at, n) {
+ this.size -= n;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
+ child.removeInner(at, rm);
+ this.height -= oldHeight - child.height;
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
+ if ((n -= rm) == 0) break;
+ at = 0;
+ } else at -= sz;
+ }
+ // If the result is smaller than 25 lines, ensure that it is a
+ // single leaf node.
+ if (this.size - n < 25 &&
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
+ var lines = [];
+ this.collapse(lines);
+ this.children = [new LeafChunk(lines)];
+ this.children[0].parent = this;
+ }
+ },
+ collapse: function(lines) {
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
+ },
+ insertInner: function(at, lines, height) {
+ this.size += lines.length;
+ this.height += height;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at <= sz) {
+ child.insertInner(at, lines, height);
+ if (child.lines && child.lines.length > 50) {
+ while (child.lines.length > 50) {
+ var spilled = child.lines.splice(child.lines.length - 25, 25);
+ var newleaf = new LeafChunk(spilled);
+ child.height -= newleaf.height;
+ this.children.splice(i + 1, 0, newleaf);
+ newleaf.parent = this;
+ }
+ this.maybeSpill();
+ }
+ break;
+ }
+ at -= sz;
+ }
+ },
+ // When a node has grown, check whether it should be split.
+ maybeSpill: function() {
+ if (this.children.length <= 10) return;
+ var me = this;
+ do {
+ var spilled = me.children.splice(me.children.length - 5, 5);
+ var sibling = new BranchChunk(spilled);
+ if (!me.parent) { // Become the parent node
+ var copy = new BranchChunk(me.children);
+ copy.parent = me;
+ me.children = [copy, sibling];
+ me = copy;
+ } else {
+ me.size -= sibling.size;
+ me.height -= sibling.height;
+ var myIndex = indexOf(me.parent.children, me);
+ me.parent.children.splice(myIndex + 1, 0, sibling);
+ }
+ sibling.parent = me.parent;
+ } while (me.children.length > 10);
+ me.parent.maybeSpill();
+ },
+ iterN: function(at, n, op) {
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var used = Math.min(n, sz - at);
+ if (child.iterN(at, used, op)) return true;
+ if ((n -= used) == 0) break;
+ at = 0;
+ } else at -= sz;
+ }
+ }
+ };
+
+ var nextDocId = 0;
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine) {
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine);
+ if (firstLine == null) firstLine = 0;
+
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
+ this.first = firstLine;
+ this.scrollTop = this.scrollLeft = 0;
+ this.cantEdit = false;
+ this.cleanGeneration = 1;
+ this.frontier = firstLine;
+ var start = Pos(firstLine, 0);
+ this.sel = simpleSelection(start);
+ this.history = new History(null);
+ this.id = ++nextDocId;
+ this.modeOption = mode;
+
+ if (typeof text == "string") text = splitLines(text);
+ updateDoc(this, {from: start, to: start, text: text});
+ setSelection(this, simpleSelection(start), sel_dontScroll);
+ };
+
+ Doc.prototype = createObj(BranchChunk.prototype, {
+ constructor: Doc,
+ // Iterate over the document. Supports two forms -- with only one
+ // argument, it calls that for each line in the document. With
+ // three, it iterates over the range given by the first two (with
+ // the second being non-inclusive).
+ iter: function(from, to, op) {
+ if (op) this.iterN(from - this.first, to - from, op);
+ else this.iterN(this.first, this.first + this.size, from);
+ },
+
+ // Non-public interface for adding and removing lines.
+ insert: function(at, lines) {
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
+ this.insertInner(at - this.first, lines, height);
+ },
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
+
+ // From here, the methods are part of the public interface. Most
+ // are also available from CodeMirror (editor) instances.
+
+ getValue: function(lineSep) {
+ var lines = getLines(this, this.first, this.first + this.size);
+ if (lineSep === false) return lines;
+ return lines.join(lineSep || "\n");
+ },
+ setValue: docMethodOp(function(code) {
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
+ text: splitLines(code), origin: "setValue"}, true);
+ setSelection(this, simpleSelection(top));
+ }),
+ replaceRange: function(code, from, to, origin) {
+ from = clipPos(this, from);
+ to = to ? clipPos(this, to) : from;
+ replaceRange(this, code, from, to, origin);
+ },
+ getRange: function(from, to, lineSep) {
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
+ if (lineSep === false) return lines;
+ return lines.join(lineSep || "\n");
+ },
+
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
+
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
+ getLineNumber: function(line) {return lineNo(line);},
+
+ getLineHandleVisualStart: function(line) {
+ if (typeof line == "number") line = getLine(this, line);
+ return visualLine(line);
+ },
+
+ lineCount: function() {return this.size;},
+ firstLine: function() {return this.first;},
+ lastLine: function() {return this.first + this.size - 1;},
+
+ clipPos: function(pos) {return clipPos(this, pos);},
+
+ getCursor: function(start) {
+ var range = this.sel.primary(), pos;
+ if (start == null || start == "head") pos = range.head;
+ else if (start == "anchor") pos = range.anchor;
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
+ else pos = range.from();
+ return pos;
+ },
+ listSelections: function() { return this.sel.ranges; },
+ somethingSelected: function() {return this.sel.somethingSelected();},
+
+ setCursor: docMethodOp(function(line, ch, options) {
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
+ }),
+ setSelection: docMethodOp(function(anchor, head, options) {
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
+ }),
+ extendSelection: docMethodOp(function(head, other, options) {
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
+ }),
+ extendSelections: docMethodOp(function(heads, options) {
+ extendSelections(this, clipPosArray(this, heads, options));
+ }),
+ extendSelectionsBy: docMethodOp(function(f, options) {
+ extendSelections(this, map(this.sel.ranges, f), options);
+ }),
+ setSelections: docMethodOp(function(ranges, primary, options) {
+ if (!ranges.length) return;
+ for (var i = 0, out = []; i < ranges.length; i++)
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
+ clipPos(this, ranges[i].head));
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
+ setSelection(this, normalizeSelection(out, primary), options);
+ }),
+ addSelection: docMethodOp(function(anchor, head, options) {
+ var ranges = this.sel.ranges.slice(0);
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
+ }),
+
+ getSelection: function(lineSep) {
+ var ranges = this.sel.ranges, lines;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
+ lines = lines ? lines.concat(sel) : sel;
+ }
+ if (lineSep === false) return lines;
+ else return lines.join(lineSep || "\n");
+ },
+ getSelections: function(lineSep) {
+ var parts = [], ranges = this.sel.ranges;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
+ if (lineSep !== false) sel = sel.join(lineSep || "\n");
+ parts[i] = sel;
+ }
+ return parts;
+ },
+ replaceSelection: docMethodOp(function(code, collapse, origin) {
+ var dup = [];
+ for (var i = 0; i < this.sel.ranges.length; i++)
+ dup[i] = code;
+ this.replaceSelections(dup, collapse, origin || "+input");
+ }),
+ replaceSelections: function(code, collapse, origin) {
+ var changes = [], sel = this.sel;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range = sel.ranges[i];
+ changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin};
+ }
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
+ for (var i = changes.length - 1; i >= 0; i--)
+ makeChange(this, changes[i]);
+ if (newSel) setSelectionReplaceHistory(this, newSel);
+ else if (this.cm) ensureCursorVisible(this.cm);
+ },
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
+
+ setExtending: function(val) {this.extend = val;},
+ getExtending: function() {return this.extend;},
+
+ historySize: function() {
+ var hist = this.history, done = 0, undone = 0;
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
+ return {undo: done, redo: undone};
+ },
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
+
+ markClean: function() {
+ this.cleanGeneration = this.changeGeneration(true);
+ },
+ changeGeneration: function(forceSplit) {
+ if (forceSplit)
+ this.history.lastOp = this.history.lastOrigin = null;
+ return this.history.generation;
+ },
+ isClean: function (gen) {
+ return this.history.generation == (gen || this.cleanGeneration);
+ },
+
+ getHistory: function() {
+ return {done: copyHistoryArray(this.history.done),
+ undone: copyHistoryArray(this.history.undone)};
+ },
+ setHistory: function(histData) {
+ var hist = this.history = new History(this.history.maxGeneration);
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
+ },
+
+ markText: function(from, to, options) {
+ return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
+ },
+ setBookmark: function(pos, options) {
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
+ insertLeft: options && options.insertLeft,
+ clearWhenEmpty: false, shared: options && options.shared};
+ pos = clipPos(this, pos);
+ return markText(this, pos, pos, realOpts, "bookmark");
+ },
+ findMarksAt: function(pos) {
+ pos = clipPos(this, pos);
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
+ if (spans) for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if ((span.from == null || span.from <= pos.ch) &&
+ (span.to == null || span.to >= pos.ch))
+ markers.push(span.marker.parent || span.marker);
+ }
+ return markers;
+ },
+ findMarks: function(from, to) {
+ from = clipPos(this, from); to = clipPos(this, to);
+ var found = [], lineNo = from.line;
+ this.iter(from.line, to.line + 1, function(line) {
+ var spans = line.markedSpans;
+ if (spans) for (var i = 0; i < spans.length; i++) {
+ var span = spans[i];
+ if (!(lineNo == from.line && from.ch > span.to ||
+ span.from == null && lineNo != from.line||
+ lineNo == to.line && span.from > to.ch))
+ found.push(span.marker.parent || span.marker);
+ }
+ ++lineNo;
+ });
+ return found;
+ },
+ getAllMarks: function() {
+ var markers = [];
+ this.iter(function(line) {
+ var sps = line.markedSpans;
+ if (sps) for (var i = 0; i < sps.length; ++i)
+ if (sps[i].from != null) markers.push(sps[i].marker);
+ });
+ return markers;
+ },
+
+ posFromIndex: function(off) {
+ var ch, lineNo = this.first;
+ this.iter(function(line) {
+ var sz = line.text.length + 1;
+ if (sz > off) { ch = off; return true; }
+ off -= sz;
+ ++lineNo;
+ });
+ return clipPos(this, Pos(lineNo, ch));
+ },
+ indexFromPos: function (coords) {
+ coords = clipPos(this, coords);
+ var index = coords.ch;
+ if (coords.line < this.first || coords.ch < 0) return 0;
+ this.iter(this.first, coords.line, function (line) {
+ index += line.text.length + 1;
+ });
+ return index;
+ },
+
+ copy: function(copyHistory) {
+ var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first);
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
+ doc.sel = this.sel;
+ doc.extend = false;
+ if (copyHistory) {
+ doc.history.undoDepth = this.history.undoDepth;
+ doc.setHistory(this.getHistory());
+ }
+ return doc;
+ },
+
+ linkedDoc: function(options) {
+ if (!options) options = {};
+ var from = this.first, to = this.first + this.size;
+ if (options.from != null && options.from > from) from = options.from;
+ if (options.to != null && options.to < to) to = options.to;
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from);
+ if (options.sharedHist) copy.history = this.history;
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
+ return copy;
+ },
+ unlinkDoc: function(other) {
+ if (other instanceof CodeMirror) other = other.doc;
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
+ var link = this.linked[i];
+ if (link.doc != other) continue;
+ this.linked.splice(i, 1);
+ other.unlinkDoc(this);
+ break;
+ }
+ // If the histories were shared, split them again
+ if (other.history == this.history) {
+ var splitIds = [other.id];
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
+ other.history = new History(null);
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
+ }
+ },
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
+
+ getMode: function() {return this.mode;},
+ getEditor: function() {return this.cm;}
+ });
+
+ // Public alias.
+ Doc.prototype.eachLine = Doc.prototype.iter;
+
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
+ var dontDelegate = "iter insert remove copy getEditor".split(" ");
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
+ CodeMirror.prototype[prop] = (function(method) {
+ return function() {return method.apply(this.doc, arguments);};
+ })(Doc.prototype[prop]);
+
+ eventMixin(Doc);
+
+ // Call f for all linked documents.
+ function linkedDocs(doc, f, sharedHistOnly) {
+ function propagate(doc, skip, sharedHist) {
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
+ var rel = doc.linked[i];
+ if (rel.doc == skip) continue;
+ var shared = sharedHist && rel.sharedHist;
+ if (sharedHistOnly && !shared) continue;
+ f(rel.doc, shared);
+ propagate(rel.doc, doc, shared);
+ }
+ }
+ propagate(doc, null, true);
+ }
+
+ // Attach a document to an editor.
+ function attachDoc(cm, doc) {
+ if (doc.cm) throw new Error("This document is already in use.");
+ cm.doc = doc;
+ doc.cm = cm;
+ estimateLineHeights(cm);
+ loadMode(cm);
+ if (!cm.options.lineWrapping) findMaxLine(cm);
+ cm.options.mode = doc.modeOption;
+ regChange(cm);
+ }
+
+ // LINE UTILITIES
+
+ // Find the line object corresponding to the given line number.
+ function getLine(doc, n) {
+ n -= doc.first;
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
+ for (var chunk = doc; !chunk.lines;) {
+ for (var i = 0;; ++i) {
+ var child = chunk.children[i], sz = child.chunkSize();
+ if (n < sz) { chunk = child; break; }
+ n -= sz;
+ }
+ }
+ return chunk.lines[n];
+ }
+
+ // Get the part of a document between two positions, as an array of
+ // strings.
+ function getBetween(doc, start, end) {
+ var out = [], n = start.line;
+ doc.iter(start.line, end.line + 1, function(line) {
+ var text = line.text;
+ if (n == end.line) text = text.slice(0, end.ch);
+ if (n == start.line) text = text.slice(start.ch);
+ out.push(text);
+ ++n;
+ });
+ return out;
+ }
+ // Get the lines between from and to, as array of strings.
+ function getLines(doc, from, to) {
+ var out = [];
+ doc.iter(from, to, function(line) { out.push(line.text); });
+ return out;
+ }
+
+ // Update the height of a line, propagating the height change
+ // upwards to parent nodes.
+ function updateLineHeight(line, height) {
+ var diff = height - line.height;
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
+ }
+
+ // Given a line object, find its line number by walking up through
+ // its parent links.
+ function lineNo(line) {
+ if (line.parent == null) return null;
+ var cur = line.parent, no = indexOf(cur.lines, line);
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+ for (var i = 0;; ++i) {
+ if (chunk.children[i] == cur) break;
+ no += chunk.children[i].chunkSize();
+ }
+ }
+ return no + cur.first;
+ }
+
+ // Find the line at the given vertical position, using the height
+ // information in the document tree.
+ function lineAtHeight(chunk, h) {
+ var n = chunk.first;
+ outer: do {
+ for (var i = 0; i < chunk.children.length; ++i) {
+ var child = chunk.children[i], ch = child.height;
+ if (h < ch) { chunk = child; continue outer; }
+ h -= ch;
+ n += child.chunkSize();
+ }
+ return n;
+ } while (!chunk.lines);
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i], lh = line.height;
+ if (h < lh) break;
+ h -= lh;
+ }
+ return n + i;
+ }
+
+
+ // Find the height above the given line.
+ function heightAtLine(lineObj) {
+ lineObj = visualLine(lineObj);
+
+ var h = 0, chunk = lineObj.parent;
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i];
+ if (line == lineObj) break;
+ else h += line.height;
+ }
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+ for (var i = 0; i < p.children.length; ++i) {
+ var cur = p.children[i];
+ if (cur == chunk) break;
+ else h += cur.height;
+ }
+ }
+ return h;
+ }
+
+ // Get the bidi ordering for the given line (and cache it). Returns
+ // false for lines that are fully left-to-right, and an array of
+ // BidiSpan objects otherwise.
+ function getOrder(line) {
+ var order = line.order;
+ if (order == null) order = line.order = bidiOrdering(line.text);
+ return order;
+ }
+
+ // HISTORY
+
+ function History(startGen) {
+ // Arrays of change events and selections. Doing something adds an
+ // event to done and clears undo. Undoing moves events from done
+ // to undone, redoing moves them in the other direction.
+ this.done = []; this.undone = [];
+ this.undoDepth = Infinity;
+ // Used to track when changes can be merged into a single undo
+ // event
+ this.lastModTime = this.lastSelTime = 0;
+ this.lastOp = null;
+ this.lastOrigin = this.lastSelOrigin = null;
+ // Used by the isClean() method
+ this.generation = this.maxGeneration = startGen || 1;
+ }
+
+ // Create a history change event from an updateDoc-style change
+ // object.
+ function historyChangeFromChange(doc, change) {
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
+ return histChange;
+ }
+
+ // Pop all selection events off the end of a history array. Stop at
+ // a change event.
+ function clearSelectionEvents(array) {
+ while (array.length) {
+ var last = lst(array);
+ if (last.ranges) array.pop();
+ else break;
+ }
+ }
+
+ // Find the top change event in the history. Pop off selection
+ // events that are in the way.
+ function lastChangeEvent(hist, force) {
+ if (force) {
+ clearSelectionEvents(hist.done);
+ return lst(hist.done);
+ } else if (hist.done.length && !lst(hist.done).ranges) {
+ return lst(hist.done);
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
+ hist.done.pop();
+ return lst(hist.done);
+ }
+ }
+
+ // Register a change in the history. Merges changes that are within
+ // a single operation, ore are close together with an origin that
+ // allows merging (starting with "+") into a single event.
+ function addChangeToHistory(doc, change, selAfter, opId) {
+ var hist = doc.history;
+ hist.undone.length = 0;
+ var time = +new Date, cur;
+
+ if ((hist.lastOp == opId ||
+ hist.lastOrigin == change.origin && change.origin &&
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
+ change.origin.charAt(0) == "*")) &&
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
+ // Merge this change into the last event
+ var last = lst(cur.changes);
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
+ // Optimized case for simple insertion -- don't want to add
+ // new changesets for every character typed
+ last.to = changeEnd(change);
+ } else {
+ // Add new sub-event
+ cur.changes.push(historyChangeFromChange(doc, change));
+ }
+ } else {
+ // Can not be merged, start a new event.
+ var before = lst(hist.done);
+ if (!before || !before.ranges)
+ pushSelectionToHistory(doc.sel, hist.done);
+ cur = {changes: [historyChangeFromChange(doc, change)],
+ generation: hist.generation};
+ hist.done.push(cur);
+ while (hist.done.length > hist.undoDepth) {
+ hist.done.shift();
+ if (!hist.done[0].ranges) hist.done.shift();
+ }
+ }
+ hist.done.push(selAfter);
+ hist.generation = ++hist.maxGeneration;
+ hist.lastModTime = hist.lastSelTime = time;
+ hist.lastOp = opId;
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
+
+ if (!last) signal(doc, "historyAdded");
+ }
+
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
+ var ch = origin.charAt(0);
+ return ch == "*" ||
+ ch == "+" &&
+ prev.ranges.length == sel.ranges.length &&
+ prev.somethingSelected() == sel.somethingSelected() &&
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
+ }
+
+ // Called whenever the selection changes, sets the new selection as
+ // the pending selection in the history, and pushes the old pending
+ // selection into the 'done' array when it was significantly
+ // different (in number of selected ranges, emptiness, or time).
+ function addSelectionToHistory(doc, sel, opId, options) {
+ var hist = doc.history, origin = options && options.origin;
+
+ // A new event is started when the previous origin does not match
+ // the current, or the origins don't allow matching. Origins
+ // starting with * are always merged, those starting with + are
+ // merged when similar and close together in time.
+ if (opId == hist.lastOp ||
+ (origin && hist.lastSelOrigin == origin &&
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
+ hist.done[hist.done.length - 1] = sel;
+ else
+ pushSelectionToHistory(sel, hist.done);
+
+ hist.lastSelTime = +new Date;
+ hist.lastSelOrigin = origin;
+ hist.lastOp = opId;
+ if (options && options.clearRedo !== false)
+ clearSelectionEvents(hist.undone);
+ }
+
+ function pushSelectionToHistory(sel, dest) {
+ var top = lst(dest);
+ if (!(top && top.ranges && top.equals(sel)))
+ dest.push(sel);
+ }
+
+ // Used to store marked span information in the history.
+ function attachLocalSpans(doc, change, from, to) {
+ var existing = change["spans_" + doc.id], n = 0;
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
+ if (line.markedSpans)
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
+ ++n;
+ });
+ }
+
+ // When un/re-doing restores text containing marked spans, those
+ // that have been explicitly cleared should not be restored.
+ function removeClearedSpans(spans) {
+ if (!spans) return null;
+ for (var i = 0, out; i < spans.length; ++i) {
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
+ else if (out) out.push(spans[i]);
+ }
+ return !out ? spans : out.length ? out : null;
+ }
+
+ // Retrieve and filter the old marked spans stored in a change event.
+ function getOldSpans(doc, change) {
+ var found = change["spans_" + doc.id];
+ if (!found) return null;
+ for (var i = 0, nw = []; i < change.text.length; ++i)
+ nw.push(removeClearedSpans(found[i]));
+ return nw;
+ }
+
+ // Used both to provide a JSON-safe object in .getHistory, and, when
+ // detaching a document, to split the history in two
+ function copyHistoryArray(events, newGroup, instantiateSel) {
+ for (var i = 0, copy = []; i < events.length; ++i) {
+ var event = events[i];
+ if (event.ranges) {
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
+ continue;
+ }
+ var changes = event.changes, newChanges = [];
+ copy.push({changes: newChanges});
+ for (var j = 0; j < changes.length; ++j) {
+ var change = changes[j], m;
+ newChanges.push({from: change.from, to: change.to, text: change.text});
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
+ if (indexOf(newGroup, Number(m[1])) > -1) {
+ lst(newChanges)[prop] = change[prop];
+ delete change[prop];
+ }
+ }
+ }
+ }
+ return copy;
+ }
+
+ // Rebasing/resetting history to deal with externally-sourced changes
+
+ function rebaseHistSelSingle(pos, from, to, diff) {
+ if (to < pos.line) {
+ pos.line += diff;
+ } else if (from < pos.line) {
+ pos.line = from;
+ pos.ch = 0;
+ }
+ }
+
+ // Tries to rebase an array of history events given a change in the
+ // document. If the change touches the same lines as the event, the
+ // event, and everything 'behind' it, is discarded. If the change is
+ // before the event, the event's positions are updated. Uses a
+ // copy-on-write scheme for the positions, to avoid having to
+ // reallocate them all on every rebase, but also avoid problems with
+ // shared position objects being unsafely updated.
+ function rebaseHistArray(array, from, to, diff) {
+ for (var i = 0; i < array.length; ++i) {
+ var sub = array[i], ok = true;
+ if (sub.ranges) {
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
+ for (var j = 0; j < sub.ranges.length; j++) {
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
+ }
+ continue;
+ }
+ for (var j = 0; j < sub.changes.length; ++j) {
+ var cur = sub.changes[j];
+ if (to < cur.from.line) {
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
+ } else if (from <= cur.to.line) {
+ ok = false;
+ break;
+ }
+ }
+ if (!ok) {
+ array.splice(0, i + 1);
+ i = 0;
+ }
+ }
+ }
+
+ function rebaseHist(hist, change) {
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
+ rebaseHistArray(hist.done, from, to, diff);
+ rebaseHistArray(hist.undone, from, to, diff);
+ }
+
+ // EVENT UTILITIES
+
+ // Due to the fact that we still support jurassic IE versions, some
+ // compatibility wrappers are needed.
+
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
+ if (e.preventDefault) e.preventDefault();
+ else e.returnValue = false;
+ };
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
+ if (e.stopPropagation) e.stopPropagation();
+ else e.cancelBubble = true;
+ };
+ function e_defaultPrevented(e) {
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
+ }
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
+
+ function e_target(e) {return e.target || e.srcElement;}
+ function e_button(e) {
+ var b = e.which;
+ if (b == null) {
+ if (e.button & 1) b = 1;
+ else if (e.button & 2) b = 3;
+ else if (e.button & 4) b = 2;
+ }
+ if (mac && e.ctrlKey && b == 1) b = 3;
+ return b;
+ }
+
+ // EVENT HANDLING
+
+ // Lightweight event framework. on/off also work on DOM nodes,
+ // registering native DOM handlers.
+
+ var on = CodeMirror.on = function(emitter, type, f) {
+ if (emitter.addEventListener)
+ emitter.addEventListener(type, f, false);
+ else if (emitter.attachEvent)
+ emitter.attachEvent("on" + type, f);
+ else {
+ var map = emitter._handlers || (emitter._handlers = {});
+ var arr = map[type] || (map[type] = []);
+ arr.push(f);
+ }
+ };
+
+ var off = CodeMirror.off = function(emitter, type, f) {
+ if (emitter.removeEventListener)
+ emitter.removeEventListener(type, f, false);
+ else if (emitter.detachEvent)
+ emitter.detachEvent("on" + type, f);
+ else {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ for (var i = 0; i < arr.length; ++i)
+ if (arr[i] == f) { arr.splice(i, 1); break; }
+ }
+ };
+
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ var args = Array.prototype.slice.call(arguments, 2);
+ for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
+ };
+
+ // Often, we want to signal events at a point where we are in the
+ // middle of some work, but don't want the handler to start calling
+ // other methods on the editor, which might be in an inconsistent
+ // state or simply not expect any other events to happen.
+ // signalLater looks whether there are any handlers, and schedules
+ // them to be executed when the last operation ends, or, if no
+ // operation is active, when a timeout fires.
+ var delayedCallbacks, delayedCallbackDepth = 0;
+ function signalLater(emitter, type /*, values...*/) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ if (!arr) return;
+ var args = Array.prototype.slice.call(arguments, 2);
+ if (!delayedCallbacks) {
+ ++delayedCallbackDepth;
+ delayedCallbacks = [];
+ setTimeout(fireDelayed, 0);
+ }
+ function bnd(f) {return function(){f.apply(null, args);};};
+ for (var i = 0; i < arr.length; ++i)
+ delayedCallbacks.push(bnd(arr[i]));
+ }
+
+ function fireDelayed() {
+ --delayedCallbackDepth;
+ var delayed = delayedCallbacks;
+ delayedCallbacks = null;
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
+ }
+
+ // The DOM events that CodeMirror handles can be overridden by
+ // registering a (non-DOM) handler on the editor for the event name,
+ // and preventDefault-ing the event in that handler.
+ function signalDOMEvent(cm, e, override) {
+ signal(cm, override || e.type, cm, e);
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
+ }
+
+ function hasHandler(emitter, type) {
+ var arr = emitter._handlers && emitter._handlers[type];
+ return arr && arr.length > 0;
+ }
+
+ // Add on and off methods to a constructor's prototype, to make
+ // registering events on such objects more convenient.
+ function eventMixin(ctor) {
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
+ }
+
+ // MISC UTILITIES
+
+ // Number of pixels added to scroller and sizer to hide scrollbar
+ var scrollerCutOff = 30;
+
+ // Returned or thrown by various protocols to signal 'I'm not
+ // handling this'.
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
+
+ // Reused option objects for setSelection & friends
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
+
+ function Delayed() {this.id = null;}
+ Delayed.prototype.set = function(ms, f) {
+ clearTimeout(this.id);
+ this.id = setTimeout(f, ms);
+ };
+
+ // Counts the column offset in a string, taking tabs into account.
+ // Used mostly to find indentation.
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
+ if (end == null) {
+ end = string.search(/[^\s\u00a0]/);
+ if (end == -1) end = string.length;
+ }
+ for (var i = startIndex || 0, n = startValue || 0;;) {
+ var nextTab = string.indexOf("\t", i);
+ if (nextTab < 0 || nextTab >= end)
+ return n + (end - i);
+ n += nextTab - i;
+ n += tabSize - (n % tabSize);
+ i = nextTab + 1;
+ }
+ };
+
+ // The inverse of countColumn -- find the offset that corresponds to
+ // a particular column.
+ function findColumn(string, goal, tabSize) {
+ for (var pos = 0, col = 0;;) {
+ var nextTab = string.indexOf("\t", pos);
+ if (nextTab == -1) nextTab = string.length;
+ var skipped = nextTab - pos;
+ if (nextTab == string.length || col + skipped >= goal)
+ return pos + Math.min(skipped, goal - col);
+ col += nextTab - pos;
+ col += tabSize - (col % tabSize);
+ pos = nextTab + 1;
+ if (col >= goal) return pos;
+ }
+ }
+
+ var spaceStrs = [""];
+ function spaceStr(n) {
+ while (spaceStrs.length <= n)
+ spaceStrs.push(lst(spaceStrs) + " ");
+ return spaceStrs[n];
+ }
+
+ function lst(arr) { return arr[arr.length-1]; }
+
+ var selectInput = function(node) { node.select(); };
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
+ else if (ie) // Suppress mysterious IE10 errors
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
+
+ function indexOf(array, elt) {
+ for (var i = 0; i < array.length; ++i)
+ if (array[i] == elt) return i;
+ return -1;
+ }
+ if ([].indexOf) indexOf = function(array, elt) { return array.indexOf(elt); };
+ function map(array, f) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
+ return out;
+ }
+ if ([].map) map = function(array, f) { return array.map(f); };
+
+ function createObj(base, props) {
+ var inst;
+ if (Object.create) {
+ inst = Object.create(base);
+ } else {
+ var ctor = function() {};
+ ctor.prototype = base;
+ inst = new ctor();
+ }
+ if (props) copyObj(props, inst);
+ return inst;
+ };
+
+ function copyObj(obj, target) {
+ if (!target) target = {};
+ for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
+ return target;
+ }
+
+ function bind(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function(){return f.apply(null, args);};
+ }
+
+ var nonASCIISingleCaseWordChar = /[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
+ var isWordChar = CodeMirror.isWordChar = function(ch) {
+ return /\w/.test(ch) || ch > "\x80" &&
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
+ };
+
+ function isEmpty(obj) {
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
+ return true;
+ }
+
+ // Extending unicode characters. A series of a non-extending char +
+ // any number of extending chars is treated as a single unit as far
+ // as editing and measuring is concerned. This is not fully correct,
+ // since some scripts/fonts/browsers also treat other configurations
+ // of code points as a group.
+ var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
+
+ // DOM UTILITIES
+
+ function elt(tag, content, className, style) {
+ var e = document.createElement(tag);
+ if (className) e.className = className;
+ if (style) e.style.cssText = style;
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
+ return e;
+ }
+
+ var range;
+ if (document.createRange) range = function(node, start, end) {
+ var r = document.createRange();
+ r.setEnd(node, end);
+ r.setStart(node, start);
+ return r;
+ };
+ else range = function(node, start, end) {
+ var r = document.body.createTextRange();
+ r.moveToElementText(node.parentNode);
+ r.collapse(true);
+ r.moveEnd("character", end);
+ r.moveStart("character", start);
+ return r;
+ };
+
+ function removeChildren(e) {
+ for (var count = e.childNodes.length; count > 0; --count)
+ e.removeChild(e.firstChild);
+ return e;
+ }
+
+ function removeChildrenAndAdd(parent, e) {
+ return removeChildren(parent).appendChild(e);
+ }
+
+ function contains(parent, child) {
+ if (parent.contains)
+ return parent.contains(child);
+ while (child = child.parentNode)
+ if (child == parent) return true;
+ }
+
+ function activeElt() { return document.activeElement; }
+ // Older versions of IE throws unspecified error when touching
+ // document.activeElement in some cases (during loading, in iframe)
+ if (ie_upto10) activeElt = function() {
+ try { return document.activeElement; }
+ catch(e) { return document.body; }
+ };
+
+ // FEATURE DETECTION
+
+ // Detect drag-and-drop
+ var dragAndDrop = function() {
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
+ // couldn't get it to work yet.
+ if (ie_upto8) return false;
+ var div = elt('div');
+ return "draggable" in div || "dragDrop" in div;
+ }();
+
+ var knownScrollbarWidth;
+ function scrollbarWidth(measure) {
+ if (knownScrollbarWidth != null) return knownScrollbarWidth;
+ var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll");
+ removeChildrenAndAdd(measure, test);
+ if (test.offsetWidth)
+ knownScrollbarWidth = test.offsetHeight - test.clientHeight;
+ return knownScrollbarWidth || 0;
+ }
+
+ var zwspSupported;
+ function zeroWidthElement(measure) {
+ if (zwspSupported == null) {
+ var test = elt("span", "\u200b");
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
+ if (measure.firstChild.offsetHeight != 0)
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_upto7;
+ }
+ if (zwspSupported) return elt("span", "\u200b");
+ else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+ }
+
+ // Feature-detect IE's crummy client rect reporting for bidi text
+ var badBidiRects;
+ function hasBadBidiRects(measure) {
+ if (badBidiRects != null) return badBidiRects;
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
+ if (r0.left == r0.right) return false;
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
+ return badBidiRects = (r1.right - r0.right < 3);
+ }
+
+ // See if "".split is the broken IE version, if so, provide an
+ // alternative way to split lines.
+ var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
+ var pos = 0, result = [], l = string.length;
+ while (pos <= l) {
+ var nl = string.indexOf("\n", pos);
+ if (nl == -1) nl = string.length;
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
+ var rt = line.indexOf("\r");
+ if (rt != -1) {
+ result.push(line.slice(0, rt));
+ pos += rt + 1;
+ } else {
+ result.push(line);
+ pos = nl + 1;
+ }
+ }
+ return result;
+ } : function(string){return string.split(/\r\n?|\n/);};
+
+ var hasSelection = window.getSelection ? function(te) {
+ try { return te.selectionStart != te.selectionEnd; }
+ catch(e) { return false; }
+ } : function(te) {
+ try {var range = te.ownerDocument.selection.createRange();}
+ catch(e) {}
+ if (!range || range.parentElement() != te) return false;
+ return range.compareEndPoints("StartToEnd", range) != 0;
+ };
+
+ var hasCopyEvent = (function() {
+ var e = elt("div");
+ if ("oncopy" in e) return true;
+ e.setAttribute("oncopy", "return;");
+ return typeof e.oncopy == "function";
+ })();
+
+ // KEY NAMES
+
+ var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete",
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"};
+ CodeMirror.keyNames = keyNames;
+ (function() {
+ // Number keys
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
+ // Alphabetic keys
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
+ // Function keys
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
+ })();
+
+ // BIDI HELPERS
+
+ function iterateBidiSections(order, from, to, f) {
+ if (!order) return f(from, to, "ltr");
+ var found = false;
+ for (var i = 0; i < order.length; ++i) {
+ var part = order[i];
+ if (part.from < to && part.to > from || from == to && part.to == from) {
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
+ found = true;
+ }
+ }
+ if (!found) f(from, to, "ltr");
+ }
+
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
+
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
+ function lineRight(line) {
+ var order = getOrder(line);
+ if (!order) return line.text.length;
+ return bidiRight(lst(order));
+ }
+
+ function lineStart(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLine(line);
+ if (visual != line) lineN = lineNo(visual);
+ var order = getOrder(visual);
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
+ return Pos(lineN, ch);
+ }
+ function lineEnd(cm, lineN) {
+ var merged, line = getLine(cm.doc, lineN);
+ while (merged = collapsedSpanAtEnd(line)) {
+ line = merged.find(1, true).line;
+ lineN = null;
+ }
+ var order = getOrder(line);
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
+ }
+
+ function compareBidiLevel(order, a, b) {
+ var linedir = order[0].level;
+ if (a == linedir) return true;
+ if (b == linedir) return false;
+ return a < b;
+ }
+ var bidiOther;
+ function getBidiPartAt(order, pos) {
+ bidiOther = null;
+ for (var i = 0, found; i < order.length; ++i) {
+ var cur = order[i];
+ if (cur.from < pos && cur.to > pos) return i;
+ if ((cur.from == pos || cur.to == pos)) {
+ if (found == null) {
+ found = i;
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
+ if (cur.from != cur.to) bidiOther = found;
+ return i;
+ } else {
+ if (cur.from != cur.to) bidiOther = i;
+ return found;
+ }
+ }
+ }
+ return found;
+ }
+
+ function moveInLine(line, pos, dir, byUnit) {
+ if (!byUnit) return pos + dir;
+ do pos += dir;
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
+ return pos;
+ }
+
+ // This is needed in order to move 'visually' through bi-directional
+ // text -- i.e., pressing left should make the cursor go left, even
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
+ // LTR text touch each other. This often requires the cursor offset
+ // to move more than one unit, in order to visually move one unit.
+ function moveVisually(line, start, dir, byUnit) {
+ var bidi = getOrder(line);
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
+
+ for (;;) {
+ if (target > part.from && target < part.to) return target;
+ if (target == part.from || target == part.to) {
+ if (getBidiPartAt(bidi, target) == pos) return target;
+ part = bidi[pos += dir];
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
+ } else {
+ part = bidi[pos += dir];
+ if (!part) return null;
+ if ((dir > 0) == part.level % 2)
+ target = moveInLine(line, part.to, -1, byUnit);
+ else
+ target = moveInLine(line, part.from, 1, byUnit);
+ }
+ }
+ }
+
+ function moveLogically(line, start, dir, byUnit) {
+ var target = start + dir;
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
+ return target < 0 || target > line.text.length ? null : target;
+ }
+
+ // Bidirectional ordering algorithm
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+ // that this (partially) implements.
+
+ // One-char codes used for character types:
+ // L (L): Left-to-Right
+ // R (R): Right-to-Left
+ // r (AL): Right-to-Left Arabic
+ // 1 (EN): European Number
+ // + (ES): European Number Separator
+ // % (ET): European Number Terminator
+ // n (AN): Arabic Number
+ // , (CS): Common Number Separator
+ // m (NSM): Non-Spacing Mark
+ // b (BN): Boundary Neutral
+ // s (B): Paragraph Separator
+ // t (S): Segment Separator
+ // w (WS): Whitespace
+ // N (ON): Other Neutrals
+
+ // Returns null if characters are ordered as they appear
+ // (left-to-right), or an array of sections ({from, to, level}
+ // objects) in the order in which they occur visually.
+ var bidiOrdering = (function() {
+ // Character types for codepoints 0 to 0xff
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
+ // Character types for codepoints 0x600 to 0x6ff
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
+ function charType(code) {
+ if (code <= 0xf7) return lowTypes.charAt(code);
+ else if (0x590 <= code && code <= 0x5f4) return "R";
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
+ else if (0x2000 <= code && code <= 0x200b) return "w";
+ else if (code == 0x200c) return "b";
+ else return "L";
+ }
+
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+ // Browsers seem to always treat the boundaries of block elements as being L.
+ var outerType = "L";
+
+ function BidiSpan(level, from, to) {
+ this.level = level;
+ this.from = from; this.to = to;
+ }
+
+ return function(str) {
+ if (!bidiRE.test(str)) return false;
+ var len = str.length, types = [];
+ for (var i = 0, type; i < len; ++i)
+ types.push(type = charType(str.charCodeAt(i)));
+
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
+ // change the type of the NSM to the type of the previous
+ // character. If the NSM is at the start of the level run, it will
+ // get the type of sor.
+ for (var i = 0, prev = outerType; i < len; ++i) {
+ var type = types[i];
+ if (type == "m") types[i] = prev;
+ else prev = type;
+ }
+
+ // W2. Search backwards from each instance of a European number
+ // until the first strong type (R, L, AL, or sor) is found. If an
+ // AL is found, change the type of the European number to Arabic
+ // number.
+ // W3. Change all ALs to R.
+ for (var i = 0, cur = outerType; i < len; ++i) {
+ var type = types[i];
+ if (type == "1" && cur == "r") types[i] = "n";
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
+ }
+
+ // W4. A single European separator between two European numbers
+ // changes to a European number. A single common separator between
+ // two numbers of the same type changes to that type.
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
+ var type = types[i];
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
+ else if (type == "," && prev == types[i+1] &&
+ (prev == "1" || prev == "n")) types[i] = prev;
+ prev = type;
+ }
+
+ // W5. A sequence of European terminators adjacent to European
+ // numbers changes to all European numbers.
+ // W6. Otherwise, separators and terminators change to Other
+ // Neutral.
+ for (var i = 0; i < len; ++i) {
+ var type = types[i];
+ if (type == ",") types[i] = "N";
+ else if (type == "%") {
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
+ for (var j = i; j < end; ++j) types[j] = replace;
+ i = end - 1;
+ }
+ }
+
+ // W7. Search backwards from each instance of a European number
+ // until the first strong type (R, L, or sor) is found. If an L is
+ // found, then change the type of the European number to L.
+ for (var i = 0, cur = outerType; i < len; ++i) {
+ var type = types[i];
+ if (cur == "L" && type == "1") types[i] = "L";
+ else if (isStrong.test(type)) cur = type;
+ }
+
+ // N1. A sequence of neutrals takes the direction of the
+ // surrounding strong text if the text on both sides has the same
+ // direction. European and Arabic numbers act as if they were R in
+ // terms of their influence on neutrals. Start-of-level-run (sor)
+ // and end-of-level-run (eor) are used at level run boundaries.
+ // N2. Any remaining neutrals take the embedding direction.
+ for (var i = 0; i < len; ++i) {
+ if (isNeutral.test(types[i])) {
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
+ var before = (i ? types[i-1] : outerType) == "L";
+ var after = (end < len ? types[end] : outerType) == "L";
+ var replace = before || after ? "L" : "R";
+ for (var j = i; j < end; ++j) types[j] = replace;
+ i = end - 1;
+ }
+ }
+
+ // Here we depart from the documented algorithm, in order to avoid
+ // building up an actual levels array. Since there are only three
+ // levels (0, 1, 2) in an implementation that doesn't take
+ // explicit embedding into account, we can build up the order on
+ // the fly, without following the level-based algorithm.
+ var order = [], m;
+ for (var i = 0; i < len;) {
+ if (countsAsLeft.test(types[i])) {
+ var start = i;
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
+ order.push(new BidiSpan(0, start, i));
+ } else {
+ var pos = i, at = order.length;
+ for (++i; i < len && types[i] != "L"; ++i) {}
+ for (var j = pos; j < i;) {
+ if (countsAsNum.test(types[j])) {
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
+ var nstart = j;
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
+ pos = j;
+ } else ++j;
+ }
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
+ }
+ }
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+ order[0].from = m[0].length;
+ order.unshift(new BidiSpan(0, 0, m[0].length));
+ }
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+ lst(order).to -= m[0].length;
+ order.push(new BidiSpan(0, len - m[0].length, len));
+ }
+ if (order[0].level != lst(order).level)
+ order.push(new BidiSpan(order[0].level, len, len));
+
+ return order;
+ };
+ })();
+
+ // THE END
+
+ CodeMirror.version = "4.0.3";
+
+ return CodeMirror;
+});
diff --git a/js_unmodified/python.js b/js_unmodified/python.js
new file mode 100644
index 0000000..f5530bc
--- /dev/null
+++ b/js_unmodified/python.js
@@ -0,0 +1,388 @@
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+
+CodeMirror.defineMode("python", function(conf, parserConf) {
+ var ERRORCLASS = 'error';
+
+ function wordRegexp(words) {
+ return new RegExp("^((" + words.join(")|(") + "))\\b");
+ }
+
+ var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
+ var singleDelimiters = parserConf.singleDelimiters || new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]');
+ var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
+ var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
+ var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
+ var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
+ var hangingIndent = parserConf.hangingIndent || parserConf.indentUnit;
+
+ var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']);
+ var commonkeywords = ['as', 'assert', 'break', 'class', 'continue',
+ 'def', 'del', 'elif', 'else', 'except', 'finally',
+ 'for', 'from', 'global', 'if', 'import',
+ 'lambda', 'pass', 'raise', 'return',
+ 'try', 'while', 'with', 'yield'];
+ var commonBuiltins = ['abs', 'all', 'any', 'bin', 'bool', 'bytearray', 'callable', 'chr',
+ 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
+ 'enumerate', 'eval', 'filter', 'float', 'format', 'frozenset',
+ 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
+ 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
+ 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next',
+ 'object', 'oct', 'open', 'ord', 'pow', 'property', 'range',
+ 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
+ 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
+ 'type', 'vars', 'zip', '__import__', 'NotImplemented',
+ 'Ellipsis', '__debug__'];
+ var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile',
+ 'file', 'intern', 'long', 'raw_input', 'reduce', 'reload',
+ 'unichr', 'unicode', 'xrange', 'False', 'True', 'None'],
+ 'keywords': ['exec', 'print']};
+ var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'],
+ 'keywords': ['nonlocal', 'False', 'True', 'None']};
+
+ if(parserConf.extra_keywords != undefined){
+ commonkeywords = commonkeywords.concat(parserConf.extra_keywords);
+ }
+ if(parserConf.extra_builtins != undefined){
+ commonBuiltins = commonBuiltins.concat(parserConf.extra_builtins);
+ }
+ if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) {
+ commonkeywords = commonkeywords.concat(py3.keywords);
+ commonBuiltins = commonBuiltins.concat(py3.builtins);
+ var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
+ } else {
+ commonkeywords = commonkeywords.concat(py2.keywords);
+ commonBuiltins = commonBuiltins.concat(py2.builtins);
+ var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
+ }
+ var keywords = wordRegexp(commonkeywords);
+ var builtins = wordRegexp(commonBuiltins);
+
+ var indentInfo = null;
+
+ // tokenizers
+ function tokenBase(stream, state) {
+ // Handle scope changes
+ if (stream.sol()) {
+ var scopeOffset = state.scopes[0].offset;
+ if (stream.eatSpace()) {
+ var lineOffset = stream.indentation();
+ if (lineOffset > scopeOffset) {
+ indentInfo = 'indent';
+ } else if (lineOffset < scopeOffset) {
+ indentInfo = 'dedent';
+ }
+ return null;
+ } else {
+ if (scopeOffset > 0) {
+ dedent(stream, state);
+ }
+ }
+ }
+ if (stream.eatSpace()) {
+ return null;
+ }
+
+ var ch = stream.peek();
+
+ // Handle Comments
+ if (ch === '#') {
+ stream.skipToEnd();
+ return 'comment';
+ }
+
+ // Handle Number Literals
+ if (stream.match(/^[0-9\.]/, false)) {
+ var floatLiteral = false;
+ // Floats
+ if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
+ if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
+ if (stream.match(/^\.\d+/)) { floatLiteral = true; }
+ if (floatLiteral) {
+ // Float literals may be "imaginary"
+ stream.eat(/J/i);
+ return 'number';
+ }
+ // Integers
+ var intLiteral = false;
+ // Hex
+ if (stream.match(/^0x[0-9a-f]+/i)) { intLiteral = true; }
+ // Binary
+ if (stream.match(/^0b[01]+/i)) { intLiteral = true; }
+ // Octal
+ if (stream.match(/^0o[0-7]+/i)) { intLiteral = true; }
+ // Decimal
+ if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
+ // Decimal literals may be "imaginary"
+ stream.eat(/J/i);
+ // TODO - Can you have imaginary longs?
+ intLiteral = true;
+ }
+ // Zero by itself with no other piece of number.
+ if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; }
+ if (intLiteral) {
+ // Integer literals may be "long"
+ stream.eat(/L/i);
+ return 'number';
+ }
+ }
+
+ // Handle Strings
+ if (stream.match(stringPrefixes)) {
+ state.tokenize = tokenStringFactory(stream.current());
+ return state.tokenize(stream, state);
+ }
+
+ // Handle operators and Delimiters
+ if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) {
+ return null;
+ }
+ if (stream.match(doubleOperators)
+ || stream.match(singleOperators)
+ || stream.match(wordOperators)) {
+ return 'operator';
+ }
+ if (stream.match(singleDelimiters)) {
+ return null;
+ }
+
+ if (stream.match(keywords)) {
+ return 'keyword';
+ }
+
+ if (stream.match(builtins)) {
+ return 'builtin';
+ }
+
+ if (stream.match(/^(self|cls)\b/)) {
+ return "variable-2";
+ }
+
+ if (stream.match(identifiers)) {
+ if (state.lastToken == 'def' || state.lastToken == 'class') {
+ return 'def';
+ }
+ return 'variable';
+ }
+
+ // Handle non-detected items
+ stream.next();
+ return ERRORCLASS;
+ }
+
+ function tokenStringFactory(delimiter) {
+ while ('rub'.indexOf(delimiter.charAt(0).toLowerCase()) >= 0) {
+ delimiter = delimiter.substr(1);
+ }
+ var singleline = delimiter.length == 1;
+ var OUTCLASS = 'string';
+
+ function tokenString(stream, state) {
+ while (!stream.eol()) {
+ stream.eatWhile(/[^'"\\]/);
+ if (stream.eat('\\')) {
+ stream.next();
+ if (singleline && stream.eol()) {
+ return OUTCLASS;
+ }
+ } else if (stream.match(delimiter)) {
+ state.tokenize = tokenBase;
+ return OUTCLASS;
+ } else {
+ stream.eat(/['"]/);
+ }
+ }
+ if (singleline) {
+ if (parserConf.singleLineStringErrors) {
+ return ERRORCLASS;
+ } else {
+ state.tokenize = tokenBase;
+ }
+ }
+ return OUTCLASS;
+ }
+ tokenString.isString = true;
+ return tokenString;
+ }
+
+ function indent(stream, state, type) {
+ type = type || 'py';
+ var indentUnit = 0;
+ if (type === 'py') {
+ if (state.scopes[0].type !== 'py') {
+ state.scopes[0].offset = stream.indentation();
+ return;
+ }
+ for (var i = 0; i < state.scopes.length; ++i) {
+ if (state.scopes[i].type === 'py') {
+ indentUnit = state.scopes[i].offset + conf.indentUnit;
+ break;
+ }
+ }
+ } else if (stream.match(/\s*($|#)/, false)) {
+ // An open paren/bracket/brace with only space or comments after it
+ // on the line will indent the next line a fixed amount, to make it
+ // easier to put arguments, list items, etc. on their own lines.
+ indentUnit = stream.indentation() + hangingIndent;
+ } else {
+ indentUnit = stream.column() + stream.current().length;
+ }
+ state.scopes.unshift({
+ offset: indentUnit,
+ type: type
+ });
+ }
+
+ function dedent(stream, state, type) {
+ type = type || 'py';
+ if (state.scopes.length == 1) return;
+ if (state.scopes[0].type === 'py') {
+ var _indent = stream.indentation();
+ var _indent_index = -1;
+ for (var i = 0; i < state.scopes.length; ++i) {
+ if (_indent === state.scopes[i].offset) {
+ _indent_index = i;
+ break;
+ }
+ }
+ if (_indent_index === -1) {
+ return true;
+ }
+ while (state.scopes[0].offset !== _indent) {
+ state.scopes.shift();
+ }
+ return false;
+ } else {
+ if (type === 'py') {
+ state.scopes[0].offset = stream.indentation();
+ return false;
+ } else {
+ if (state.scopes[0].type != type) {
+ return true;
+ }
+ state.scopes.shift();
+ return false;
+ }
+ }
+ }
+
+ function tokenLexer(stream, state) {
+ indentInfo = null;
+ var style = state.tokenize(stream, state);
+ var current = stream.current();
+
+ // Handle '.' connected identifiers
+ if (current === '.') {
+ style = stream.match(identifiers, false) ? null : ERRORCLASS;
+ if (style === null && state.lastStyle === 'meta') {
+ // Apply 'meta' style to '.' connected identifiers when
+ // appropriate.
+ style = 'meta';
+ }
+ return style;
+ }
+
+ // Handle decorators
+ if (current === '@') {
+ return stream.match(identifiers, false) ? 'meta' : ERRORCLASS;
+ }
+
+ if ((style === 'variable' || style === 'builtin')
+ && state.lastStyle === 'meta') {
+ style = 'meta';
+ }
+
+ // Handle scope changes.
+ if (current === 'pass' || current === 'return') {
+ state.dedent += 1;
+ }
+ if (current === 'lambda') state.lambda = true;
+ if ((current === ':' && !state.lambda && state.scopes[0].type == 'py')
+ || indentInfo === 'indent') {
+ indent(stream, state);
+ }
+ var delimiter_index = '[({'.indexOf(current);
+ if (delimiter_index !== -1) {
+ indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1));
+ }
+ if (indentInfo === 'dedent') {
+ if (dedent(stream, state)) {
+ return ERRORCLASS;
+ }
+ }
+ delimiter_index = '])}'.indexOf(current);
+ if (delimiter_index !== -1) {
+ if (dedent(stream, state, current)) {
+ return ERRORCLASS;
+ }
+ }
+ if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') {
+ if (state.scopes.length > 1) state.scopes.shift();
+ state.dedent -= 1;
+ }
+
+ return style;
+ }
+
+ var external = {
+ startState: function(basecolumn) {
+ return {
+ tokenize: tokenBase,
+ scopes: [{offset:basecolumn || 0, type:'py'}],
+ lastStyle: null,
+ lastToken: null,
+ lambda: false,
+ dedent: 0
+ };
+ },
+
+ token: function(stream, state) {
+ var style = tokenLexer(stream, state);
+
+ state.lastStyle = style;
+
+ var current = stream.current();
+ if (current && style) {
+ state.lastToken = current;
+ }
+
+ if (stream.eol() && state.lambda) {
+ state.lambda = false;
+ }
+ return style;
+ },
+
+ indent: function(state) {
+ if (state.tokenize != tokenBase) {
+ return state.tokenize.isString ? CodeMirror.Pass : 0;
+ }
+
+ return state.scopes[0].offset;
+ },
+
+ lineComment: "#",
+ fold: "indent"
+ };
+ return external;
+});
+
+CodeMirror.defineMIME("text/x-python", "python");
+
+var words = function(str){return str.split(' ');};
+
+CodeMirror.defineMIME("text/x-cython", {
+ name: "python",
+ extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
+ "extern gil include nogil property public"+
+ "readonly struct union DEF IF ELIF ELSE")
+});
+
+});
diff --git a/js_unmodified/shell.js b/js_unmodified/shell.js
new file mode 100644
index 0000000..9381a41
--- /dev/null
+++ b/js_unmodified/shell.js
@@ -0,0 +1,5121 @@
+// (c) Colin Barschel 2007-2008 - http://cb.vu - See shell.js for the original uncompressed version. termlib.js is (c) Norbert Landsteiner 2003-2007 http://www.masswerk.at
+var Terminal = function(conf) {
+ if (typeof conf != 'object') conf = new Object();
+ else {
+ for (var i in this.Defaults) {
+ if (typeof conf[i] == 'undefined') conf[i] = this.Defaults[i];
+ }
+ }
+ this.conf = conf;
+ this.setInitValues();
+}
+Terminal.prototype = {
+ version: '1.43 (original)',
+ Defaults: {
+ cols: 80,
+ rows: 24,
+ x: 100,
+ y: 100,
+ termDiv: 'termDiv',
+ bgColor: '#181818',
+ frameColor: '#555555',
+ frameWidth: 1,
+ rowHeight: 15,
+ blinkDelay: 500,
+ fontClass: 'term',
+ crsrBlinkMode: false,
+ crsrBlockMode: true,
+ DELisBS: false,
+ printTab: true,
+ printEuro: true,
+ catchCtrlH: true,
+ closeOnESC: true,
+ historyUnique: false,
+ id: 0,
+ ps: '>',
+ greeting: '%+r Terminal ready. %-r',
+ handler: this.defaultHandler,
+ ctrlHandler: null,
+ initHandler: null,
+ exitHandler: null,
+ wrap: false
+ },
+ setInitValues: function() {
+ this.isSafari = (navigator.userAgent.indexOf('Safari') >= 0) ? true : false;
+ this.isOpera = (window.opera && navigator.userAgent.indexOf('Opera') >= 0) ? true : false;
+ this.id = this.conf.id;
+ this.maxLines = this.conf.rows;
+ this.maxCols = this.conf.cols;
+ this.termDiv = this.conf.termDiv;
+ this.crsrBlinkMode = this.conf.crsrBlinkMode;
+ this.crsrBlockMode = this.conf.crsrBlockMode;
+ this.blinkDelay = this.conf.blinkDelay;
+ this.DELisBS = this.conf.DELisBS;
+ this.printTab = this.conf.printTab;
+ this.printEuro = this.conf.printEuro;
+ this.catchCtrlH = this.conf.catchCtrlH;
+ this.closeOnESC = this.conf.closeOnESC;
+ this.historyUnique = this.conf.historyUnique;
+ this.ps = this.conf.ps;
+ this.closed = false;
+ this.r;
+ this.c;
+ this.charBuf = new Array();
+ this.styleBuf = new Array();
+ this.scrollBuf = null;
+ this.blinkBuffer = 0;
+ this.blinkTimer;
+ this.cursoractive = false;
+ this.lock = true;
+ this.insert = false;
+ this.charMode = false;
+ this.rawMode = false;
+ this.lineBuffer = '';
+ this.inputChar = 0;
+ this.lastLine = '';
+ this.guiCounter = 0;
+ this.history = new Array();
+ this.histPtr = 0;
+ this.env = new Object();
+ this.ns4ParentDoc = null;
+ this.handler = this.conf.handler;
+ this.wrapping = this.conf.wrapping;
+ this.ctrlHandler = this.conf.ctrlHandler;
+ this.initHandler = this.conf.initHandler;
+ this.exitHandler = this.conf.exitHandler;
+ },
+ defaultHandler: function() {
+ this.newLine();
+ if (this.lineBuffer != '') {
+ this.type('You typed: ' + this.lineBuffer);
+ this.newLine();
+ }
+ this.prompt();
+ },
+ open: function() {
+ if (this.termDivReady()) {
+ if (!this.closed) this._makeTerm();
+ this.init();
+ return true;
+ } else return false;
+ },
+ close: function() {
+ this.lock = true;
+ this.cursorOff();
+ if (this.exitHandler) this.exitHandler();
+ this.globals.setVisible(this.termDiv, 0);
+ this.closed = true;
+ },
+ init: function() {
+ if (this.guiReady()) {
+ this.guiCounter = 0;
+ if (this.closed) {
+ this.setInitValues();
+ }
+ this.clear();
+ this.globals.setVisible(this.termDiv, 1);
+ this.globals.enableKeyboard(this);
+ if (this.initHandler) {
+ this.initHandler();
+ } else {
+ this.write(this.conf.greeting);
+ this.newLine();
+ this.prompt();
+ }
+ } else {
+ this.guiCounter++;
+ if (this.guiCounter > 18000) {
+ if (confirm('Terminal:\nYour browser hasn\'t responded for more than 2 minutes.\nRetry?')) this.guiCounter = 0
+ else return;
+ };
+ this.globals.termToInitialze = this;
+ window.setTimeout('Terminal.prototype.globals.termToInitialze.init()', 200);
+ }
+ },
+ getRowArray: function(l, v) {
+ var a = new Array();
+ for (var i = 0; i < l; i++) a[i] = v;
+ return a;
+ },
+ wrapOn: function() {
+ this.wrapping = true;
+ },
+ wrapOff: function() {
+ this.wrapping = false;
+ },
+ type: function(text, style) {
+ for (var i = 0; i < text.length; i++) {
+ var ch = text.charCodeAt(i);
+ if (!this.isPrintable(ch)) ch = 94;
+ this.charBuf[this.r][this.c] = ch;
+ this.styleBuf[this.r][this.c] = (style) ? style : 0;
+ var last_r = this.r;
+ this._incCol();
+ if (this.r != last_r) this.redraw(last_r);
+ }
+ this.redraw(this.r)
+ },
+ write: function(text, usemore) {
+ if (typeof text != 'object') {
+ if (typeof text != 'string') text = '' + text;
+ if (text.indexOf('\n') >= 0) {
+ var ta = text.split('\n');
+ text = ta.join('%n');
+ }
+ } else {
+ if (text.join) text = text.join('%n')
+ else text = '' + text;
+ if (text.indexOf('\n') >= 0) {
+ var ta = text.split('\n');
+ text = ta.join('%n');
+ }
+ }
+ this._sbInit(usemore);
+ var chunks = text.split('%');
+ var esc = (text.charAt(0) != '%');
+ var style = 0;
+ var styleMarkUp = this.globals.termStyleMarkup;
+ for (var i = 0; i < chunks.length; i++) {
+ if (esc) {
+ if (chunks[i].length > 0) this._sbType(chunks[i], style)
+ else if (i > 0) this._sbType('%', style);
+ esc = false;
+ } else {
+ var func = chunks[i].charAt(0);
+ if ((chunks[i].length == 0) && (i > 0)) {
+ this._sbType("%", style);
+ esc = true;
+ } else if (func == 'n') {
+ this._sbNewLine(true);
+ if (chunks[i].length > 1) this._sbType(chunks[i].substring(1), style);
+ } else if (func == '+') {
+ var opt = chunks[i].charAt(1);
+ opt = opt.toLowerCase();
+ if (opt == 'p') style = 0
+ else if (styleMarkUp[opt]) style |= styleMarkUp[opt];
+ if (chunks[i].length > 2) this._sbType(chunks[i].substring(2), style);
+ } else if (func == '-') {
+ var opt = chunks[i].charAt(1);
+ opt = opt.toLowerCase();
+ if (opt == 'p') style = 0
+ else if (styleMarkUp[opt]) style &= ~styleMarkUp[opt];
+ if (chunks[i].length > 2) this._sbType(chunks[i].substring(2), style);
+ } else if ((chunks[i].length > 1) && (func == 'c')) {
+ var cinfo = this._parseColor(chunks[i].substring(1));
+ style = (style & (~0xfffff0)) | cinfo.style;
+ if (cinfo.rest) this._sbType(cinfo.rest, style);
+ } else if ((chunks[i].length > 1) && (chunks[i].charAt(0) == 'C') && (chunks[i].charAt(1) == 'S')) {
+ this.clear();
+ this._sbInit();
+ if (chunks[i].length > 2) this._sbType(chunks[i].substring(2), style);
+ } else {
+ if (chunks[i].length > 0) this._sbType(chunks[i], style);
+ }
+ }
+ }
+ this._sbOut();
+ },
+ _parseColor: function(chunk) {
+ var rest = '';
+ var style = 0;
+ if (chunk.length) {
+ if (chunk.charAt(0) == '(') {
+ var clabel = '';
+ for (var i = 1; i < chunk.length; i++) {
+ var c = chunk.charAt(i);
+ if (c == ')') {
+ if (chunk.length > i) rest = chunk.substring(i + 1);
+ break;
+ }
+ clabel += c;
+ }
+ if (clabel) {
+ if (clabel.charAt(0) == '@') {
+ var sc = this.globals.nsColors[clabel.substring(1).toLowerCase()];
+ if (sc) style = (16 + sc) * 0x100;
+ } else if (clabel.charAt(0) == '#') {
+ var cl = clabel.substring(1).toLowerCase();
+ var sc = this.globals.webColors[cl];
+ if (sc) {
+ style = sc * 0x10000;
+ } else {
+ cl = this.globals.webifyColor(cl);
+ if (cl) style = this.globals.webColors[cl] * 0x10000;
+ }
+ } else if ((clabel.length) && (clabel.length <= 2)) {
+ var isHex = false;
+ for (var i = 0; i < clabel.length; i++) {
+ if (this.globals.isHexOnlyChar(clabel.charAt(i))) {
+ isHex = true;
+ break;
+ }
+ }
+ var cl = (isHex) ? parseInt(clabel, 16) : parseInt(clabel, 10);
+ if ((!isNaN(cl)) || (cl <= 15)) {
+ style = cl * 0x100;
+ }
+ } else {
+ style = this.globals.getColorCode(clabel) * 0x100;
+ }
+ }
+ } else {
+ var c = chunk.charAt(0);
+ if (this.globals.isHexChar(c)) {
+ style = this.globals.hexToNum[c] * 0x100;
+ rest = chunk.substring(1);
+ } else {
+ rest = chunk;
+ }
+ }
+ }
+ return {
+ rest: rest,
+ style: style
+ };
+ },
+ _sbInit: function(usemore) {
+ var sb = this.scrollBuf = new Object();
+ var sbl = sb.lines = new Array();
+ var sbs = sb.styles = new Array();
+ sb.more = usemore;
+ sb.line = 0;
+ sb.status = 0;
+ sb.r = 0;
+ sb.c = this.c;
+ sbl[0] = this.getRowArray(this.conf.cols, 0);
+ sbs[0] = this.getRowArray(this.conf.cols, 0);
+ for (var i = 0; i < this.c; i++) {
+ sbl[0][i] = this.charBuf[this.r][i];
+ sbs[0][i] = this.styleBuf[this.r][i];
+ }
+ },
+ _sbType: function(text, style) {
+ var sb = this.scrollBuf;
+ for (var i = 0; i < text.length; i++) {
+ var ch = text.charCodeAt(i);
+ if (!this.isPrintable(ch)) ch = 94;
+ sb.lines[sb.r][sb.c] = ch;
+ sb.styles[sb.r][sb.c++] = (style) ? style : 0;
+ if (sb.c >= this.maxCols) this._sbNewLine();
+ }
+ },
+ _sbNewLine: function(forced) {
+ var sb = this.scrollBuf;
+ if (this.wrapping && forced) {
+ sb.lines[sb.r][sb.c] = 10;
+ sb.lines[sb.r].length = sb.c + 1;
+ }
+ sb.r++;
+ sb.c = 0;
+ sb.lines[sb.r] = this.getRowArray(this.conf.cols, 0);
+ sb.styles[sb.r] = this.getRowArray(this.conf.cols, 0);
+ },
+ _sbWrap: function() {
+ var wb = new Object();
+ wb.lines = new Array();
+ wb.styles = new Array();
+ wb.lines[0] = this.getRowArray(this.conf.cols, 0);
+ wb.styles[0] = this.getRowArray(this.conf.cols, 0);
+ wb.r = 0;
+ wb.c = 0;
+ var sb = this.scrollBuf;
+ var sbl = sb.lines;
+ var sbs = sb.styles;
+ var ch, st, wrap, lc, ls;
+ var l = this.c;
+ var lastR = 0;
+ var lastC = 0;
+ wb.cBreak = false;
+ for (var r = 0; r < sbl.length; r++) {
+ lc = sbl[r];
+ ls = sbs[r];
+ for (var c = 0; c < lc.length; c++) {
+ ch = lc[c];
+ st = ls[c];
+ if (ch) {
+ var wrap = this.globals.wrapChars[ch];
+ if (ch == 10) wrap = 1;
+ if (wrap) {
+ if (wrap == 2) {
+ l++;
+ } else if (wrap == 4) {
+ l++;
+ lc[c] = 45;
+ }
+ this._wbOut(wb, lastR, lastC, l);
+ if (ch == 10) {
+ this._wbIncLine(wb);
+ } else if ((wrap == 1) && (wb.c < this.maxCols)) {
+ wb.lines[wb.r][wb.c] = ch;
+ wb.styles[wb.r][wb.c++] = st;
+ if (wb.c >= this.maxCols) this._wbIncLine(wb);
+ }
+ if (wrap == 3) {
+ lastR = r;
+ lastC = c;
+ l = 1;
+ } else {
+ l = 0;
+ lastR = r;
+ lastC = c + 1;
+ if (lastC == lc.length) {
+ lastR++;
+ lastC = 0;
+ }
+ if (wrap == 4) wb.cBreak = true;
+ }
+ } else {
+ l++;
+ }
+ } else continue;
+ }
+ }
+ if (l) {
+ if ((wb.cbreak) && (wb.c != 0)) wb.c--;
+ this._wbOut(wb, lastR, lastC, l);
+ }
+ sb.lines = wb.lines;
+ sb.styles = wb.styles;
+ sb.r = wb.r;
+ sb.c = wb.c;
+ },
+ _wbOut: function(wb, br, bc, l) {
+ var sb = this.scrollBuf;
+ var sbl = sb.lines;
+ var sbs = sb.styles;
+ var ofs = 0;
+ var lc, ls;
+ if (l + wb.c > this.maxCols) {
+ if (l < this.maxCols) {
+ this._wbIncLine(wb);
+ } else {
+ var i0 = 0;
+ ofs = this.maxCols - wb.c;
+ lc = sbl[br];
+ ls = sbs[br];
+ while (true) {
+ for (var i = i0; i < ofs; i++) {
+ wb.lines[wb.r][wb.c] = lc[bc];
+ wb.styles[wb.r][wb.c++] = ls[bc++];
+ if (bc == sbl[br].length) {
+ bc = 0;
+ br++;
+ lc = sbl[br];
+ ls = sbs[br];
+ }
+ }
+ this._wbIncLine(wb);
+ if (l - ofs < this.maxCols) break;
+ i0 = ofs;
+ ofs += this.maxCols;
+ }
+ }
+ } else if (wb.cBreak) {
+ wb.c--;
+ }
+ lc = sbl[br];
+ ls = sbs[br];
+ for (var i = ofs; i < l; i++) {
+ wb.lines[wb.r][wb.c] = lc[bc];
+ wb.styles[wb.r][wb.c++] = ls[bc++];
+ if (bc == sbl[br].length) {
+ bc = 0;
+ br++;
+ lc = sbl[br];
+ ls = sbs[br];
+ }
+ }
+ wb.cBreak = false;
+ },
+ _wbIncLine: function(wb) {
+ wb.r++;
+ wb.c = 0;
+ wb.lines[wb.r] = this.getRowArray(this.conf.cols, 0);
+ wb.styles[wb.r] = this.getRowArray(this.conf.cols, 0);
+ },
+ _sbOut: function() {
+ var sb = this.scrollBuf;
+ if ((this.wrapping) && (!sb.status)) this._sbWrap();
+ var sbl = sb.lines;
+ var sbs = sb.styles;
+ var tcb = this.charBuf;
+ var tsb = this.styleBuf;
+ var ml = this.maxLines;
+ var buflen = sbl.length;
+ if (sb.more) {
+ if (sb.status) {
+ if (this.inputChar == this.globals.lcMoreKeyAbort) {
+ this.r = ml - 1;
+ this.c = 0;
+ tcb[this.r] = this.getRowArray(this.conf.cols, 0);
+ tsb[this.r] = this.getRowArray(this.conf.cols, 0);
+ this.redraw(this.r);
+ this.handler = sb.handler;
+ this.charMode = false;
+ this.inputChar = 0;
+ this.scrollBuf = null;
+ this.prompt();
+ return;
+ } else if (this.inputChar == this.globals.lcMoreKeyContinue) {
+ this.clear();
+ } else {
+ return;
+ }
+ } else {
+ if (this.r >= ml - 1) this.clear();
+ }
+ }
+ if (this.r + buflen - sb.line <= ml) {
+ for (var i = sb.line; i < buflen; i++) {
+ var r = this.r + i - sb.line;
+ tcb[r] = sbl[i];
+ tsb[r] = sbs[i];
+ this.redraw(r);
+ }
+ this.r += sb.r - sb.line;
+ this.c = sb.c;
+ if (sb.more) {
+ if (sb.status) this.handler = sb.handler;
+ this.charMode = false;
+ this.inputChar = 0;
+ this.scrollBuf = null;
+ this.prompt();
+ return;
+ }
+ } else if (sb.more) {
+ ml--;
+ if (sb.status == 0) {
+ sb.handler = this.handler;
+ this.handler = this._sbOut;
+ this.charMode = true;
+ sb.status = 1;
+ }
+ if (this.r) {
+ var ofs = ml - this.r;
+ for (var i = sb.line; i < ofs; i++) {
+ var r = this.r + i - sb.line;
+ tcb[r] = sbl[i];
+ tsb[r] = sbs[i];
+ this.redraw(r);
+ }
+ } else {
+ var ofs = sb.line + ml;
+ for (var i = sb.line; i < ofs; i++) {
+ var r = this.r + i - sb.line;
+ tcb[r] = sbl[i];
+ tsb[r] = sbs[i];
+ this.redraw(r);
+ }
+ }
+ sb.line = ofs;
+ this.r = ml;
+ this.c = 0;
+ this.type(this.globals.lcMorePrompt1, this.globals.lcMorePromtp1Style);
+ this.type(this.globals.lcMorePrompt2, this.globals.lcMorePrompt2Style);
+ this.lock = false;
+ return;
+ } else if (buflen >= ml) {
+ var ofs = buflen - ml;
+ for (var i = 0; i < ml; i++) {
+ var r = ofs + i;
+ tcb[i] = sbl[r];
+ tsb[i] = sbs[r];
+ this.redraw(i);
+ }
+ this.r = ml - 1;
+ this.c = sb.c;
+ } else {
+ var dr = ml - buflen;
+ var ofs = this.r - dr;
+ for (var i = 0; i < dr; i++) {
+ var r = ofs + i;
+ for (var c = 0; c < this.maxCols; c++) {
+ tcb[i][c] = tcb[r][c];
+ tsb[i][c] = tsb[r][c];
+ }
+ this.redraw(i);
+ }
+ for (var i = 0; i < buflen; i++) {
+ var r = dr + i;
+ tcb[r] = sbl[i];
+ tsb[r] = sbs[i];
+ this.redraw(r);
+ }
+ this.r = ml - 1;
+ this.c = sb.c;
+ }
+ this.scrollBuf = null;
+ },
+ typeAt: function(r, c, text, style) {
+ var tr1 = this.r;
+ var tc1 = this.c;
+ this.cursorSet(r, c);
+ for (var i = 0; i < text.length; i++) {
+ var ch = text.charCodeAt(i);
+ if (!this.isPrintable(ch)) ch = 94;
+ this.charBuf[this.r][this.c] = ch;
+ this.styleBuf[this.r][this.c] = (style) ? style : 0;
+ var last_r = this.r;
+ this._incCol();
+ if (this.r != last_r) this.redraw(last_r);
+ }
+ this.redraw(this.r);
+ this.r = tr1;
+ this.c = tc1;
+ },
+ statusLine: function(text, style, offset) {
+ var ch, r;
+ style = ((style) && (!isNaN(style))) ? parseInt(style) & 15 : 0;
+ if ((offset) && (offset > 0)) r = this.conf.rows - offset
+ else r = this.conf.rows - 1;
+ for (var i = 0; i < this.conf.cols; i++) {
+ if (i < text.length) {
+ ch = text.charCodeAt(i);
+ if (!this.isPrintable(ch)) ch = 94;
+ } else ch = 0;
+ this.charBuf[r][i] = ch;
+ this.styleBuf[r][i] = style;
+ }
+ this.redraw(r);
+ },
+ printRowFromString: function(r, text, style) {
+ var ch;
+ style = ((style) && (!isNaN(style))) ? parseInt(style) & 15 : 0;
+ if ((r >= 0) && (r < this.maxLines)) {
+ if (typeof text != 'string') text = '' + text;
+ for (var i = 0; i < this.conf.cols; i++) {
+ if (i < text.length) {
+ ch = text.charCodeAt(i);
+ if (!this.isPrintable(ch)) ch = 94;
+ } else ch = 0;
+ this.charBuf[r][i] = ch;
+ this.styleBuf[r][i] = style;
+ }
+ this.redraw(r);
+ }
+ },
+ setChar: function(ch, r, c, style) {
+ this.charBuf[r][c] = ch;
+ this.styleBuf[this.r][this.c] = (style) ? style : 0;
+ this.redraw(r);
+ },
+ newLine: function() {
+ this.c = 0;
+ this._incRow();
+ },
+ _charOut: function(ch, style) {
+ this.charBuf[this.r][this.c] = ch;
+ this.styleBuf[this.r][this.c] = (style) ? style : 0;
+ this.redraw(this.r);
+ this._incCol();
+ },
+ _incCol: function() {
+ this.c++;
+ if (this.c >= this.maxCols) {
+ this.c = 0;
+ this._incRow();
+ }
+ },
+ _incRow: function() {
+ this.r++;
+ if (this.r >= this.maxLines) {
+ this._scrollLines(0, this.maxLines);
+ this.r = this.maxLines - 1;
+ }
+ },
+ _scrollLines: function(start, end) {
+ window.status = 'Scrolling lines ...';
+ start++;
+ for (var ri = start; ri < end; ri++) {
+ var rt = ri - 1;
+ this.charBuf[rt] = this.charBuf[ri];
+ this.styleBuf[rt] = this.styleBuf[ri];
+ }
+ var rt = end - 1;
+ this.charBuf[rt] = this.getRowArray(this.conf.cols, 0);
+ this.styleBuf[rt] = this.getRowArray(this.conf.cols, 0);
+ this.redraw(rt);
+ for (var r = end - 1; r >= start; r--) this.redraw(r - 1);
+ window.status = '';
+ },
+ clear: function() {
+ window.status = 'Clearing display ...';
+ this.cursorOff();
+ this.insert = false;
+ for (var ri = 0; ri < this.maxLines; ri++) {
+ this.charBuf[ri] = this.getRowArray(this.conf.cols, 0);
+ this.styleBuf[ri] = this.getRowArray(this.conf.cols, 0);
+ this.redraw(ri);
+ }
+ this.r = 0;
+ this.c = 0;
+ window.status = '';
+ },
+ reset: function() {
+ if (this.lock) return;
+ this.lock = true;
+ this.rawMode = false;
+ this.charMode = false;
+ this.maxLines = this.conf.rows;
+ this.maxCols = this.conf.cols;
+ this.lastLine = '';
+ this.lineBuffer = '';
+ this.inputChar = 0;
+ this.clear();
+ },
+ prompt: function() {
+ this.lock = true;
+ if (this.c > 0) this.newLine();
+ this.type(this.ps);
+ this._charOut(1);
+ this.lock = false;
+ this.cursorOn();
+ },
+ isPrintable: function(ch, unicodePage1only) {
+ if ((this.wrapping) && (this.globals.wrapChars[ch] == 4)) return true;
+ if ((unicodePage1only) && (ch > 255)) {
+ return ((ch == this.termKey.EURO) && (this.printEuro)) ? true : false;
+ }
+ return (((ch >= 32) && (ch != this.termKey.DEL)) || ((this.printTab) && (ch == this.termKey.TAB)));
+ },
+ cursorSet: function(r, c) {
+ var crsron = this.cursoractive;
+ if (crsron) this.cursorOff();
+ this.r = r % this.maxLines;
+ this.c = c % this.maxCols;
+ this._cursorReset(crsron);
+ },
+ cursorOn: function() {
+ if (this.blinkTimer) clearTimeout(this.blinkTimer);
+ this.blinkBuffer = this.styleBuf[this.r][this.c];
+ this._cursorBlink();
+ this.cursoractive = true;
+ },
+ cursorOff: function() {
+ if (this.blinkTimer) clearTimeout(this.blinkTimer);
+ if (this.cursoractive) {
+ this.styleBuf[this.r][this.c] = this.blinkBuffer;
+ this.redraw(this.r);
+ this.cursoractive = false;
+ }
+ },
+ cursorLeft: function() {
+ var crsron = this.cursoractive;
+ if (crsron) this.cursorOff();
+ var r = this.r;
+ var c = this.c;
+ if (c > 0) c--
+ else if (r > 0) {
+ c = this.maxCols - 1;
+ r--;
+ }
+ if (this.isPrintable(this.charBuf[r][c])) {
+ this.r = r;
+ this.c = c;
+ }
+ this.insert = true;
+ this._cursorReset(crsron);
+ },
+ cursorRight: function() {
+ var crsron = this.cursoractive;
+ if (crsron) this.cursorOff();
+ var r = this.r;
+ var c = this.c;
+ if (c < this.maxCols - 1) c++
+ else if (r < this.maxLines - 1) {
+ c = 0;
+ r++;
+ }
+ if (!this.isPrintable(this.charBuf[r][c])) {
+ this.insert = false;
+ }
+ if (this.isPrintable(this.charBuf[this.r][this.c])) {
+ this.r = r;
+ this.c = c;
+ }
+ this._cursorReset(crsron);
+ },
+ backspace: function() {
+ var crsron = this.cursoractive;
+ if (crsron) this.cursorOff();
+ var r = this.r;
+ var c = this.c;
+ if (c > 0) c--
+ else if (r > 0) {
+ c = this.maxCols - 1;
+ r--;
+ };
+ if (this.isPrintable(this.charBuf[r][c])) {
+ this._scrollLeft(r, c);
+ this.r = r;
+ this.c = c;
+ };
+ this._cursorReset(crsron);
+ },
+ fwdDelete: function() {
+ var crsron = this.cursoractive;
+ if (crsron) this.cursorOff();
+ if (this.isPrintable(this.charBuf[this.r][this.c])) {
+ this._scrollLeft(this.r, this.c);
+ if (!this.isPrintable(this.charBuf[this.r][this.c])) this.insert = false;
+ }
+ this._cursorReset(crsron);
+ },
+ _cursorReset: function(crsron) {
+ if (crsron) this.cursorOn()
+ else {
+ this.blinkBuffer = this.styleBuf[this.r][this.c];
+ }
+ },
+ _cursorBlink: function() {
+ if (this.blinkTimer) clearTimeout(this.blinkTimer);
+ if (this == this.globals.activeTerm) {
+ if (this.crsrBlockMode) {
+ this.styleBuf[this.r][this.c] = (this.styleBuf[this.r][this.c] & 1) ? this.styleBuf[this.r][this.c] & 254 : this.styleBuf[this.r][this.c] | 1;
+ } else {
+ this.styleBuf[this.r][this.c] = (this.styleBuf[this.r][this.c] & 2) ? this.styleBuf[this.r][this.c] & 253 : this.styleBuf[this.r][this.c] | 2;
+ }
+ this.redraw(this.r);
+ }
+ if (this.crsrBlinkMode) this.blinkTimer = setTimeout('Terminal.prototype.globals.activeTerm._cursorBlink()', this.blinkDelay);
+ },
+ _scrollLeft: function(r, c) {
+ var rows = new Array();
+ rows[0] = r;
+ while (this.isPrintable(this.charBuf[r][c])) {
+ var ri = r;
+ var ci = c + 1;
+ if (ci == this.maxCols) {
+ if (ri < this.maxLines - 1) {
+ ci = 0;
+ ri++;
+ rows[rows.length] = ri;
+ } else {
+ break;
+ }
+ }
+ this.charBuf[r][c] = this.charBuf[ri][ci];
+ this.styleBuf[r][c] = this.styleBuf[ri][ci];
+ c = ci;
+ r = ri;
+ }
+ if (this.charBuf[r][c] != 0) this.charBuf[r][c] = 0;
+ for (var i = 0; i < rows.length; i++) this.redraw(rows[i]);
+ },
+ _scrollRight: function(r, c) {
+ var rows = new Array();
+ var end = this._getLineEnd(r, c);
+ var ri = end[0];
+ var ci = end[1];
+ if ((ci == this.maxCols - 1) && (ri == this.maxLines - 1)) {
+ if (r == 0) return;
+ this._scrollLines(0, this.maxLines);
+ this.r--;
+ r--;
+ ri--;
+ }
+ rows[r] = 1;
+ while (this.isPrintable(this.charBuf[ri][ci])) {
+ var rt = ri;
+ var ct = ci + 1;
+ if (ct == this.maxCols) {
+ ct = 0;
+ rt++;
+ rows[rt] = 1;
+ }
+ this.charBuf[rt][ct] = this.charBuf[ri][ci];
+ this.styleBuf[rt][ct] = this.styleBuf[ri][ci];
+ if ((ri == r) && (ci == c)) break;
+ ci--;
+ if (ci < 0) {
+ ci = this.maxCols - 1;
+ ri--;
+ rows[ri] = 1;
+ }
+ }
+ for (var i = r; i < this.maxLines; i++) {
+ if (rows[i]) this.redraw(i);
+ }
+ },
+ _getLineEnd: function(r, c) {
+ if (!this.isPrintable(this.charBuf[r][c])) {
+ c--;
+ if (c < 0) {
+ if (r > 0) {
+ r--;
+ c = this.maxCols - 1;
+ } else {
+ c = 0;
+ }
+ }
+ }
+ if (this.isPrintable(this.charBuf[r][c])) {
+ while (true) {
+ var ri = r;
+ var ci = c + 1;
+ if (ci == this.maxCols) {
+ if (ri < this.maxLines - 1) {
+ ri++;
+ ci = 0;
+ } else {
+ break;
+ }
+ }
+ if (!this.isPrintable(this.charBuf[ri][ci])) break;
+ c = ci;
+ r = ri;
+ }
+ }
+ return [r, c];
+ },
+ _getLineStart: function(r, c) {
+ var ci, ri;
+ if (!this.isPrintable(this.charBuf[r][c])) {
+ ci = c - 1;
+ ri = r;
+ if (ci < 0) {
+ if (ri == 0) return [0, 0];
+ ci = this.maxCols - 1;
+ ri--;
+ }
+ if (!this.isPrintable(this.charBuf[ri][ci])) return [r, c]
+ else {
+ r = ri;
+ c = ci;
+ }
+ }
+ while (true) {
+ var ri = r;
+ var ci = c - 1;
+ if (ci < 0) {
+ if (ri == 0) break;
+ ci = this.maxCols - 1;
+ ri--;
+ }
+ if (!this.isPrintable(this.charBuf[ri][ci])) break;;
+ r = ri;
+ c = ci;
+ }
+ return [r, c];
+ },
+ _getLine: function() {
+ var end = this._getLineEnd(this.r, this.c);
+ var r = end[0];
+ var c = end[1];
+ var line = new Array();
+ while (this.isPrintable(this.charBuf[r][c])) {
+ line[line.length] = String.fromCharCode(this.charBuf[r][c]);
+ if (c > 0) c--
+ else if (r > 0) {
+ c = this.maxCols - 1;
+ r--;
+ }
+ else break;
+ }
+ line.reverse();
+ return line.join('');
+ },
+ _clearLine: function() {
+ var end = this._getLineEnd(this.r, this.c);
+ var r = end[0];
+ var c = end[1];
+ var line = '';
+ while (this.isPrintable(this.charBuf[r][c])) {
+ this.charBuf[r][c] = 0;
+ if (c > 0) {
+ c--;
+ } else if (r > 0) {
+ this.redraw(r);
+ c = this.maxCols - 1;
+ r--;
+ } else break;
+ }
+ if (r != end[0]) this.redraw(r);
+ c++;
+ this.cursorSet(r, c);
+ this.insert = false;
+ },
+ focus: function() {
+ this.globals.setFocus(this);
+ },
+ termKey: null,
+ _makeTerm: function(rebuild) {
+ window.status = 'Building terminal ...';
+ this.globals.hasLayers = (document.layers) ? true : false;
+ this.globals.hasSubDivs = (navigator.userAgent.indexOf('Gecko') < 0);
+ var divPrefix = this.termDiv + '_r';
+ var s = '';
+ s += '<table border="0" cellspacing="0" cellpadding="' + this.conf.frameWidth + '">\n';
+ s += '<tr><td bgcolor="' + this.conf.frameColor + '"><table border="0" cellspacing="0" cellpadding="2"><tr><td bgcolor="' + this.conf.bgColor + '"><table border="0" cellspacing="0" cellpadding="0">\n';
+ var rstr = '';
+ for (var c = 0; c < this.conf.cols; c++) rstr += '&nbsp;';
+ for (var r = 0; r < this.conf.rows; r++) {
+ var termid = ((this.globals.hasLayers) || (this.globals.hasSubDivs)) ? '' : ' id="' + divPrefix + r + '"';
+ s += '<tr><td nowrap height="' + this.conf.rowHeight + '"' + termid + ' class="' + this.conf.fontClass + '">' + rstr + '<\/td><\/tr>\n';
+ }
+ s += '<\/table><\/td><\/tr>\n';
+ s += '<\/table><\/td><\/tr>\n';
+ s += '<\/table>\n';
+ var termOffset = 48 + this.conf.frameWidth;
+ if (this.globals.hasLayers) {
+ for (var r = 0; r < this.conf.rows; r++) {
+ s += '<layer name="' + divPrefix + r + '" top="' + (termOffset + r * this.conf.rowHeight) + '" left="' + termOffset + '" class="' + this.conf.fontClass + '"><\/layer>\n';
+ }
+ this.ns4ParentDoc = document.layers[this.termDiv].document;
+ this.globals.termStringStart = '<table border="0" cellspacing="0" cellpadding="0"><tr><td nowrap height="' + this.conf.rowHeight + '" class="' + this.conf.fontClass + '">';
+ this.globals.termStringEnd = '<\/td><\/tr><\/table>';
+ } else if (this.globals.hasSubDivs) {
+ for (var r = 0; r < this.conf.rows; r++) {
+ s += '<div id="' + divPrefix + r + '" style="position:absolute; top:' + (termOffset + r * this.conf.rowHeight) + 'px; left: ' + termOffset + 'px;" class="' + this.conf.fontClass + '"><\/div>\n';
+ }
+ this.globals.termStringStart = '<table border="0" cellspacing="0" cellpadding="0"><tr><td nowrap height="' + this.conf.rowHeight + '" class="' + this.conf.fontClass + '">';
+ this.globals.termStringEnd = '<\/td><\/tr><\/table>';
+ }
+ this.globals.writeElement(this.termDiv, s);
+ if (!rebuild) {
+ this.globals.setElementXY(this.termDiv, this.conf.x, this.conf.y);
+ this.globals.setVisible(this.termDiv, 1);
+ }
+ window.status = '';
+ },
+ rebuild: function() {
+ var rl = this.conf.rows;
+ var cl = this.conf.cols;
+ for (var r = 0; r < rl; r++) {
+ var cbr = this.charBuf[r];
+ if (!cbr) {
+ this.charBuf[r] = this.getRowArray(cl, 0);
+ this.styleBuf[r] = this.getRowArray(cl, 0);
+ } else if (cbr.length < cl) {
+ for (var c = cbr.length; c < cl; c++) {
+ this.charBuf[r][c] = 0;
+ this.styleBuf[r][c] = 0;
+ }
+ }
+ }
+ var resetcrsr = false;
+ if (this.r >= rl) {
+ r = rl - 1;
+ resetcrsr = true;
+ }
+ if (this.c >= cl) {
+ c = cl - 1;
+ resetcrsr = true;
+ }
+ if ((resetcrsr) && (this.cursoractive)) this.cursorOn();
+ this._makeTerm(true);
+ for (var r = 0; r < rl; r++) {
+ this.redraw(r);
+ }
+ },
+ moveTo: function(x, y) {
+ this.globals.setElementXY(this.termDiv, x, y);
+ },
+ resizeTo: function(x, y) {
+ if (this.termDivReady()) {
+ x = parseInt(x, 10);
+ y = parseInt(y, 10);
+ if ((isNaN(x)) || (isNaN(y)) || (x < 4) || (y < 2)) return false;
+ this.maxCols = this.conf.cols = x;
+ this.maxLines = this.conf.rows = y;
+ this._makeTerm();
+ this.clear();
+ return true;
+ } else return false;
+ },
+ redraw: function(r) {
+ var s = this.globals.termStringStart;
+ var curStyle = 0;
+ var tstls = this.globals.termStyles;
+ var tscls = this.globals.termStyleClose;
+ var tsopn = this.globals.termStyleOpen;
+ var tspcl = this.globals.termSpecials;
+ var tclrs = this.globals.colorCodes;
+ var tnclrs = this.globals.nsColorCodes;
+ var twclrs = this.globals.webColorCodes;
+ var t_cb = this.charBuf;
+ var t_sb = this.styleBuf;
+ var clr;
+ for (var i = 0; i < this.conf.cols; i++) {
+ var c = t_cb[r][i];
+ var cs = t_sb[r][i];
+ if (cs != curStyle) {
+ if (curStyle) {
+ if (curStyle & 0xffff00) s += '</span>';
+ for (var k = tstls.length - 1; k >= 0; k--) {
+ var st = tstls[k];
+ if (curStyle & st) s += tscls[st];
+ }
+ }
+ curStyle = cs;
+ for (var k = 0; k < tstls.length; k++) {
+ var st = tstls[k];
+ if (curStyle & st) s += tsopn[st];
+ }
+ clr = '';
+ if (curStyle & 0xff00) {
+ var cc = (curStyle & 0xff00) >>> 8;
+ clr = (cc < 16) ? tclrs[cc] : '#' + tnclrs[cc - 16];
+ } else if (curStyle & 0xff0000) {
+ clr = '#' + twclrs[(curStyle & 0xff0000) >>> 16];
+ }
+ if (clr) {
+ if (curStyle & 1) {
+ s += '<span style="background-color:' + clr + ' !important;">';
+ } else {
+ s += '<span style="color:' + clr + ' !important;">';
+ }
+ }
+ }
+ s += (tspcl[c]) ? tspcl[c] : String.fromCharCode(c);
+ }
+ if (curStyle > 0) {
+ if (curStyle & 0xffff00) s += '</span>';
+ for (var k = tstls.length - 1; k >= 0; k--) {
+ var st = tstls[k];
+ if (curStyle & st) s += tscls[st];
+ }
+ }
+ s += this.globals.termStringEnd;
+ this.globals.writeElement(this.termDiv + '_r' + r, s, this.ns4ParentDoc);
+ },
+ guiReady: function() {
+ ready = true;
+ if (this.globals.guiElementsReady(this.termDiv, window.document)) {
+ for (var r = 0; r < this.conf.rows; r++) {
+ if (this.globals.guiElementsReady(this.termDiv + '_r' + r, this.ns4ParentDoc) == false) {
+ ready = false;
+ break;
+ }
+ }
+ } else ready = false;
+ return ready;
+ },
+ termDivReady: function() {
+ if (document.layers) {
+ return (document.layers[this.termDiv]) ? true : false;
+ } else if (document.getElementById) {
+ return (document.getElementById(this.termDiv)) ? true : false;
+ } else if (document.all) {
+ return (document.all[this.termDiv]) ? true : false;
+ } else {
+ return false;
+ }
+ },
+ getDimensions: function() {
+ var w = 0;
+ var h = 0;
+ var d = this.termDiv;
+ if (document.layers) {
+ if (document.layers[d]) {
+ w = document.layers[d].clip.right;
+ h = document.layers[d].clip.bottom;
+ }
+ } else if (document.getElementById) {
+ var obj = document.getElementById(d);
+ if ((obj) && (obj.firstChild)) {
+ w = parseInt(obj.firstChild.offsetWidth, 10);
+ h = parseInt(obj.firstChild.offsetHeight, 10);
+ } else if ((obj) && (obj.children) && (obj.children[0])) {
+ w = parseInt(obj.children[0].offsetWidth, 10);
+ h = parseInt(obj.children[0].offsetHeight, 10);
+ }
+ } else if (document.all) {
+ var obj = document.all[d];
+ if ((obj) && (obj.children) && (obj.children[0])) {
+ w = parseInt(obj.children[0].offsetWidth, 10);
+ h = parseInt(obj.children[0].offsetHeight, 10);
+ }
+ }
+ return {
+ width: w,
+ height: h
+ };
+ },
+ globals: {
+ termToInitialze: null,
+ activeTerm: null,
+ kbdEnabled: false,
+ keylock: false,
+ keyRepeatDelay1: 450,
+ keyRepeatDelay2: 100,
+ keyRepeatTimer: null,
+ lcMorePrompt1: ' -- MORE -- ',
+ lcMorePromtp1Style: 1,
+ lcMorePrompt2: ' (Type: space to continue, \'q\' to quit)',
+ lcMorePrompt2Style: 0,
+ lcMoreKeyAbort: 113,
+ lcMoreKeyContinue: 32,
+ _initGlobals: function() {
+ var tg = Terminal.prototype.globals;
+ tg._extendMissingStringMethods();
+ tg._initWebColors();
+ tg._initDomKeyRef();
+ Terminal.prototype.termKey = tg.termKey;
+ },
+ getHexChar: function(c) {
+ var tg = Terminal.prototype.globals;
+ if (tg.isHexChar(c)) return tg.hexToNum[c];
+ return -1;
+ },
+ isHexChar: function(c) {
+ return (((c >= '0') && (c <= '9')) || ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F'))) ? true : false;
+ },
+ isHexOnlyChar: function(c) {
+ return (((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F'))) ? true : false;
+ },
+ hexToNum: {
+ '0': 0,
+ '1': 1,
+ '2': 2,
+ '3': 3,
+ '4': 4,
+ '5': 5,
+ '6': 6,
+ '7': 7,
+ '8': 8,
+ '9': 9,
+ 'a': 10,
+ 'b': 11,
+ 'c': 12,
+ 'd': 13,
+ 'e': 14,
+ 'f': 15,
+ 'A': 10,
+ 'B': 11,
+ 'C': 12,
+ 'D': 13,
+ 'E': 14,
+ 'F': 15
+ },
+ webColors: [],
+ webColorCodes: [''],
+ colors: {
+ black: 1,
+ red: 2,
+ green: 3,
+ yellow: 4,
+ blue: 5,
+ magenta: 6,
+ cyan: 7,
+ white: 8,
+ grey: 9,
+ red2: 10,
+ green2: 11,
+ yellow2: 12,
+ blue2: 13,
+ magenta2: 14,
+ cyan2: 15,
+ red1: 2,
+ green1: 3,
+ yellow1: 4,
+ blue1: 5,
+ magenta1: 6,
+ cyan1: 7,
+ gray: 9,
+ darkred: 10,
+ darkgreen: 11,
+ darkyellow: 12,
+ darkblue: 13,
+ darkmagenta: 14,
+ darkcyan: 15,
+ 'default': 0,
+ clear: 0
+ },
+ colorCodes: ['', '#000000', '#ff0000', '#00ff00', '#ffff00', '#0066ff', '#ff00ff', '#00ffff', '#ffffff', '#808080', '#990000', '#009900', '#999900', '#003399', '#990099', '#009999'],
+ nsColors: {
+ 'aliceblue': 1,
+ 'antiquewhite': 2,
+ 'aqua': 3,
+ 'aquamarine': 4,
+ 'azure': 5,
+ 'beige': 6,
+ 'black': 7,
+ 'blue': 8,
+ 'blueviolet': 9,
+ 'brown': 10,
+ 'burlywood': 11,
+ 'cadetblue': 12,
+ 'chartreuse': 13,
+ 'chocolate': 14,
+ 'coral': 15,
+ 'cornflowerblue': 16,
+ 'cornsilk': 17,
+ 'crimson': 18,
+ 'darkblue': 19,
+ 'darkcyan': 20,
+ 'darkgoldenrod': 21,
+ 'darkgray': 22,
+ 'darkgreen': 23,
+ 'darkkhaki': 24,
+ 'darkmagenta': 25,
+ 'darkolivegreen': 26,
+ 'darkorange': 27,
+ 'darkorchid': 28,
+ 'darkred': 29,
+ 'darksalmon': 30,
+ 'darkseagreen': 31,
+ 'darkslateblue': 32,
+ 'darkslategray': 33,
+ 'darkturquoise': 34,
+ 'darkviolet': 35,
+ 'deeppink': 36,
+ 'deepskyblue': 37,
+ 'dimgray': 38,
+ 'dodgerblue': 39,
+ 'firebrick': 40,
+ 'floralwhite': 41,
+ 'forestgreen': 42,
+ 'fuchsia': 43,
+ 'gainsboro': 44,
+ 'ghostwhite': 45,
+ 'gold': 46,
+ 'goldenrod': 47,
+ 'gray': 48,
+ 'green': 49,
+ 'greenyellow': 50,
+ 'honeydew': 51,
+ 'hotpink': 52,
+ 'indianred': 53,
+ 'indigo': 54,
+ 'ivory': 55,
+ 'khaki': 56,
+ 'lavender': 57,
+ 'lavenderblush': 58,
+ 'lawngreen': 59,
+ 'lemonchiffon': 60,
+ 'lightblue': 61,
+ 'lightcoral': 62,
+ 'lightcyan': 63,
+ 'lightgoldenrodyellow': 64,
+ 'lightgreen': 65,
+ 'lightgrey': 66,
+ 'lightpink': 67,
+ 'lightsalmon': 68,
+ 'lightseagreen': 69,
+ 'lightskyblue': 70,
+ 'lightslategray': 71,
+ 'lightsteelblue': 72,
+ 'lightyellow': 73,
+ 'lime': 74,
+ 'limegreen': 75,
+ 'linen': 76,
+ 'maroon': 77,
+ 'mediumaquamarine': 78,
+ 'mediumblue': 79,
+ 'mediumorchid': 80,
+ 'mediumpurple': 81,
+ 'mediumseagreen': 82,
+ 'mediumslateblue': 83,
+ 'mediumspringgreen': 84,
+ 'mediumturquoise': 85,
+ 'mediumvioletred': 86,
+ 'midnightblue': 87,
+ 'mintcream': 88,
+ 'mistyrose': 89,
+ 'moccasin': 90,
+ 'navajowhite': 91,
+ 'navy': 92,
+ 'oldlace': 93,
+ 'olive': 94,
+ 'olivedrab': 95,
+ 'orange': 96,
+ 'orangered': 97,
+ 'orchid': 98,
+ 'palegoldenrod': 99,
+ 'palegreen': 100,
+ 'paleturquoise': 101,
+ 'palevioletred': 102,
+ 'papayawhip': 103,
+ 'peachpuff': 104,
+ 'peru': 105,
+ 'pink': 106,
+ 'plum': 107,
+ 'powderblue': 108,
+ 'purple': 109,
+ 'red': 110,
+ 'rosybrown': 111,
+ 'royalblue': 112,
+ 'saddlebrown': 113,
+ 'salmon': 114,
+ 'sandybrown': 115,
+ 'seagreen': 116,
+ 'seashell': 117,
+ 'sienna': 118,
+ 'silver': 119,
+ 'skyblue': 120,
+ 'slateblue': 121,
+ 'slategray': 122,
+ 'snow': 123,
+ 'springgreen': 124,
+ 'steelblue': 125,
+ 'tan': 126,
+ 'teal': 127,
+ 'thistle': 128,
+ 'tomato': 129,
+ 'turquoise': 130,
+ 'violet': 131,
+ 'wheat': 132,
+ 'white': 133,
+ 'whitesmoke': 134,
+ 'yellow': 135,
+ 'yellowgreen': 136
+ },
+ nsColorCodes: ['', 'f0f8ff', 'faebd7', '00ffff', '7fffd4', 'f0ffff', 'f5f5dc', '000000', '0000ff', '8a2be2', 'a52a2a', 'deb887', '5f9ea0', '7fff00', 'd2691e', 'ff7f50', '6495ed', 'fff8dc', 'dc143c', '00008b', '008b8b', 'b8860b', 'a9a9a9', '006400', 'bdb76b', '8b008b', '556b2f', 'ff8c00', '9932cc', '8b0000', 'e9967a', '8fbc8f', '483d8b', '2f4f4f', '00ced1', '9400d3', 'ff1493', '00bfff', '696969', '1e90ff', 'b22222', 'fffaf0', '228b22', 'ff00ff', 'dcdcdc', 'f8f8ff', 'ffd700', 'daa520', '808080', '008000', 'adff2f', 'f0fff0', 'ff69b4', 'cd5c5c', '4b0082', 'fffff0', 'f0e68c', 'e6e6fa', 'fff0f5', '7cfc00', 'fffacd', 'add8e6', 'f08080', 'e0ffff', 'fafad2', '90ee90', 'd3d3d3', 'ffb6c1', 'ffa07a', '20b2aa', '87cefa', '778899', 'b0c4de', 'ffffe0', '00ff00', '32cd32', 'faf0e6', '800000', '66cdaa', '0000cd', 'ba55d3', '9370db', '3cb371', '7b68ee', '00fa9a', '48d1cc', 'c71585', '191970', 'f5fffa', 'ffe4e1', 'ffe4b5', 'ffdead', '000080', 'fdf5e6', '808000', '6b8e23', 'ffa500', 'ff4500', 'da70d6', 'eee8aa', '98fb98', 'afeeee', 'db7093', 'ffefd5', 'ffdab9', 'cd853f', 'ffc0cb', 'dda0dd', 'b0e0e6', '800080', 'ff0000', 'bc8f8f', '4169e1', '8b4513', 'fa8072', 'f4a460', '2e8b57', 'fff5ee', 'a0522d', 'c0c0c0', '87ceeb', '6a5acd', '708090', 'fffafa', '00ff7f', '4682b4', 'd2b48c', '008080', 'd8bfd8', 'ff6347', '40e0d0', 'ee82ee', 'f5deb3', 'ffffff', 'f5f5f5', 'ffff00', '9acd32'],
+ _webSwatchChars: ['0', '3', '6', '9', 'c', 'f'],
+ _initWebColors: function() {
+ var tg = Terminal.prototype.globals;
+ var ws = tg._webColorSwatch;
+ var wn = tg.webColors;
+ var cc = tg.webColorCodes;
+ var n = 1;
+ var a, b, c, al, bl, bs, cl;
+ for (var i = 0; i < 6; i++) {
+ a = tg._webSwatchChars[i];
+ al = a + a;
+ for (var j = 0; j < 6; j++) {
+ b = tg._webSwatchChars[j];
+ bl = al + b + b;
+ bs = a + b;
+ for (var k = 0; k < 6; k++) {
+ c = tg._webSwatchChars[k];
+ cl = bl + c + c;
+ wn[bs + c] = wn[cl] = n;
+ cc[n] = cl;
+ n++;
+ }
+ }
+ }
+ },
+ webifyColor: function(s) {
+ var tg = Terminal.prototype.globals;
+ if (s.length == 6) {
+ var c = '';
+ for (var i = 0; i < 6; i += 2) {
+ var a = s.charAt(i);
+ var b = s.charAt(i + 1);
+ if ((tg.isHexChar(a)) && (tg.isHexChar(b))) {
+ c += tg._webSwatchChars[Math.round(parseInt(a + b, 16) / 255 * 5)];
+ } else {
+ return '';
+ }
+ }
+ return c;
+ } else if (s.length == 3) {
+ var c = '';
+ for (var i = 0; i < 3; i++) {
+ var a = s.charAt(i);
+ if (tg.isHexChar(a)) {
+ c += tg._webSwatchChars[Math.round(parseInt(a, 16) / 15 * 5)];
+ } else {
+ return '';
+ }
+ }
+ return c;
+ } else return '';
+ },
+ setColor: function(label, value) {
+ var tg = Terminal.prototype.globals;
+ if ((typeof label == 'number') && (label >= 1) && (label <= 15)) {
+ tg.colorCodes[label] = value;
+ } else if (typeof label == 'string') {
+ label = label.toLowerCase();
+ if ((label.length == 1) && (tg.isHexChar(label))) {
+ var n = tg.hexToNum[label];
+ if (n) tg.colorCodes[n] = value;
+ } else if (typeof tg.colors[label] != 'undefined') {
+ var n = tg.colors[label];
+ if (n) tg.colorCodes[n] = value;
+ }
+ }
+ },
+ getColorString: function(label) {
+ var tg = Terminal.prototype.globals;
+ if ((typeof label == 'number') && (label >= 0) && (label <= 15)) {
+ return tg.colorCodes[label];
+ } else if (typeof label == 'string') {
+ label = label.toLowerCase();
+ if ((label.length == 1) && (tg.isHexChar(label))) {
+ return tg.colorCodes[tg.hexToNum[label]];
+ } else if ((typeof tg.colors[label] != 'undefined')) {
+ return tg.colorCodes[tg.colors[label]];
+ }
+ }
+ return '';
+ },
+ getColorCode: function(label) {
+ var tg = Terminal.prototype.globals;
+ if ((typeof label == 'number') && (label >= 0) && (label <= 15)) {
+ return label;
+ } else if (typeof label == 'string') {
+ label = label.toLowerCase();
+ if ((label.length == 1) && (tg.isHexChar(label))) {
+ return parseInt(label, 16);
+ } else if ((typeof tg.colors[label] != 'undefined')) {
+ return tg.colors[label];
+ }
+ }
+ return 0;
+ },
+ insertText: function(text) {
+ var tg = Terminal.prototype.globals;
+ var termRef = tg.activeTerm;
+ if ((!termRef) || (termRef.closed) || (tg.keylock) || (termRef.lock) || (termRef.charMode)) return false;
+ for (var i = 0; i < text.length; i++) {
+ tg.keyHandler({
+ which: text.charCodeAt(i),
+ _remapped: true
+ });
+ }
+ return true;
+ },
+ importEachLine: function(text) {
+ var tg = Terminal.prototype.globals;
+ var termRef = tg.activeTerm;
+ if ((!termRef) || (termRef.closed) || (tg.keylock) || (termRef.lock) || (termRef.charMode)) return false;
+ termRef.cursorOff();
+ termRef._clearLine();
+ text = text.replace(/\r\n?/g, '\n');
+ var t = text.split('\n');
+ for (var i = 0; i < t.length; i++) {
+ for (var k = 0; k < t[i].length; k++) {
+ tg.keyHandler({
+ which: t[i].charCodeAt(k),
+ _remapped: true
+ });
+ }
+ tg.keyHandler({
+ which: term.termKey.CR,
+ _remapped: true
+ });
+ }
+ return true;
+ },
+ importMultiLine: function(text) {
+ var tg = Terminal.prototype.globals;
+ var termRef = tg.activeTerm;
+ if ((!termRef) || (termRef.closed) || (tg.keylock) || (termRef.lock) || (termRef.charMode)) return false;
+ termRef.lock = true;
+ termRef.cursorOff();
+ termRef._clearLine();
+ text = text.replace(/\r\n?/g, '\n');
+ var lines = text.split('\n');
+ for (var i = 0; i < lines.length; i++) {
+ termRef.type(lines[i]);
+ if (i < lines.length - 1) termRef.newLine();
+ }
+ termRef.lineBuffer = text;
+ termRef.lastLine = '';
+ termRef.inputChar = 0;
+ termRef.handler();
+ return true;
+ },
+ normalize: function(n, m) {
+ var s = '' + n;
+ while (s.length < m) s = '0' + s;
+ return s;
+ },
+ fillLeft: function(t, n) {
+ if (typeof t != 'string') t = '' + t;
+ while (t.length < n) t = ' ' + t;
+ return t;
+ },
+ center: function(t, l) {
+ var s = '';
+ for (var i = t.length; i < l; i += 2) s += ' ';
+ return s + t;
+ },
+ stringReplace: function(s1, s2, t) {
+ var l1 = s1.length;
+ var l2 = s2.length;
+ var ofs = t.indexOf(s1);
+ while (ofs >= 0) {
+ t = t.substring(0, ofs) + s2 + t.substring(ofs + l1);
+ ofs = t.indexOf(s1, ofs + l2);
+ }
+ return t;
+ },
+ wrapChars: {
+ 9: 1,
+ 10: 1,
+ 12: 4,
+ 13: 1,
+ 32: 1,
+ 40: 3,
+ 45: 2,
+ 61: 2,
+ 91: 3,
+ 94: 3,
+ 123: 3
+ },
+ setFocus: function(termref) {
+ Terminal.prototype.globals.activeTerm = termref;
+ Terminal.prototype.globals.clearRepeatTimer();
+ },
+ termKey: {
+ 'NUL': 0x00,
+ 'SOH': 0x01,
+ 'STX': 0x02,
+ 'ETX': 0x03,
+ 'EOT': 0x04,
+ 'ENQ': 0x05,
+ 'ACK': 0x06,
+ 'BEL': 0x07,
+ 'BS': 0x08,
+ 'BACKSPACE': 0x08,
+ 'HT': 0x09,
+ 'TAB': 0x09,
+ 'LF': 0x0A,
+ 'VT': 0x0B,
+ 'FF': 0x0C,
+ 'CR': 0x0D,
+ 'SO': 0x0E,
+ 'SI': 0x0F,
+ 'DLE': 0x10,
+ 'DC1': 0x11,
+ 'DC2': 0x12,
+ 'DC3': 0x13,
+ 'DC4': 0x14,
+ 'NAK': 0x15,
+ 'SYN': 0x16,
+ 'ETB': 0x17,
+ 'CAN': 0x18,
+ 'EM': 0x19,
+ 'SUB': 0x1A,
+ 'ESC': 0x1B,
+ 'IS4': 0x1C,
+ 'IS3': 0x1D,
+ 'IS2': 0x1E,
+ 'IS1': 0x1F,
+ 'DEL': 0x7F,
+ 'EURO': 0x20AC,
+ 'LEFT': 0x1C,
+ 'RIGHT': 0x1D,
+ 'UP': 0x1E,
+ 'DOWN': 0x1F
+ },
+ termDomKeyRef: {},
+ _domKeyMappingData: {
+ 'LEFT': 'LEFT',
+ 'RIGHT': 'RIGHT',
+ 'UP': 'UP',
+ 'DOWN': 'DOWN',
+ 'BACK_SPACE': 'BS',
+ 'RETURN': 'CR',
+ 'ENTER': 'CR',
+ 'ESCAPE': 'ESC',
+ 'DELETE': 'DEL',
+ 'TAB': 'TAB'
+ },
+ _initDomKeyRef: function() {
+ var tg = Terminal.prototype.globals;
+ var m = tg._domKeyMappingData;
+ var r = tg.termDomKeyRef;
+ var k = tg.termKey;
+ for (var i in m) r['DOM_VK_' + i] = k[m[i]];
+ },
+ registerEvent: function(obj, eventType, handler, capture) {
+ if (obj.addEventListener) {
+ obj.addEventListener(eventType.toLowerCase(), handler, capture);
+ } else {
+ var et = eventType.toUpperCase();
+ if ((window.Event) && (window.Event[et]) && (obj.captureEvents)) obj.captureEvents(Event[et]);
+ obj['on' + eventType.toLowerCase()] = handler;
+ }
+ },
+ releaseEvent: function(obj, eventType, handler, capture) {
+ if (obj.removeEventListener) {
+ obj.removeEventListener(eventType.toLowerCase(), handler, capture);
+ } else {
+ var et = eventType.toUpperCase();
+ if ((window.Event) && (window.Event[et]) && (obj.releaseEvents)) obj.releaseEvents(Event[et]);
+ et = 'on' + eventType.toLowerCase();
+ if ((obj[et]) && (obj[et] == handler)) obj.et = null;
+ }
+ },
+ enableKeyboard: function(term) {
+ var tg = Terminal.prototype.globals;
+ if (!tg.kbdEnabled) {
+ tg.registerEvent(document, 'keypress', tg.keyHandler, true);
+ tg.registerEvent(document, 'keydown', tg.keyFix, true);
+ tg.registerEvent(document, 'keyup', tg.clearRepeatTimer, true);
+ tg.kbdEnabled = true;
+ }
+ tg.activeTerm = term;
+ },
+ disableKeyboard: function(term) {
+ var tg = Terminal.prototype.globals;
+ if (tg.kbdEnabled) {
+ tg.releaseEvent(document, 'keypress', tg.keyHandler, true);
+ tg.releaseEvent(document, 'keydown', tg.keyFix, true);
+ tg.releaseEvent(document, 'keyup', tg.clearRepeatTimer, true);
+ tg.kbdEnabled = false;
+ }
+ tg.activeTerm = null;
+ },
+ keyFix: function(e) {
+ var tg = Terminal.prototype.globals;
+ var term = tg.activeTerm;
+ if ((tg.keylock) || (term.lock)) return true;
+ if (window.event) {
+ var ch = window.event.keyCode;
+ if (!e) e = window.event;
+ if (e.DOM_VK_UP) {
+ for (var i in tg.termDomKeyRef) {
+ if ((e[i]) && (ch == e[i])) {
+ tg.keyHandler({
+ which: tg.termDomKeyRef[i],
+ _remapped: true,
+ _repeat: (ch == 0x1B) ? true : false
+ });
+ if (e.preventDefault) e.preventDefault();
+ if (e.stopPropagation) e.stopPropagation();
+ e.cancleBubble = true;
+ return false;
+ }
+ }
+ e.cancleBubble = false;
+ return true;
+ } else {
+ var termKey = term.termKey;
+ var keyHandler = tg.keyHandler;
+ if ((ch == 8) && (!term.isSafari) && (!term.isOpera)) keyHandler({
+ which: termKey.BS,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 9) keyHandler({
+ which: termKey.TAB,
+ _remapped: true,
+ _repeat: (term.printTab) ? false : true
+ })
+ else if (ch == 37) keyHandler({
+ which: termKey.LEFT,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 39) keyHandler({
+ which: termKey.RIGHT,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 38) keyHandler({
+ which: termKey.UP,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 40) keyHandler({
+ which: termKey.DOWN,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 127) keyHandler({
+ which: termKey.DEL,
+ _remapped: true,
+ _repeat: true
+ })
+ else if ((ch >= 57373) && (ch <= 57376)) {
+ if (ch == 57373) keyHandler({
+ which: termKey.UP,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 57374) keyHandler({
+ which: termKey.DOWN,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 57375) keyHandler({
+ which: termKey.LEFT,
+ _remapped: true,
+ _repeat: true
+ })
+ else if (ch == 57376) keyHandler({
+ which: termKey.RIGHT,
+ _remapped: true,
+ _repeat: true
+ });
+ } else {
+ e.cancleBubble = false;
+ return true;
+ }
+ if (e.preventDefault) e.preventDefault();
+ if (e.stopPropagation) e.stopPropagation();
+ e.cancleBubble = true;
+ return false;
+ }
+ }
+ },
+ clearRepeatTimer: function(e) {
+ var tg = Terminal.prototype.globals;
+ if (tg.keyRepeatTimer) {
+ clearTimeout(tg.keyRepeatTimer);
+ tg.keyRepeatTimer = null;
+ }
+ },
+ doKeyRepeat: function(ch) {
+ Terminal.prototype.globals.keyHandler({
+ which: ch,
+ _remapped: true,
+ _repeated: true
+ })
+ },
+ keyHandler: function(e) {
+ var tg = Terminal.prototype.globals;
+ var term = tg.activeTerm;
+ if ((tg.keylock) || (term.lock)) return true;
+ if ((window.event) && (window.event.preventDefault)) window.event.preventDefault()
+ else if ((e) && (e.preventDefault)) e.preventDefault();
+ if ((window.event) && (window.event.stopPropagation)) window.event.stopPropagation()
+ else if ((e) && (e.stopPropagation)) e.stopPropagation();
+ var ch;
+ var ctrl = false;
+ var shft = false;
+ var remapped = false;
+ var termKey = term.termKey;
+ var keyRepeat = 0;
+ if (e) {
+ ch = e.which;
+ ctrl = (((e.ctrlKey) && (e.altKey)) || (e.modifiers == 2));
+ shft = ((e.shiftKey) || (e.modifiers == 4));
+ if (e._remapped) {
+ remapped = true;
+ if (window.event) {
+ ctrl = ((ctrl) || ((window.event.ctrlKey) && (!window.event.altKey)));
+ shft = ((shft) || (window.event.shiftKey));
+ }
+ }
+ if (e._repeated) {
+ keyRepeat = 2;
+ } else if (e._repeat) {
+ keyRepeat = 1;
+ }
+ } else if (window.event) {
+ ch = window.event.keyCode;
+ ctrl = ((window.event.ctrlKey) && (!window.event.altKey));
+ shft = (window.event.shiftKey);
+ if (window.event._repeated) {
+ keyRepeat = 2;
+ } else if (window.event._repeat) {
+ keyRepeat = 1;
+ }
+ } else {
+ return true;
+ }
+ if ((ch == '') && (remapped == false)) {
+ if (e == null) e = window.event;
+ if ((e.charCode == 0) && (e.keyCode)) {
+ if (e.DOM_VK_UP) {
+ var dkr = tg.termDomKeyRef;
+ for (var i in dkr) {
+ if ((e[i]) && (e.keyCode == e[i])) {
+ ch = dkr[i];
+ break;
+ }
+ }
+ } else {
+ if (e.keyCode == 28) ch = termKey.LEFT
+ else if (e.keyCode == 29) ch = termKey.RIGHT
+ else if (e.keyCode == 30) ch = termKey.UP
+ else if (e.keyCode == 31) ch = termKey.DOWN
+ else if (e.keyCode == 37) ch = termKey.LEFT
+ else if (e.keyCode == 39) ch = termKey.RIGHT
+ else if (e.keyCode == 38) ch = termKey.UP
+ else if (e.keyCode == 40) ch = termKey.DOWN
+ else if (e.keyCode == 9) ch = termKey.TAB;
+ }
+ }
+ }
+ if ((ch >= 0xE000) && (ch <= 0xF8FF)) return;
+ if (keyRepeat) {
+ tg.clearRepeatTimer();
+ tg.keyRepeatTimer = window.setTimeout('Terminal.prototype.globals.doKeyRepeat(' + ch + ')', (keyRepeat == 1) ? tg.keyRepeatDelay1 : tg.keyRepeatDelay2);
+ }
+ if (term.charMode) {
+ term.insert = false;
+ term.inputChar = ch;
+ term.lineBuffer = '';
+ term.handler();
+ if ((ch <= 32) && (window.event)) window.event.cancleBubble = true;
+ return false;
+ }
+ if (!ctrl) {
+ if (ch == termKey.CR) {
+ term.lock = true;
+ term.cursorOff();
+ term.insert = false;
+ if (term.rawMode) {
+ term.lineBuffer = term.lastLine;
+ } else {
+ term.lineBuffer = term._getLine();
+ if ((term.lineBuffer != '') && ((!term.historyUnique) || (term.history.length == 0) || (term.lineBuffer != term.history[term.history.length - 1]))) {
+ term.history[term.history.length] = term.lineBuffer;
+ }
+ term.histPtr = term.history.length;
+ }
+ term.lastLine = '';
+ term.inputChar = 0;
+ term.handler();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if (ch == termKey.ESC && term.conf.closeOnESC) {
+ term.close();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ }
+ if ((ch < 32) && (term.rawMode)) {
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else {
+ if (ch == termKey.LEFT) {
+ term.cursorLeft();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if (ch == termKey.RIGHT) {
+ term.cursorRight();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if (ch == termKey.UP) {
+ term.cursorOff();
+ if (term.histPtr == term.history.length) term.lastLine = term._getLine();
+ term._clearLine();
+ if ((term.history.length) && (term.histPtr >= 0)) {
+ if (term.histPtr > 0) term.histPtr--;
+ term.type(term.history[term.histPtr]);
+ } else if (term.lastLine) term.type(term.lastLine);
+ term.cursorOn();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if (ch == termKey.DOWN) {
+ term.cursorOff();
+ if (term.histPtr == term.history.length) term.lastLine = term._getLine();
+ term._clearLine();
+ if ((term.history.length) && (term.histPtr <= term.history.length)) {
+ if (term.histPtr < term.history.length) term.histPtr++;
+ if (term.histPtr < term.history.length) term.type(term.history[term.histPtr])
+ else if (term.lastLine) term.type(term.lastLine);
+ } else if (term.lastLine) term.type(term.lastLine);
+ term.cursorOn();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if (ch == termKey.BS) {
+ term.backspace();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if (ch == termKey.DEL) {
+ if (term.DELisBS) term.backspace()
+ else term.fwdDelete();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ }
+ }
+ }
+ if (term.rawMode) {
+ if (term.isPrintable(ch)) {
+ term.lastLine += String.fromCharCode(ch);
+ }
+ if ((ch == 32) && (window.event)) window.event.cancleBubble = true
+ else if ((window.opera) && (window.event)) window.event.cancleBubble = true;
+ return false;
+ } else {
+ if ((term.conf.catchCtrlH) && ((ch == termKey.BS) || ((ctrl) && (ch == 72)))) {
+ term.backspace();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if ((term.ctrlHandler) && ((ch < 32) || ((ctrl) && (term.isPrintable(ch, true))))) {
+ if (((ch >= 65) && (ch <= 96)) || (ch == 63)) {
+ if (ch == 63) ch = 31
+ else ch -= 64;
+ }
+ term.inputChar = ch;
+ term.ctrlHandler();
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if ((ctrl) || (!term.isPrintable(ch, true))) {
+ if (window.event) window.event.cancleBubble = true;
+ return false;
+ } else if (term.isPrintable(ch, true)) {
+ if (term.blinkTimer) clearTimeout(term.blinkTimer);
+ if (term.insert) {
+ term.cursorOff();
+ term._scrollRight(term.r, term.c);
+ }
+ term._charOut(ch);
+ term.cursorOn();
+ if ((ch == 32) && (window.event)) window.event.cancleBubble = true
+ else if ((window.opera) && (window.event)) window.event.cancleBubble = true;
+ return false;
+ }
+ }
+ return true;
+ },
+ hasSubDivs: false,
+ hasLayers: false,
+ termStringStart: '',
+ termStringEnd: '',
+ termSpecials: {
+ 0: '&nbsp;',
+ 1: '&nbsp;',
+ 9: '&nbsp;',
+ 32: '&nbsp;',
+ 34: '&quot;',
+ 38: '&amp;',
+ 60: '&lt;',
+ 62: '&gt;',
+ 127: '&loz;',
+ 0x20AC: '&euro;'
+ },
+ termStyles: [1, 2, 4, 8],
+ termStyleMarkup: {
+ 'r': 1,
+ 'u': 2,
+ 'i': 4,
+ 's': 8
+ },
+ termStyleOpen: {
+ 1: '<span class="termReverse">',
+ 2: '<u>',
+ 4: '<i>',
+ 8: '<strike>'
+ },
+ termStyleClose: {
+ 1: '<\/span>',
+ 2: '<\/u>',
+ 4: '<\/i>',
+ 8: '<\/strike>'
+ },
+ assignStyle: function(styleCode, markup, htmlOpen, htmlClose) {
+ var tg = Terminal.prototype.globals;
+ if ((!styleCode) || (isNaN(styleCode))) {
+ if (styleCode >= 256) {
+ alert('termlib.js:\nCould not assign style.\n' + s + ' is not a valid power of 2 between 0 and 256.');
+ return;
+ }
+ }
+ var s = styleCode & 0xff;
+ var matched = false;
+ for (var i = 0; i < 8; i++) {
+ if ((s >>> i) & 1) {
+ if (matched) {
+ alert('termlib.js:\nCould not assign style code.\n' + s + ' is not a power of 2!');
+ return;
+ }
+ matched = true;
+ }
+ }
+ if (!matched) {
+ alert('termlib.js:\nCould not assign style code.\n' + s + ' is not a valid power of 2 between 0 and 256.');
+ return;
+ }
+ markup = String(markup).toLowerCase();
+ if ((markup == 'c') || (markup == 'p')) {
+ alert('termlib.js:\nCould not assign mark up.\n"' + markup + '" is a reserved code.');
+ return;
+ }
+ if (markup.length > 1) {
+ alert('termlib.js:\nCould not assign mark up.\n"' + markup + '" is not a single letter code.');
+ return;
+ }
+ var exists = false;
+ for (var i = 0; i < tg.termStyles.length; i++) {
+ if (tg.termStyles[i] == s) {
+ exists = true;
+ break;
+ }
+ }
+ if (exists) {
+ var m = tg.termStyleMarkup[markup];
+ if ((m) && (m != s)) {
+ alert('termlib.js:\nCould not assign mark up.\n"' + markup + '" is already in use.');
+ return;
+ }
+ } else {
+ if (tg.termStyleMarkup[markup]) {
+ alert('termlib.js:\nCould not assign mark up.\n"' + markup + '" is already in use.');
+ return;
+ }
+ tg.termStyles[tg.termStyles.length] = s;
+ }
+ tg.termStyleMarkup[markup] = s;
+ tg.termStyleOpen[s] = htmlOpen;
+ tg.termStyleClose[s] = htmlClose;
+ },
+ writeElement: function(e, t, d) {
+ if (document.layers) {
+ var doc = (d) ? d : window.document;
+ doc.layers[e].document.open();
+ doc.layers[e].document.write(t);
+ doc.layers[e].document.close();
+ } else if (document.getElementById) {
+ var obj = document.getElementById(e);
+ obj.innerHTML = t;
+ } else if (document.all) {
+ document.all[e].innerHTML = t;
+ }
+ },
+ setElementXY: function(d, x, y) {
+ if (document.layers) {
+ document.layers[d].moveTo(x, y);
+ } else if (document.getElementById) {
+ var obj = document.getElementById(d);
+ obj.style.left = x + 'px';
+ obj.style.top = y + 'px';
+ } else if (document.all) {
+ document.all[d].style.left = x + 'px';
+ document.all[d].style.top = y + 'px';
+ }
+ },
+ setVisible: function(d, v) {
+ if (document.layers) {
+ document.layers[d].visibility = (v) ? 'show' : 'hide';
+ } else if (document.getElementById) {
+ var obj = document.getElementById(d);
+ obj.style.visibility = (v) ? 'visible' : 'hidden';
+ } else if (document.all) {
+ document.all[d].style.visibility = (v) ? 'visible' : 'hidden';
+ }
+ },
+ setDisplay: function(d, v) {
+ if (document.getElementById) {
+ var obj = document.getElementById(d);
+ obj.style.display = v;
+ } else if (document.all) {
+ document.all[d].style.display = v;
+ }
+ },
+ guiElementsReady: function(e, d) {
+ if (document.layers) {
+ var doc = (d) ? d : window.document;
+ return ((doc) && (doc.layers[e])) ? true : false;
+ } else if (document.getElementById) {
+ return (document.getElementById(e)) ? true : false;
+ } else if (document.all) {
+ return (document.all[e]) ? true : false;
+ } else return false;
+ },
+ _termString_makeKeyref: function() {
+ var tg = Terminal.prototype.globals;
+ var termString_keyref = tg.termString_keyref = new Array();
+ var termString_keycoderef = tg.termString_keycoderef = new Array();
+ var hex = new Array('A', 'B', 'C', 'D', 'E', 'F');
+ for (var i = 0; i <= 15; i++) {
+ var high = (i < 10) ? i : hex[i - 10];
+ for (var k = 0; k <= 15; k++) {
+ var low = (k < 10) ? k : hex[k - 10];
+ var cc = i * 16 + k;
+ if (cc >= 32) {
+ var cs = unescape("%" + high + low);
+ termString_keyref[cc] = cs;
+ termString_keycoderef[cs] = cc;
+ }
+ }
+ }
+ },
+ _extendMissingStringMethods: function() {
+ if ((!String.fromCharCode) || (!String.prototype.charCodeAt)) {
+ Terminal.prototype.globals._termString_makeKeyref();
+ }
+ if (!String.fromCharCode) {
+ String.fromCharCode = function(cc) {
+ return (cc != null) ? Terminal.prototype.globals.termString_keyref[cc] : '';
+ };
+ }
+ if (!String.prototype.charCodeAt) {
+ String.prototype.charCodeAt = function(n) {
+ cs = this.charAt(n);
+ return (Terminal.prototype.globals.termString_keycoderef[cs]) ? Terminal.prototype.globals.termString_keycoderef[cs] : 0;
+ };
+ }
+ }
+ }
+}
+Terminal.prototype.globals._initGlobals();
+var TerminalDefaults = Terminal.prototype.Defaults;
+var termDefaultHandler = Terminal.prototype.defaultHandler;
+var TermGlobals = Terminal.prototype.globals;
+var termKey = Terminal.prototype.globals.termKey;
+var termDomKeyRef = Terminal.prototype.globals.termDomKeyRef;
+var parserWhiteSpace = {
+ ' ': true,
+ '\t': true
+}
+var parserQuoteChars = {
+ '"': true,
+ "'": true,
+ '`': true
+};
+var parserSingleEscapes = {
+ '\\': true
+};
+var parserOptionChars = {
+ '-': true
+}
+var parserEscapeExpressions = {
+ '%': parserHexExpression
+}
+
+function parserHexExpression(termref, pointer, echar, quotelevel) {
+ if (termref.lineBuffer.length > pointer + 2) {
+ var hi = termref.lineBuffer.charAt(pointer + 1);
+ var lo = termref.lineBuffer.charAt(pointer + 2);
+ lo = lo.toUpperCase();
+ hi = hi.toUpperCase();
+ if ((((hi >= '0') && (hi <= '9')) || ((hi >= 'A') && ((hi <= 'F')))) && (((lo >= '0') && (lo <= '9')) || ((lo >= 'A') && ((lo <= 'F'))))) {
+ parserEscExprStrip(termref, pointer + 1, pointer + 3);
+ return String.fromCharCode(parseInt(hi + lo, 16));
+ }
+ }
+ return echar;
+}
+
+function parserEscExprStrip(termref, from, to) {
+ termref.lineBuffer = termref.lineBuffer.substring(0, from) +
+ termref.lineBuffer.substring(to);
+}
+
+function parserGetopt(termref, optsstring) {
+ var opts = {
+ 'illegals': []
+ };
+ while ((termref.argc < termref.argv.length) && (termref.argQL[termref.argc] == '')) {
+ var a = termref.argv[termref.argc];
+ if ((a.length > 0) && (parserOptionChars[a.charAt(0)])) {
+ var i = 1;
+ while (i < a.length) {
+ var c = a.charAt(i);
+ var v = '';
+ while (i < a.length - 1) {
+ var nc = a.charAt(i + 1);
+ if ((nc == '.') || ((nc >= '0') && (nc <= '9'))) {
+ v += nc;
+ i++;
+ } else break;
+ }
+ if (optsstring.indexOf(c) >= 0) {
+ opts[c] = (v == '') ? {
+ value: -1
+ } : (isNaN(v)) ? {
+ value: 0
+ } : {
+ value: parseFloat(v)
+ };
+ } else {
+ opts.illegals[opts.illegals.length] = c;
+ }
+ i++;
+ }
+ termref.argc++;
+ } else break;
+ }
+ return opts;
+}
+
+function parseLine(termref) {
+ var argv = [''];
+ var argQL = [''];
+ var argc = 0;
+ var escape = false;
+ for (var i = 0; i < termref.lineBuffer.length; i++) {
+ var ch = termref.lineBuffer.charAt(i);
+ if (escape) {
+ argv[argc] += ch;
+ escape = false;
+ } else if (parserEscapeExpressions[ch]) {
+ var v = parserEscapeExpressions[ch](termref, i, ch, argQL[argc]);
+ if (typeof v != 'undefined') argv[argc] += v;
+ } else if (parserQuoteChars[ch]) {
+ if (argQL[argc]) {
+ if (argQL[argc] == ch) {
+ argc++;
+ argv[argc] = argQL[argc] = '';
+ } else {
+ argv[argc] += ch;
+ }
+ } else {
+ if (argv[argc] != '') {
+ argc++;
+ argv[argc] = '';
+ argQL[argc] = ch;
+ } else {
+ argQL[argc] = ch;
+ }
+ }
+ } else if (parserWhiteSpace[ch]) {
+ if (argQL[argc]) {
+ argv[argc] += ch;
+ } else if (argv[argc] != '') {
+ argc++;
+ argv[argc] = argQL[argc] = '';
+ }
+ } else if (parserSingleEscapes[ch]) {
+ escape = true;
+ } else {
+ argv[argc] += ch;
+ }
+ }
+ if ((argv[argc] == '') && (!argQL[argc])) {
+ argv.length--;
+ argQL.length--;
+ }
+ termref.argv = argv;
+ termref.argQL = argQL;
+ termref.argc = 0;
+}
+
+var helpPage = ['%c(@beige)This is a Unix-like virtual shell command line interface.'];
+var infoPage = ['%c(@beige)This console is implemented with the javascript terminal library termlib.js.'];
+var asciinumber = [' .XEEEEb ,:LHL :LEEEEEG .CNEEEEE8 bMNj NHKKEEEEEX 1LEEE1 KEEEEEEEKNMHH 8EEEEEL. cEEEEEO ', ' MEEEUXEEE8 jNEEEEE EEEEHMEEEEU EEEELLEEEEc NEEEU 7EEEEEEEEEK :EEEEEEN, EEEEEEEEEEEEE OEEEGC8EEEM 1EEELOLEEE3 ', ' NEE. OEEC EY" MEE OC LEEc :" EEE EEGEE3 8EN MEEM. :EE. 1EEj :EEO 1EE3 DEEc ', ' ,EEj EEE HEE EEE cEE: EEU EEJ NEC EEE EEJ EEE EEE EEN KEE ', ' HEE jEE1 NEE EEE EEE EEM EEJ EE LEE .. EEK DEEj :EE7 ,EE1 jEE ', ' EEH EEZ KEE :EE1 .::jZEEG EEU EEJ .EEEEEENC EE77EEEEEEL NEE UEENj bEE7 .EEX :EE.', '.EEZ EEM KEE EEK EEEEEEC .EEc EEC :X3DGMEEEEU 3EEEED.".GEEE. CEE. EEEEEEE EEEj :EEE ', ' EEZ EEM KEE :EEK "jNEEZ :EE EE7 MEEU LEEb EEE .EE8 DEEL:.8EEEM NEEENMEEEHEE ', ' EEN .EEG KEE bEEG 7EEM jEEN738ODDEEM3b EEE MEE 8EE, EEE EEE ,EEE .bEEEEC XEE ', ' LEE 3EE: KEE .EEE, EEE LEEEEEEEEEEEEEE XEE 8EE cEE: NEE 7EE1 jEE1 :EE: ', ' .EEc EEE KEE bEED EEE EE1 EEE EEX EEE 3EE: cEEc 7EEj CEEG ', ' MEE7 NEE. EEE jEEK C EEE1 EEC j :EEE CEEG LEEj .EEU EEE: .EEE 1EEEJ ', ' bEEEEEEEE. EEE NEEEEEEEEEEEE bEEEEEEEEEE7 EEd JEEEEEEEEEN jEEEEEEEEE7 .EEE KEEEEHEEEEL 8EEEEEEX ', ' DEEEL7 CGD 3GD3DOGGGGGUX :DHEEEN8. bUd 7GNEEEMc 7LEEEX: 1XG JHEEEM1 COLIN" '];
+var asciinumber_s = ['.oPYo. .o .oPYo. .oPYo. .8 oooooo .pPYo. oooooo .PY. .oPYo. ', '8 o8 8 `8 `8 d"8 8 8 .o" 8 8 8" `8 ', '8 P 8 8 oP" .oP" d" 8 8pPYo. 8oPYo. .o" .oPYo. 8. .8 ', '8 d 8 8 .oP" `b. Pooooo `8 8" `8 .o" 8" `8 `YooP8 ', '8o 8 8 8" :8 8 .P 8. .P .o" 8. .P .P ', '`YooP" o8o 8ooooo `YooP" 8 `YooP" `YooP" o" `YooP" `YooP" '];
+var asciiddot = [' ', ' ', ' ', ' @@ ', ' @@ ', ' ', ' ', ' ', ' ', ' ', ' @@ ', ' @@ ', ' ', ' ', ' '];
+var asciiddot_s = [' ', 'x ', ' ', ' ', 'x ', ' '];
+var asciin = asciinumber;
+var asciid = asciiddot;
+var bs = ['%c(@white)A problem has been detected and windows has been shut down to prevent', 'damage to your computer.', '', 'PAGE_FAULT_BECAUSE_OF_DUMB_USER', '', 'Suggestions: Restart computer, if problems continue, install Linux.', '', 'Technical Information:', '', '***STOP: 0x00000050 (0xBD32E7E4, 0x00000011, 0x8B5F87F4,0x00000012)', '', 'Physical memory was dumped.'];
+var safari = false;
+var fortuneid = 1;
+var shortm = ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+var path = "/home/www";
+var files_root_n = ['bin', 'etc', 'home', 'tmp', 'sbin', 'usr', 'var'];
+var files_root_s = [' 512', ' 512', ' 1024', ' 512', ' 512', ' 512', ' 512'];
+var files_root_t = ['Jan 23 00:13', 'Feb 2 14:36', 'Jan 23 00:13', 'Nov 10 2007', 'Nov 10 2007', 'Nov 10 2007', 'Nov 10 2007'];
+var files_root = [files_root_n, files_root_s, files_root_t, '%c(@lightgrey)drwxr-x--- 1 root wheel'];
+var files_etc_n = ['passwd', 'group', 'rc.conf', 'master.passwd', 'hosts', 'crontab'];
+var files_etc_s = [' 766', ' 266', ' 3061', ' 3960', ' 766', ' 1852'];
+var files_etc_t = ['Jan 23 00:13', 'Jan 23 00:13', 'Feb 2 14:36', 'Jan 23 00:13', 'Nov 10 2007', 'Nov 26 17:28'];
+var files_etc = [files_etc_n, files_etc_s, files_etc_t, '%c(@lightgrey)-rw-r----- 1 root wheel'];
+var files_home_n = ['www'];
+var files_home_s = [' 766'];
+var files_home_t = ['Nov 10 2007'];
+var files_home = [files_home_n, files_home_s, files_home_t, '%c(@lightgrey)drwxr-xr-x 1 root wheel'];
+var files_tmp_n = ['test'];
+var files_tmp_s = [' 512'];
+var files_tmp_t = ['Jun 11 2007'];
+var files_tmp = [files_tmp_n, files_tmp_s, files_tmp_t, '%c(@lightgrey)drwxrwx--- 1 root wheel'];
+var files_var_n = ['log'];
+var files_var_s = [' 512'];
+var files_var_t = ['Jun 11 2007'];
+var files_var = [files_var_n, files_var_s, files_var_t, '%c(@lightgrey)drwxrwx--- 1 root wheel'];
+var files_usr_n = ['share'];
+var files_usr_s = [' 512'];
+var files_usr_t = ['Oct 21 2006'];
+var files_usr = [files_usr_n, files_usr_s, files_usr_t, '%c(@lightgrey)drwxrwxr-x 1 root wheel'];
+var files_share_n = ['man'];
+var files_share_s = [' 512'];
+var files_share_t = ['Oct 21 2006'];
+var files_share = [files_share_n, files_share_s, files_share_t, '%c(@lightgrey)drwxrwxr-x 1 root wheel'];
+var files_man_n = ['echo', 'cal', 'clock', 'ed', 'hostname', 'ls', 'matrix', 'redim', 'reload', 'reset', 'ssh', 'vi', 'weather', 'whereami'];
+var files_man_s = [' 252', ' 287', ' 352', ' 1173', ' 281', ' 361', ' 292', ' 291', ' 451', ' 353', ' 198', ' 358', ' 232', ' 216', ' 112', ' 3412'];
+var files_man_t = ['Nov 21 2007', 'Jan 31 2008', 'Nov 21 2007', 'Nov 21 2007', 'Nov 21 2007', 'Nov 21 2007', 'Nov 21 2007', 'Jul 10 2008', 'Nov 21 2007', 'Nov 21 2007', 'Apr 17 2008', 'Feb 01 2008', 'Feb 11 2008', 'Apr 02 2008', 'Nov 21 2007', 'Mar 21 2008'];
+var files_man = [files_man_n, files_man_s, files_man_t, '%c(@lightgrey)-rw-rw-r-- 1 root wheel'];
+var files_bin_n = ['apropos', 'browse', 'browser', 'cal', 'cat', 'chat', 'clear', 'clock', 'cd', 'date', 'df', 'echo', 'ed', 'fortune', 'history', 'login', 'hostname', 'help', 'id', 'info', 'll', 'logout', 'ls', 'man', 'matrix', 'more', 'ping', 'ps', 'pwd', 'pr', 'reload', 'snake', 'ssh', 'sudo', 'redim', 'reset', 'top', 'uname', 'whereami', 'rm', 'time', 'uptime', 'vi', 'who', 'weather', 'whoami'];
+var files_bin_s = [' 1933', ' 3061', ' 3960', ' 766', ' 1150', ' 2170', ' 1176', ' 1834', ' 1650', ' 81933', ' 695', ' 1507', ' 1327', ' 1127', ' 1852', ' 1140', ' 1933', ' 256', ' 1678', ' 32648', ' 5150', ' 1232', ' 5150', ' 593', ' 3595', ' 1698', ' 2668', ' 1668', ' 3855', ' 7159', ' 1353', ' 3695', ' 1435', ' 1135', ' 1156', ' 815', ' 193', ' 2565', ' 5466', ' 9331', ' 1357', ' 150', ' 19364', ' 8364', ' 384', ' 1744'];
+var files_bin_t = ['Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 22 2006', 'Oct 22 2006', 'Oct 21 2006', 'Oct 21 2006', 'Apr 11 2008', 'Jul 11 2008', 'Oct 21 2006', 'Oct 21 2006', 'Feb 10 2008', 'Feb 10 2008', 'Oct 21 2006', 'Jun 11 2007', 'Jun 11 2007', 'Apr 11 2008', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Jan 28 2008', 'Jan 25 2008', 'Oct 21 2006', 'Oct 21 2006', 'Jun 11 2007', 'Oct 21 2006', 'Apr 5 2008', 'Oct 21 2006', 'Jan 21 2008', 'Oct 21 2006', 'Nov 10 2007', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Apr 4 02:46', 'Jan 23 00:13', 'Jan 23 00:13', 'Feb 10 01:24'];
+var files_bin = [files_bin_n, files_bin_s, files_bin_t, '%c(@lightgrey)-rwxr-x--x 1 root wheel'];
+var files_sbin_n = ['sysctl', 'netstat', 'browser', 'passwd', 'ifconfig', 'route', 'mount', 'reboot', 'halt', 'shutdown', 'su'];
+var files_sbin_s = [' 1933', ' 3061', ' 3960', ' 766', ' 1150', ' 1350', ' 1834', ' 1650', ' 933', ' 695', ' 1507'];
+var files_sbin_t = ['Feb 10 01:23', 'Feb 10 01:24', 'Oct 21 2006', 'Oct 24 2006', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006', 'Jun 11 2007', 'Oct 21 2006', 'Oct 21 2006', 'Oct 21 2006'];
+var files_sbin = [files_sbin_n, files_sbin_s, files_sbin_t, '%c(@lightgrey)-rwxr-x--- 1 root wheel'];
+var files_www_n = ['about.txt', 'bugs.txt', 'cb.txt', 'exploring.gif', 'favicon.ico', 'index.html', 'shell.js', 'sitemap.xml', 'termlib.js', 'termlib_invaders.js', 'termlib_parser.js', 'unixtoolbox.book.pdf', 'unixtoolbox.book2.pdf', 'unixtoolbox.pdf', 'unixtoolbox.txt', '%+nunixtoolbox.xhtml%-n'];
+var files_www_s = [' 1045', ' 954', ' 4033', ' 98166', ' 1150', ' 1933', ' 25695', ' 766', ' 64720', ' 21371', ' 6036', '272458', '271664', '345472', '124113', '191701'];
+var files_www_t = ['Feb 15 01:31', 'Apr 18 00:31', 'Feb 11 02:06', 'Jul 23 2004', 'Jan 31 15:17', 'Feb 10 16:53', 'Feb 5 00:52', 'Feb 10 01:13', 'Feb 10 01:13', 'Feb 10 02:14', 'Feb 10 02:14', 'Apr 09 02:14', 'Apr 09 02:14', 'Apr 09 04:20', 'Apr 09 01:47', 'Apr 09 02:50'];
+var files_www = [files_www_n, files_www_s, files_www_t, '%c(@lightgrey)-rw-r----- 1 colin www'];
+var tree = ['/', '/etc', '/tmp', '/bin', '/home', '/home/www', '/sbin', '/usr', '/usr/share', '/usr/share/man', '/var'];
+var tree_files = [files_root, files_etc, files_tmp, files_bin, files_home, files_www, files_sbin, files_usr, files_share, files_man, files_var];
+var remote_files = ['unixtoolbox.xhtml', 'unixtoolbox.txt', 'index.html', 'shell.js', 'termlib.js', 'termlib_parser.js', 'termlib_invaders.js'];
+var binary_files = ['unixtoolbox.pdf', 'unixtoolbox.book.pdf', 'unixtoolbox.book2.pdf', 'exploring.gif', 'favicon.ico'];
+var filesContent = [];
+filesContent["/boot/shutdown"] = ['%c(@lightgrey)Waiting (max 60 seconds) for system process \'crypto\' to stop...done', '%c(@lightgrey)Waiting (max 60 seconds) for system process \'vnlru\' to stop...done', '%c(@lightgrey)Waiting (max 60 seconds) for system process \'bufdaemon\' to stop...done', '%c(@lightgrey)Waiting (max 60 seconds) for system process \'syncer\' to stop...', '%c(@lightgrey)Syncing disks, vnodes remaining...5 6 7 3 2 1 1 1 0 0 0 done', '', '', '', '%c(@lightgrey)All buffers synced.', '%c(@lightgrey)Uptime: 14d13h29m45s', '', '%c(@lightgrey)Rebooting...%n', '', '', ''];
+filesContent["/boot/kernel"] = ['%c(@lightgrey)localhost ROM BIOS Version 1.34 A12', '%c(@lightgrey)Copyright 2007-2008 Colin Barschel All Rights Reserved', '', '%c(@lightgrey)FreeBSD 7.1-STABLE #3: Sat Feb 16 16:14:11 CET 2009', '%c(@lightgrey) sysad@localhost:/usr/obj/usr/src/sys/CB', '', '%c(@lightgrey)Timecounter "i8254" frequency 1193182 Hz quality 0', '%c(@lightgrey)CPU: Dual Core AMD Opteron(tm) Processor 270 (2010.31-MHz K8-class CPU)', '%c(@lightgrey) Origin = "AuthenticAMD" Id = 0x20f12 Stepping = 2', '%c(@lightgrey) Features=0x178bfbff<FPU,VME,DE,PSE,TSC,MSR,PAE,MCE,CX8,APIC,SEP,MTRR,PGE,MCA,CMOV,PAT,PSE36,CLFLUSH,MMX,FXSR,SSE,SSE2,HTT>', '%c(@lightgrey) Features2=0x1<SSE3>', '%c(@lightgrey) AMD Features=0xe2500800<SYSCALL,NX,MMX+,FFXSR,LM,3DNow!+,3DNow!>', '%c(@lightgrey) AMD Features2=0x3<LAHF,CMP>', '%c(@lightgrey) Cores per package: 2', '%c(@lightgrey)usable memory = 2139738112 (2040 MB)', '%c(@lightgrey)avail memory = 2065133568 (1969 MB)', '', '%c(@lightgrey)Detecting IDE drives ... IDE Flash Disk', '', '%c(@lightgrey)acpi0: <Nvidia AWRDACPI> on motherboard', '%c(@lightgrey)acpi_timer0: <24-bit timer at 3.579545MHz> port 0x808-0x80b on acpi0', '%c(@lightgrey)ata0: <ATA channel 0> on atapci0', '%c(@lightgrey)ata1: <ATA channel 1> on atapci0', '%c(@lightgrey)usb0: <SiS 5571 USB controller> on ohci0', '%c(@lightgrey)usb0: USB revision 2.0', '%c(@lightgrey)uhub0: SiS OHCI root hub, class 9/0, rev 1.00/1.00, addr 1', '%c(@lightgrey)cpu0: <ACPI CPU> on acpi0', '%c(@lightgrey)cpu1: <ACPI CPU> on acpi0', '%c(@lightgrey)bge0: <Broadcom NetXtreme Gigabit Ethernet Controller, ASIC rev. 0x3003> mem 0xfe9e0000-0xfe9effff irq 18 at device 6.0 on pci1', '%c(@lightgrey)Looks convincing, doesn\'t it?', '%c(@lightgrey)atapci0: <SiS 962/963 UDMA133 controller> port 0x1f0-0x1f7,0x3f6,0x170-0x177at device 2.5 on pci0%n', '%c(@lightgrey)Timecounters tick every 1.000 msec', '', '%c(@lightgrey)ipfw2 (+ipv6) initialized, divert enabled, rule-based forwarding disabled, default to deny, logging enabled', '%c(@lightgrey)Trying to mount root from ufs:/dev/ad0a', '', '%c(@lightgrey)/bin/sh: accessing tty1', '%c(@lightgrey)Starting external programs: ssh apache2 mxvpn sendmail', '', 'ready', ' '];
+filesContent["/etc/passwd"] = ['%c(@lightgrey)# $FreeBSD: src/etc/master.passwd,v 1.40 2005/06/06 20:19:56 brooks Exp $', '#', 'root:*:0:0:Charlie &:/root:/bin/csh', 'toor:*:0:0:Bourne-again Superuser:/root:', 'mailnull:*:26:26:Sendmail Default User:/var/spool/mqueue:/usr/sbin/nologin', 'www:*:80:80:World Wide Web Owner:/nonexistent:/usr/sbin/nologin', 'sysa:*:1001:0:System Administrator:/home/sysadmin:/bin/tcsh'];
+filesContent["/etc/group"] = ['%c(@lightgrey)# $FreeBSD: src/etc/group,v 1.32.2.1 2006/03/06 22:23:10 rwatson Exp $', '#', 'wheel:*:0:root,sysa', 'mailnull:*:26:milter', 'www:*:80:', 'sysa:*:1001:'];
+filesContent["/etc/rc.conf"] = ['%c(@lightgrey)hostname="localhost"', 'firewall_enable="YES" # Set to YES to enable firewall functionality', 'firewall_type="web" # Firewall type (see /etc/rc.firewall)', 'ifconfig_rl0="inet 78.31.70.238 netmask 255.255.255.0"', 'defaultrouter="78.31.70.1"', 'sshd_enable="YES" # Enable sshd', 'sendmail_enable="YES" # Run the sendmail inbound daemon (YES/NO).', 'sendmail_flags="-L sm-mta -bd -q30m"', 'apache22_enable="YES" # start Apache httpd', 'apache22ssl_enable="YES"', 'apache22_http_accept_enable="YES" # Use kernel accf_data and accf_http modules'];
+filesContent["/etc/hosts"] = ['%c(@lightgrey)# In the presence of the domain name service or NIS, this file may', '# not be consulted at all; see /etc/nsswitch.conf for the resolution order.', '#', '::1 localhost localhost.localhost', '127.0.0.1 localhost localhost.localhost'];
+filesContent["/etc/crontab"] = ['%c(@lightgrey)# $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $', '#minute hour mday month wday who command', '# Save some entropy so that /dev/random can re-seed on boot.', '*/11 * * * * operator /usr/libexec/save-entropy', '# Rotate log files every hour, if necessary.', '0 * * * * root newsyslog', '# Perform daily/weekly/monthly maintenance.', '1 3 */2 * * root periodic daily', '15 4 */2 * 6 root periodic weekly', '30 5 1 */2 * root periodic monthly'];
+filesContent["/usr/share/man/vi"] = ['%c(@lightcyan)VI localhost General Commands Manual VI', '', 'NAME', ' Vi -- a screen oriented text editor.', '', 'DESCRIPTION', ' Vi is a modal editor and is either in insert mode or err... Who doesn\'t ', ' know vi? This implementation is very thin and does not support paging. That', ' is only the visible page can be edited. The following commands should work:', '', ' <ESC> to enter command mode', ' :q<Enter> to exit', ' :w<Enter> to save', ' :w filename to save to "filename"', ' :e filename to open "filename"', ' :q!<Enter> to exit without saving', ' D to delete rest of line', ' dd to delete current line', ' x to delete current char', ' i to enter edit mode ', ' UP RIGHT DOWN LEFT to move the cursor', ' or h left j down k up l right', '', ' %c(@chartreuse)On Safari browsers use <TAB> instead of <ESC>!!%c(@lightcyan)'];
+filesContent["/usr/share/man/ssh"] = ['%c(@lightcyan)SSH localhost General Commands Manual SSH', '', 'NAME', ' ssh -- Mindterm SSH client (remote login program)', '', 'SYNOPSIS', ' ssh [-L port:host:hostport] [-p port] [user@]hostname', '', 'DESCRIPTION', ' The ssh command will start the Appgate java applet "mindterm".', ' The applet is self-signed and can thus be used to connect to any server', ' (as you don\'t have an account on localhost...)', ' and also allows to build tunnels. This is the compiled version from', ' www.appgate.com with the logo removed.', ' %c(@chartreuse)There is no connection between this client and the localhost server.', '', ' Use the top right "X" to close the ssh client%c(@lightcyan)', '', 'EXAMPLES', ' ssh hostname', ' ssh -p 123 user@hostname', ' ssh -L 3128:127.0.0.1:80 -p 1234 user@hostname'];
+filesContent["/usr/share/man/echo"] = ['%c(@lightcyan)ECHO localhost General Commands Manual ECHO', '', 'NAME', ' echo -- write arguments to the standard output', '', 'DESCRIPTION', ' The echo utility writes any specified operands, separated by single blank', ' (\' \') characters and followed by a newline (\\n) character, to the stan-', ' dard output.', ' the > redirect can be used to create a file. For example the command', ' %c(@chartreuse)echo Hello world! > hello.txt%c(@lightcyan)', ' will create the file hello.txt'];
+filesContent["/usr/share/man/hostname"] = ['%c(@lightcyan)HOSTNAME localhost General Commands Manual HOSTNAME', '', 'NAME', ' hostname -- print name of current host system', '', 'SYNOPSIS', ' hostname [-fsi]', '', 'DESCRIPTION', ' The hostname utility prints the name of the current host.', ' This script uses the hostname variable in /etc/rc.conf.', '', ' Options:', '', ' -f Include domain information in the printed name. This is the', ' default behavior.', '', ' -s Trim off any domain information from the printed name.', '', ' -i Show the corresponding host IP address.'];
+filesContent["/usr/share/man/reload"] = ['%c(@lightcyan)RELOAD localhost General Commands Manual RELOAD', '', 'NAME', ' reload -- reload the terminal as a new http request', '', 'DESCRIPTION', ' This command will reload the terminal with a new http GET request from the', ' browser. This will reinitialize the shell and all variables and has the same ', ' effect as the browser reload button. A reload will also recalculate the shell', ' size.', '', 'SEE ALSO', ' reset, redim'];
+filesContent["/usr/share/man/reset"] = ['%c(@lightcyan)RESET localhost General Commands Manual RESET', '', 'NAME', ' reset -- reset the terminal to the initial state', '', 'DESCRIPTION', ' This command will reset the terminal to its initial state but will not reload', ' the variables. The created file are not deleted either. Delete them all with', ' rm * in the home directory.', '', 'SEE ALSO', ' reload'];
+filesContent["/usr/share/man/redim"] = ['%c(@lightcyan)REDIM localhost General Commands Manual REDIM', '', 'NAME', ' redim -- calculates and resizes the shell to it\'s maximal size.', '', 'DESCRIPTION', ' This command resizes the shell to fit the visible browser area, it can be used', ' when the browser size has changed. The argument <-s> will only display the sizes', ' but will not change anything.', '', ' The following options are available:', '', ' -s only display the window and shell sizes without changing anything', '', 'SEE ALSO', ' reload'];
+filesContent["/usr/share/man/snake"] = ['%c(@lightcyan)SNAKE localhost General Commands Manual SNAKE', '', 'NAME', ' snake -- a variation of the classical snake game.', '', 'DESCRIPTION', ' The snake must be steered to get food (the numbers randomly displayed)', ' and avoid crashing on rocks or wall or itself. There is also an autopilot,', ' but it is not to be trusted.', '', ' The following options are available:', '', ' -s1 for speed: -s1 = slow; -s3 = fast', ' -f1 for food: -f1 = less; -f3 = more', ' -o1 for obstacles: -o1 = less; -o3 = more rocks', ' -a toggle the autopilot on or off. Status is displayed on the status line', ' -r toggle auto-restart on or off. Status is displayed on the status line', '', 'EXAMPLES', '', ' snake -f3 -o3 -a -r max food and rocks with autopilot and auto-restart', '', 'SEE ALSO', ' invaders'];
+filesContent["/usr/share/man/invaders"] = ['%c(@lightcyan)INVADERS localhost General Commands Manual INVADERS', '', 'NAME', ' invaders -- the classical invaders game, courtesy of Norbert Landsteiner.', '', 'DESCRIPTION', ' The invaders must be shot down before they reach earth. The ship must also', ' avoid the enemy fire.', '', ' On a large screen the game might be too stretched and thus too easy to', ' win... Use option -s to reduce the available game area to the classical', ' 80x25 characters.', '', ' -s start the game with a smaller area of 80x25 characters', '', 'SEE ALSO', ' snake'];
+filesContent["/usr/share/man/ls"] = ['%c(@lightcyan)LS localhost General Commands Manual LS', '', 'NAME', ' ls -- list directory contents', '', 'SYNOPSIS', ' ls [-la] [directory]', '', 'DESCRIPTION', ' For each operand that names a directory, ls displays the names of files', ' contained within that directory, as well as any requested, associated', ' information.', ' If no operands are given, the contents of the current directory are dis-', ' played.', '', ' The following options are available:', '', ' -l List files in the long format with date and permission information', '', ' -a Display also hidden files and folders'];
+filesContent["/usr/share/man/matrix"] = ['%c(@lightcyan)MATRIX localhost General Commands Manual MATRIX', '', 'NAME', ' matrix -- a matrix like screen saver animation', '', 'SYNOPSIS', ' matrix [-s]', '', 'DESCRIPTION', ' This animation displays falling random letters in a gree gradient. This is', ' quite heavy on the browser rendering engine and thus uses a lot of CPU.', '', ' The following options are available:', '', ' -s Start with an empty page and fill it with time. Default starts with a newly', ' generated screen.', '', ' key <q> or <ESC> to quit the animation', '', ' key <space> to pause or play the animation', '', ' any other key will add an iteration'];
+filesContent["/usr/share/man/cal"] = ['%c(@lightcyan)CAL localhost General Commands Manual CAL', '', 'NAME', ' cal -- a simple month calender', '', 'SYNOPSIS', ' cal [n] (n = 1-12)', '', 'DESCRIPTION', ' Display a calender of the current month or an other month given as option.', '', ' The following options are available:', '', ' n Selects an other month of the year. For example:', ' Jan = 1, Jan next year = 13, Dec last year = 0'];
+filesContent["/usr/share/man/clock"] = ['%c(@lightcyan)CLOCK localhost General Commands Manual CLOCK', '', 'NAME', ' clock -- display a large clock or stopwatch', '', 'SYNOPSIS', ' clock [-t -s]', '', 'DESCRIPTION', ' With no option the command clock displays a large clock in full screen', ' mode and international format, like 21:45:04. It is also possible to display', ' a stopwatch. Use any key besides <space> and <r> to quit', '', ' The following options are available:', '', ' -t start in stopwatch mode', '', ' -s use smaller numbers. This is automatic if the terminal is too small', '', ' <space key> pause the display, the time is still ticking...', '', ' <r key> reset the stopwatch and start again.'];
+filesContent["/usr/share/man/ed"] = ['%c(@lightgrey)This text is straight from http://www.gnu.org/fun/jokes/ed.msg.html', '%c(@lightcyan)When I log into my Xenix system with my 110 baud teletype, both vi', '*and* Emacs are just too damn slow. They print useless messages like,', '\'C-h for help\' and \'"foo" File is read only\'. So I use the editor', 'that doesn\'t waste my VALUABLE time.', '', 'Ed, man! !man ed', '', 'ED(1) Unix Programmer\'s Manual ED(1)', '', 'NAME', ' ed - text editor', '', 'SYNOPSIS', ' ed [ - ] [ -x ] [ name ]', 'DESCRIPTION', ' Ed is the standard text editor.', '---', '', 'Computer Scientists love ed, not just because it comes first', 'alphabetically, but because it\'s the standard. Everyone else loves ed', 'because it\'s ED!', '', '"Ed is the standard text editor."', '', 'And ed doesn\'t waste space on my Timex Sinclair. Just look:', '', '-rwxr-xr-x 1 root 24 Oct 29 1929 /bin/ed', '-rwxr-xr-t 4 root 1310720 Jan 1 1970 /usr/ucb/vi', '-rwxr-xr-x 1 root 5.89824e37 Oct 22 1990 /usr/bin/emacs', '', 'Of course, on the system *I* administrate, vi is symlinked to ed.', 'Emacs has been replaced by a shell script which 1) Generates a syslog', 'message at level LOG_EMERG; 2) reduces the user\'s disk quota by 100K;', 'and 3) RUNS ED!!!!!!', '', '"Ed is the standard text editor."', '', 'Let\'s look at a typical novice\'s session with the mighty ed:', '', 'golem$ ed', '', '?', 'help', '?', '?', '?', 'quit', '?', 'exit', '?', 'bye', '?', 'hello?', '?', 'eat flaming death', '?', '^C', '?', '^C', '?', '^D', '?', '', '---', 'Note the consistent user interface and error reportage. Ed is', 'generous enough to flag errors, yet prudent enough not to overwhelm', 'the novice with verbosity.', '', '"Ed is the standard text editor."', '', 'Ed, the greatest WYGIWYG editor of all.', '', 'ED IS THE TRUE PATH TO NIRVANA! ED HAS BEEN THE CHOICE OF EDUCATED', 'AND IGNORANT ALIKE FOR CENTURIES! ED WILL NOT CORRUPT YOUR PRECIOUS', 'BODILY FLUIDS!! ED IS THE STANDARD TEXT EDITOR! ED MAKES THE SUN', 'SHINE AND THE BIRDS SING AND THE GRASS GREEN!!', '', 'When I use an editor, I don\'t want eight extra KILOBYTES of worthless', 'help screens and cursor positioning code! I just want an EDitor!!', 'Not a "viitor". Not a "emacsitor". Those aren\'t even WORDS!!!! ED!', 'ED! ED IS THE STANDARD!!!', '', 'TEXT EDITOR.', '', 'When IBM, in its ever-present omnipotence, needed to base their', '"edlin" on a Unix standard, did they mimic vi? No. Emacs? Surely', 'you jest. They chose the most karmic editor of all. The standard.', '', 'Ed is for those who can *remember* what they are working on. If you', 'are an idiot, you should use Emacs. If you are an Emacs, you should', 'not be vi. If you use ED, you are on THE PATH TO REDEMPTION. THE', 'SO-CALLED "VISUAL" EDITORS HAVE BEEN PLACED HERE BY ED TO TEMPT THE', 'FAITHLESS. DO NOT GIVE IN!!! THE MIGHTY ED HAS SPOKEN!!!', '', '?'];
+var pslong = ['%c(@lightgrey)USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND'];
+var globalterm;
+var fetcherror = "";
+var vgeoip_country_code;
+var vgeoip_country_name;
+var vgeoip_city;
+var vgeoip_region;
+var vgeoip_latitude;
+var vgeoip_longitude;
+
+function incrementLoaded(t) {
+ var loaded = readCookie("loaded");
+ loaded++;
+ if (loaded > 4) {
+ t.newLine();
+ carriageReturn();
+ loaded = 2;
+ }
+ createCookie("loaded", loaded, 0, 5);
+}
+
+function carriageReturn() {
+ Terminal.prototype.globals.keyHandler({
+ which: globalterm.termKey.CR,
+ _remapped: true
+ });
+}
+
+function pressKey(ch) {
+ Terminal.prototype.globals.keyHandler({
+ which: ch,
+ _remapped: true
+ });
+}
+
+function createCookie(name, value, days, min) {
+ var expires;
+ var date = new Date();
+ if (days) {
+ date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
+ expires = "; expires=" + date.toGMTString();
+ } else {
+ expires = "";
+ }
+ if (min) {
+ date.setTime(date.getTime() + (min * 60 * 1000));
+ expires = "; expires=" + date.toGMTString();
+ }
+ document.cookie = name + "=" + value + expires + "; path=/";
+}
+
+function readCookie(name) {
+ var nameEQ = name + "=";
+ var ca = document.cookie.split(';');
+ for (var i = 0; i < ca.length; i++) {
+ var c = ca[i];
+ while (c.charAt(0) == ' ') {
+ c = c.substring(1, c.length);
+ }
+ if (c.indexOf(nameEQ) === 0) {
+ return c.substring(nameEQ.length, c.length);
+ }
+ }
+ return "";
+}
+
+function readAllCookies() {
+ var nameEQ = "=";
+ var all = [];
+ var ca = document.cookie.split(';');
+ for (var i = 0; i < ca.length; i++) {
+ var c = ca[i];
+ while (c.charAt(0) == ' ') {
+ c = c.substring(1, c.length);
+ }
+ all.push(c.substring(c[0], c.indexOf(nameEQ)));
+ }
+ return all;
+}
+if (!Array.indexOf) {
+ Array.prototype.indexOf = function(obj) {
+ for (var i = 0; i < this.length; i++) {
+ if (this[i] == obj) {
+ return i;
+ }
+ }
+ return -1;
+ };
+}
+
+function randomRange(min, max) {
+ if (min > max) {
+ return -1;
+ }
+ if (min == max) {
+ return min;
+ }
+ var r = parseInt(Math.random() * (max + 1), 10);
+ return (r + min <= max ? r + min : r);
+}
+
+function browserWidth() {
+ if (window.innerWidth) {
+ return window.innerWidth;
+ } else if (document.documentElement && document.documentElement.clientWidth) {
+ return document.documentElement.clientWidth;
+ } else if (document.body && document.body.offsetWidth) {
+ return document.body.offsetWidth;
+ } else {
+ return 0;
+ }
+}
+
+function browserHeight() {
+ if (window.innerHeight) {
+ return window.innerHeight;
+ } else if (document.documentElement && document.documentElement.clientHeight) {
+ return document.documentElement.clientHeight;
+ } else if (document.body && document.body.offsetHeight) {
+ return document.body.offsetHeight;
+ } else {
+ return 0;
+ }
+}
+Date.prototype.getMonthName = function() {
+ return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][this.getMonth()];
+};
+Date.prototype.milTime = function() {
+ var t = this.getHours() + ':' + this.getMinutes() + ':' + this.getSeconds();
+ return t;
+};
+Date.prototype.daysInMonth = function() {
+ return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
+};
+Date.prototype.calendar = function() {
+ var calArray = [];
+ var buildStr = '';
+ var numDays = this.daysInMonth();
+ var startDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
+ calArray.push('%c(@lightgrey) ' + this.getMonthName() + ' ' + this.getFullYear());
+ calArray.push('Sun Mon Tue Wed Thu Fri Sat');
+ for (var i = 0; i < startDay; i++) {
+ buildStr += ' ';
+ }
+ var blankdays = startDay;
+ var filler = '';
+ var j = 1;
+ for (i = 1; i <= numDays; i++) {
+ if (this.getDate() == i) {
+ j = '%+r' + i + '%-r';
+ } else {
+ j = i;
+ }
+ if (i < 10) {
+ buildStr += ' ' + j + ' ';
+ } else {
+ buildStr += j + ' ';
+ }
+ blankdays++;
+ if (((blankdays % 7) === 0) && (i < numDays)) {
+ calArray.push(buildStr);
+ buildStr = '';
+ }
+ }
+ blankdays++;
+ while ((blankdays % 7) !== 0) {
+ buildStr += ' ';
+ blankdays++;
+ }
+ calArray.push(buildStr);
+ return calArray;
+};
+Array.prototype.shuffle = function() {
+ var tindex, rindex;
+ for (var i = 0; i < this.length; i++) {
+ rindex = Math.floor(Math.random() * this.length);
+ tindex = this[i];
+ this[i] = this[rindex];
+ this[rindex] = tindex;
+ }
+};
+var xmlHttp = null;
+if (typeof XMLHttpRequest != 'undefined') {
+ xmlHttp = new XMLHttpRequest();
+}
+if (!xmlHttp) {
+ var xhttperr;
+ try {
+ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
+ } catch (xhttperr) {
+ try {
+ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
+ } catch (xhttperr) {
+ xmlHttp = null;
+ }
+ }
+}
+
+function fetchHttp(url, fkt) {
+ var xhttperr;
+ fetcherror = "";
+ if (xmlHttp) {
+ try {
+ xmlHttp.open('GET', url, true);
+ xmlHttp.onreadystatechange = function() {
+ if (xmlHttp.readyState == 4) {
+ fkt(xmlHttp.responseText);
+ }
+ };
+ xmlHttp.send(null);
+ } catch (xhttperr) {
+ fetcherror = "Error: no network";
+ if (fkt != eval) {
+ globalterm.write(fetcherror);
+ globalterm.prompt();
+ }
+ }
+ } else {
+ fkt("Error: no XMLHttpRequest. Your browser is broken!");
+ }
+}
+
+function evaljs(content) {
+ var JSONCode = document.createElement("script");
+ JSONCode.setAttribute('type', 'text/javascript');
+ JSONCode.text = content;
+ document.body.appendChild(JSONCode);
+}
+
+function displayraw(content) {
+ globalterm.write(content);
+ globalterm.rawMode = false;
+ globalterm.prompt();
+}
+
+function displaymore(content) {
+ globalterm.clear();
+ globalterm.write('%c(@lightgrey)' + content, true);
+ globalterm.rawMode = false;
+}
+
+function initGeoIP() {
+ if (!window.geoip_country_code) {
+ vgeoip_country_code = "N/A";
+ vgeoip_country_name = "N/A";
+ vgeoip_city = "N/A";
+ vgeoip_region = "N/A";
+ vgeoip_latitude = "N/A";
+ vgeoip_longitude = "N/A";
+ } else {
+ vgeoip_country_code = geoip_country_code();
+ vgeoip_country_name = geoip_country_name();
+ vgeoip_city = geoip_city();
+ vgeoip_region = geoip_region();
+ vgeoip_latitude = geoip_latitude();
+ vgeoip_longitude = geoip_longitude();
+ }
+}
+
+function delAFile(fname) {
+ var fpath = getPath(fname);
+ if (fpath[0] != '/home/www') {
+ globalterm.write('%c(@lightgrey) rm ' + fname + ': Permission denied.');
+ return;
+ }
+ var findex = files_www_n.indexOf(fpath[1]);
+ if (findex != -1) {
+ if (!readCookie(fpath[1])) {
+ globalterm.write('%c(@lightgrey) rm ' + fname + ': Permission denied.');
+ return;
+ }
+ files_www_n.splice(findex, 1);
+ files_www_s.splice(findex, 1);
+ files_www_t.splice(findex, 1);
+ createCookie(fpath[1], '', 0);
+ } else {
+ globalterm.write('%c(@lightgrey)' + fname + ': No such file or directory.');
+ }
+}
+
+function delAllFiles() {
+ var allcookies = readAllCookies();
+ var deleted = 0;
+ for (var i = 0; i < allcookies.length; i++) {
+ if (allcookies[i] == 'clilastlog' || allcookies[i] == 'style' || allcookies[i] == 'broken') {
+ continue;
+ }
+ var fcontent = readCookie(allcookies[i]);
+ var date = fcontent.slice(fcontent.length - 12);
+ if (date.length != 12) {
+ continue;
+ }
+ delAFile(allcookies[i]);
+ deleted++;
+ }
+ if (deleted > 0) {
+ globalterm.write('%c(@lightgrey) deleted ' + deleted + ' files%n');
+ }
+}
+
+function addFile(fname, fcontent, iseditor, fdate) {
+ if (typeof iseditor == 'undefined') {
+ iseditor = false;
+ }
+ var error = "";
+ var fpath = getPath(fname);
+ fname = fpath[1];
+ if (fname == 'unixtoolbox.xhtml') {
+ error = fname + ': Permission denied';
+ if (iseditor) {
+ return 'Save ' + error;
+ } else {
+ globalterm.write('%c(@lightgrey)' + error);
+ return error;
+ }
+ }
+ var size = fcontent.length + 1;
+ var sizestr;
+ var datestr;
+ if (size < 10) {
+ sizestr = ' ' + size;
+ } else if (size < 100) {
+ sizestr = ' ' + size;
+ } else if (size < 1000) {
+ sizestr = ' ' + size;
+ } else if (size < 10000) {
+ sizestr = ' ' + size;
+ }
+ if (typeof fdate == 'undefined') {
+ var d = new Date();
+ var h = d.getHours();
+ if (h < 10) {
+ h = '0' + h;
+ }
+ var m = d.getMinutes();
+ if (m < 10) {
+ m = '0' + m;
+ }
+ var day = d.getDate();
+ if (day < 10) {
+ day = ' ' + day;
+ }
+ var mo = shortm[d.getMonth()];
+ datestr = mo + ' ' + day + ' ' + h + ':' + m;
+ } else {
+ datestr = fdate;
+ }
+ var findex = files_www_n.indexOf(fname);
+ if (fpath[0] != '/home/www') {
+ error = fname + ': Permission denied';
+ if (iseditor) {
+ return 'Save ' + error;
+ } else {
+ globalterm.write('%c(@lightgrey)' + error);
+ return error;
+ }
+ } else if (findex != -1) {
+ if (!readCookie(fname)) {
+ error = fname + ': system file permission denied';
+ if (iseditor) {
+ return 'Save ' + error;
+ } else {
+ globalterm.write('%c(@lightgrey)' + error);
+ return error;
+ }
+ }
+ files_www_n[findex] = fname;
+ files_www_s[findex] = sizestr;
+ files_www_t[findex] = datestr;
+ } else {
+ files_www_n.push(fname);
+ files_www_s.push(sizestr);
+ files_www_t.push(datestr);
+ }
+ fcontent = fcontent.replace(/;/g, '~~');
+ fcontent = fcontent + datestr;
+ createCookie(fname, fcontent, 365);
+ return error;
+}
+
+function addAFile(fname) {
+ var fcontent = readCookie(fname);
+ if (fcontent !== "") {
+ var cnt = fcontent.slice(0, fcontent.length - 12);
+ cnt = cnt.replace(/~~/g, ";");
+ var date = fcontent.slice(fcontent.length - 12);
+ if (date.length == 12) {
+ addFile(fname, cnt, false, date);
+ }
+ }
+}
+
+function getPath(fname) {
+ var fullpath = '';
+ var filename = '';
+ var fullname = '';
+ var rpath = path;
+ while (fname.charAt(fname.length - 1) == '/' && fname.length > 1) {
+ fname = fname.slice(0, fname.length - 1);
+ }
+ var slashindex = fname.lastIndexOf('/');
+ if (slashindex == -1 && fname.charAt(0) != '.') {
+ filename = fname;
+ fullpath = rpath;
+ } else {
+ filename = fname.slice(slashindex + 1);
+ if (fname.charAt(0) == '/') {
+ fullpath = fname.slice(0, slashindex);
+ if (fullpath === '') {
+ fullpath = '/';
+ }
+ } else if (fname.indexOf('..') === 0) {
+ var relarray = fname.split('..');
+ var relpath = rpath.split('/');
+ if (relpath.length >= relarray.length) {
+ for (var i = 0; i < relarray.length - 1; i++) {
+ rpath = rpath.slice(0, rpath.lastIndexOf('/'));
+ }
+ var lastrel = fname.lastIndexOf('../');
+ if (lastrel != -1) {
+ var pathtoadd = fname.slice(lastrel + 3, slashindex);
+ if (pathtoadd.length > 0) {
+ fullpath = rpath + '/' + pathtoadd;
+ } else {
+ fullpath = rpath;
+ }
+ } else {
+ fullpath = rpath;
+ }
+ if (filename == '..') {
+ filename = '';
+ fullname = fullpath;
+ } else {
+ fullname = fullpath + '/' + filename;
+ }
+ }
+ } else {
+ if (rpath == '/') {
+ fullpath = rpath + fname.slice(0, slashindex);
+ } else {
+ fullpath = rpath + '/' + fname.slice(0, slashindex);
+ }
+ }
+ }
+ if (fullpath == '/') {
+ fullname = fullpath + filename;
+ } else {
+ if (fullname.length === 0) {
+ fullname = fullpath + '/' + filename;
+ }
+ }
+ return [fullpath, filename, fullname];
+}
+
+function longlisting(t, files, opt) {
+ if (typeof files == 'undefined') {
+ t.write('%c(@lightgrey)Error path does not exist%n');
+ return;
+ }
+ var showmore = false;
+ var lines = [];
+ if (typeof opt != 'undefined' && opt.indexOf('a') != -1) {
+ t.write(['%c(@lightgrey)drwxrwxr-x 6 sysa wheel 1024 Feb 12 03:03 ./', 'drwxr-xr-x 21 root wheel 512 Jan 25 00:26 ../%n']);
+ }
+ for (var i = 0; i < files[0].length; i++) {
+ lines[i] = files[3] + ' ' + files[1][i] + ' ' + files[2][i] + ' ' + files[0][i];
+ }
+ if (files[0].length > t.conf.rows - 2) {
+ showmore = true;
+ }
+ t.write(lines, showmore);
+}
+
+function listing(t, f) {
+ if (typeof f == 'undefined') {
+ t.write('%c(@lightgrey)Error path does not exist%n');
+ return;
+ }
+ var files = f;
+ var name_length = 0;
+ var space_divider = 5;
+ var fileslist = [];
+ for (var i = 0; i < files.length; i++) {
+ if (files[i].length > name_length) {
+ name_length = files[i].length;
+ }
+ }
+ name_length = name_length + space_divider;
+ var dividers = Math.round((t.conf.cols - 2) / name_length);
+ var j = 1;
+ var thisline = '%c(@lightgrey)';
+ for (var k = 0; k < files.length; k++) {
+ thisline += files[k];
+ var this_name_lenth = files[k].length;
+ if (files[k] == '%+nunixtoolbox.xhtml%-n') {
+ this_name_lenth = this_name_lenth - 6;
+ }
+ var space_missing = name_length - this_name_lenth;
+ var space = '';
+ while (space_missing > 0) {
+ space = space + ' ';
+ space_missing--;
+ }
+ thisline += space;
+ j++;
+ if (j >= dividers) {
+ fileslist.push(thisline);
+ t.write(thisline + '%n');
+ thisline = '%c(@lightgrey)';
+ j = 1;
+ }
+ }
+ if (j !== 0) {
+ t.write(thisline + '%n');
+ }
+}
+var uptimed = randomRange(10, 380);
+var uptime = ' up ' + uptimed + ' days, 04:32, ' +
+ randomRange(0, 10) + ' users, load averages: 0.' +
+ randomRange(10, 99) + ', 0.' + randomRange(10, 89) + ', 0.' + randomRange(10, 69);
+var clockvisible = false;
+stopwatch = false;
+var numh = asciin.length;
+var numw = asciin[0].length / 10;
+var asciistr = [];
+var r;
+var c;
+var started;
+var now;
+var firstline = '';
+var sp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabscdefghijklmnopqrstuvwxyz23456789#$@';
+var s = ' ';
+var dim = null;
+var allRows = [];
+var interval = 0;
+var xperIter = 0;
+var mcolors = ['030', '033', '063', '093', '393', '0c3', '3c0', '6c3', '0f0', '6f3', '3f0', '9f3', 'ff3', 'fff'];
+var regex = [];
+
+function connectionLost() {
+ globalterm.charMode = true;
+ globalterm.lock = true;
+ globalterm.cursorOff();
+ globalterm.newLine();
+ globalterm.write("%n%c(@orange)Error: connection reset by peer%n");
+ createCookie("broken", "true", 0, 1);
+}
+
+function cmdLogin(t) {
+ if ((t.argc == t.argv.length) || (t.argv[t.argc] === '')) {
+ t.write('%c(@lightgrey)usage: login <username>');
+ } else {
+ t.env.getPassword = true;
+ t.env.username = t.argv[t.argc];
+ t.write('%c(@lightgrey)Password: ');
+ t.rawMode = true;
+ t.lock = false;
+ return;
+ }
+}
+
+function cmdSu(t) {
+ t.env.getPassword = true;
+ t.env.username = 'root';
+ t.write('%c(@lightgrey)Password: ');
+ t.rawMode = true;
+ t.lock = false;
+ return;
+}
+var uid = randomRange(500, 1000);
+
+function cmdId(t) {
+ var uidnow = uid;
+ if (t.user == 'www') {
+ uidnow = 80;
+ } else if (t.user == 'root') {
+ uidnow = 0;
+ }
+ t.write('%c(@lightgrey)uid=' + uidnow + '(' + t.user + ') gid=' + uidnow + '(' + t.user + ') groups=' + uidnow + '(' + t.user + ')');
+}
+
+function cmdUptime(t) {
+ d = new Date();
+ t.write('%c(@lightgrey)' + d.milTime() + uptime);
+}
+
+function isnumeric(str) {
+ for (var i = 0; i < str.length; i++) {
+ var c = str.charAt(i);
+ var a = c.charCodeAt(0);
+ if (!(a > 47 && a < 58) && !(a == 45)) {
+ return false;
+ }
+ if (a == 45 && i !== 0) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function cmdCal(t) {
+ if (t.argv.length == 1) {
+ d = new Date();
+ } else {
+ if (t.argv[1] == '-h' || t.argv[1] == '--help') {
+ t.write('%c(@lightgrey)display this months calender.%n');
+ t.write('%c(@lightgrey)usage: cal [month]%n');
+ return;
+ } else if (!isnumeric(t.argv[1])) {
+ t.write('%c(@lightgrey)usage: cal [month] where [month] is numeric%n');
+ return;
+ } else {
+ now = new Date();
+ var year = now.getFullYear();
+ var day = now.getUTCDate();
+ var month = t.argv[1] - 1;
+ d = new Date(year, month, day);
+ }
+ }
+ t.write(d.calendar());
+}
+
+function cmdLs(t) {
+ var findex = 0;
+ var fpath = null;
+ var longlist = false;
+ if (t.argv.length == 1) {
+ listing(t, tree_files[tree.indexOf(path)][0]);
+ return;
+ } else if (t.argv[1] == '-l' || t.argv[1] == '-la' || t.argv[1] == '-al') {
+ if (t.argv.length == 2) {
+ longlisting(t, tree_files[tree.indexOf(path)], t.argv[1]);
+ return;
+ } else {
+ longlist = true;
+ fpath = getPath(t.argv[2]);
+ }
+ } else {
+ fpath = getPath(t.argv[1]);
+ }
+ findex = tree.indexOf(fpath[2]);
+ if (findex != -1) {
+ if (longlist) {
+ longlisting(t, tree_files[findex], t.argv[1]);
+ } else {
+ listing(t, tree_files[findex][0]);
+ }
+ } else {
+ t.write('%c(@lightgrey)' + t.argv[1] + ': No such file or directory.');
+ }
+}
+
+function cmdLl(t) {
+ if (t.argv.length == 1) {
+ longlisting(t, tree_files[tree.indexOf(path)]);
+ } else {
+ fpath = getPath(t.argv[1]);
+ findex = tree.indexOf(fpath[2]);
+ if (findex != -1) {
+ longlisting(t, tree_files[findex]);
+ } else {
+ t.write('%c(@lightgrey)' + t.argv[1] + ': No such file or directory.');
+ }
+ }
+}
+
+function cmdPwd(t) {
+ t.write('%c(@lightgrey)' + path);
+}
+
+function cmdCd(t) {
+ if (t.argv.length == 1 || t.argv[1] == '~') {
+ path = '/home/www';
+ t.ps = '[' + t.user + '@localhost]~>';
+ return;
+ } else {
+ splitpath = getPath(t.argv[1]);
+ var findex = tree.indexOf(splitpath[2]);
+ if (findex != -1) {
+ path = splitpath[2];
+ } else {
+ t.write('%c(@lightgrey)' + splitpath[2] + ': No such file or directory.');
+ }
+ }
+ if (path == '/home/www') {
+ t.ps = '[' + t.user + '@localhost]~>';
+ } else {
+ t.ps = '[' + t.user + '@localhost]' + path + '>';
+ }
+}
+
+function cmdEcho(t) {
+ if (t.argv.length != 1 && t.argv[t.argv.length - 2] == '>') {
+ var file = t.argv[t.argv.length - 1];
+ if (path != '/home/www') {
+ t.write('%c(@lightgrey)Permission denied');
+ return;
+ }
+ var fs = '';
+ for (var i = 1; i < t.argv.length - 2; i++) {
+ fs += t.argv[i];
+ if (i + 1 != t.argv.length - 2) {
+ fs += ' ';
+ }
+ }
+ addFile(file, fs);
+ } else if (t.argv.length != 1 && t.argv[1] == '$PATH') {
+ t.write('%c(@lightgrey)/bin:/sbin:/etc');
+ } else {
+ var s = '%c(@lightgrey)';
+ for (var j = 1; j < t.argv.length; j++) {
+ s += t.argv[j];
+ if (j + 1 != t.argv.length) {
+ s += ' ';
+ }
+ }
+ t.write(s);
+ }
+}
+
+function isdir(dirpath) {
+ if (tree.indexOf(dirpath) != -1) {
+ return true;
+ }
+ return false;
+}
+
+function isfile(filepath) {
+ var fpath = getPath(filepath);
+ if (tree.indexOf(fpath[0]) == -1) {
+ return false;
+ }
+ if (tree_files[tree.indexOf(fpath[0])][0].indexOf(fpath[1]) == -1) {
+ return false;
+ }
+ return true;
+}
+
+function rmdir(dirpath) {
+ var fpath = getPath(dirpath);
+ for (var j = 0; j < 3; j++) {
+ tree_files[tree.indexOf(fpath[0])][j].splice(tree_files[tree.indexOf(fpath[0])][0].indexOf(fpath[1]), 1);
+ }
+ if (isdir(dirpath)) {
+ tree_files.splice(tree.indexOf(fpath[2]), 1);
+ tree.splice(tree.indexOf(fpath[2]), 1);
+ }
+}
+
+function rmdirr(dirpath) {
+ if (isdir(dirpath)) {
+ var fpath = getPath(dirpath);
+ var files = tree_files[tree.indexOf(fpath[2])][0];
+ while (files.length > 0) {
+ rmdirr(dirpath + '/' + files[files.length - 1]);
+ }
+ }
+ rmdir(dirpath);
+}
+
+function cmdRm(t) {
+ t.wrap = false;
+ if (t.argv.length == 1) {
+ t.write('%c(@lightgrey)usage: rm <file>');
+ return;
+ }
+ var rf = false;
+ var rootindex = 0;
+ var dirindex = 0;
+ var fileindex = 0;
+ var filearg = t.argv[t.argv.length - 1];
+ if (t.argv.indexOf('-rf') != -1) {
+ rf = true;
+ }
+ if (t.user == 'root') {
+ if (filearg == '/' && rf) {
+ setTimeout('connectionLost()', 15000);
+ filearg = '/bin';
+ }
+ var fpath = getPath(filearg);
+ var fname = fpath[1];
+ var lpath = fpath[0];
+ var fullname = fpath[2];
+ rootindex = tree.indexOf(lpath);
+ if (rootindex != -1) {
+ dirindex = tree.indexOf(fullname);
+ fileindex = tree_files[rootindex][0].indexOf(fname);
+ if (isdir(fullname)) {
+ if (rf) {
+ rmdirr(fullname);
+ } else {
+ t.write('rm: cannot remove ' + filearg + ': Is a directory%n');
+ }
+ } else {
+ if (fileindex != -1) {
+ for (var i = 0; i < 3; i++) {
+ tree_files[rootindex][i].splice(fileindex, 1);
+ }
+ } else {
+ t.write('rm: cannot remove ' + fname + ': No such file or directory%n');
+ }
+ }
+ } else {
+ t.write('rm: cannot remove ' + lpath + ': No such file or directory%n');
+ }
+ } else {
+ if (filearg == '/') {
+ t.write('%c(@lightgrey)I\'m sorry Dave, I\'m afraid I can\'t do that.');
+ } else if (t.argv[1] == '*') {
+ delAllFiles();
+ } else {
+ delAFile(filearg);
+ }
+ }
+}
+
+function cmdUname(t) {
+ if (t.argv.length == 1 || t.argv[1] == '-s') {
+ t.write('%c(@lightgrey)FreeBSD');
+ } else if (t.argv[1] == '-i') {
+ t.write('%c(@lightgrey)CB');
+ } else if (t.argv[1] == '-m' || t.argv[1] == '-p') {
+ t.write('%c(@lightgrey)i386');
+ } else if (t.argv[1] == '-n') {
+ t.write('%c(@lightgrey)localhost');
+ } else if (t.argv[1] == '-a') {
+ t.write('%c(@lightgrey)FreeBSD localhost 7.1-STABLE FreeBSD 7.1-STABLE #2: Wed Jan 30 16:21:05 CET 2009 c@localhost:/usr/obj/usr/src/sys/CB i386');
+ } else if (t.argv[1] == '-v') {
+ t.write('%c(@lightgrey)FreeBSD 7.1-STABLE #2: Wed Jan 30 16:21:05 CET 2009 c@localhost:/usr/obj/usr/src/sys/CB');
+ } else if (t.argv[1] == '-r') {
+ t.write('%c(@lightgrey)7.1-STABLE');
+ } else {
+ t.write(['%c(@lightgrey)uname: illegal option -' + t.argv[1], 'usage: uname [-aimnprsv]']);
+ }
+}
+
+function cmdHostname(t) {
+ if (t.argv.length == 1 || t.argv[1] == '-f') {
+ t.write('%c(@lightgrey)localhost');
+ } else if (t.argv[1] == '-s') {
+ t.write('%c(@lightgrey)cb');
+ } else if (t.argv[1] == '-i') {
+ t.write('%c(@lightgrey)78.31.70.238');
+ } else {
+ t.write(['%c(@lightgrey)uname: illegal option -' + t.argv[1], 'usage: hostname [-fsi]']);
+ }
+}
+
+function cmdReset(t) {
+ t.write(' ');
+ t.clear();
+ t.rawMode = true;
+ t.open();
+ return;
+}
+
+function cmdCat(t, iseditor, filename) {
+ var error = "ok";
+ if (t.argv.length == 1 && !iseditor) {
+ t.write('%c(@lightgrey)usage: cat file');
+ return error;
+ }
+ if (typeof filename == 'undefined') {
+ filename = t.argv[1];
+ }
+ var fpath = getPath(filename);
+ var fname = fpath[1];
+ var lpath = fpath[0];
+ var fullname = fpath[2];
+ var cnt;
+ var tindex = tree.indexOf(lpath);
+ if (tindex == -1) {
+ error = "Error: " + lpath + " wrong path";
+ return error;
+ }
+ var findex = tree_files[tindex][0].indexOf(fname);
+ if (findex != -1 || fname == 'unixtoolbox.xhtml') {
+ var fcontent = readCookie(fname);
+ if (fcontent) {
+ cnt = fcontent.slice(0, fcontent.length - 12);
+ cnt = cnt.replace(/~~/g, ";");
+ t.write('%c(@lightgrey)' + cnt + '%n');
+ return error;
+ }
+ cnt = filesContent[fullname];
+ if (typeof cnt != 'undefined' && cnt != 'undefined') {
+ t.write(cnt);
+ } else {
+ if (remote_files.indexOf(fname) != -1) {
+ cnt = filesContent[fullname];
+ t.write('%c(@lightgrey)' + cnt + '%n');
+ } else if (binary_files.indexOf(fname) != -1) {
+ if (iseditor) {
+ error = " binary file";
+ } else {
+ window.location = '/' + fname;
+ }
+ } else {
+ error = fname + ': Permission denied';
+ if (iseditor) {
+ return 'Open ' + error;
+ } else {
+ t.write('%c(@lightgrey)cat : ' + error + '%n');
+ }
+ }
+ }
+ } else {
+ if (!iseditor) {
+ t.write('%c(@lightgrey)cat : ' + fname + ' : File not found%n');
+ } else {
+ error = "";
+ }
+ }
+ return error;
+}
+
+function cmdMan(t) {
+ if (t.argv.length == 1) {
+ t.write('%c(@lightgrey)usage: man <command>%n');
+ t.write('%c(@lightgrey)The following man pages are available, or use apropos on any command.%n');
+ listing(t, files_man[0]);
+ return;
+ }
+ var cmd = t.argv[1];
+ if (files_man_n.indexOf(cmd) != -1) {
+ var dim = t.getDimensions();
+ var file = filesContent['/usr/share/man/' + cmd];
+ if (file.length > t.conf.rows - 1) {
+ t.write(file, true);
+ } else {
+ t.write(file);
+ }
+ } else {
+ t.write('%c(@lightgrey)No manual entry for ' + cmd);
+ }
+}
+
+function cmdMore(t) {
+ if (t.argv.length == 1) {
+ t.write('%c(@lightgrey)usage: more <file>');
+ return;
+ }
+ var fpath = getPath(t.argv[1]);
+ var fname = fpath[1];
+ var lpath = fpath[0];
+ var fullname = fpath[2];
+ var cnt;
+ var findex;
+ var tindex = tree.indexOf(lpath);
+ if (tindex == -1) {
+ return;
+ }
+ if (lpath == '/home/www') {
+ findex = tree_files[tindex][0].indexOf(fname);
+ if (findex != -1) {
+ t.clear();
+ var fcontent = readCookie(fname);
+ if (fcontent) {
+ cnt = fcontent.slice(0, fcontent.length - 12);
+ cnt = cnt.replace(/~~/g, ";");
+ t.write('%c(@lightgrey)' + cnt + '%n');
+ return;
+ } else if (fname == 'sitemap.xml') {
+ t.write(file_sitemap, true);
+ return;
+ } else if (fname == 'cb.txt') {
+ t.write(file_cb, true);
+ return;
+ } else if (fname == 'about.txt') {
+ t.write(file_about, true);
+ return;
+ } else if (fname == 'bugs.txt') {
+ t.write(file_bugs, true);
+ return;
+ }
+ }
+ if (remote_files.indexOf(fname) != -1) {
+ t.rawMode = true;
+ t.write('%c(@lightgrey)Patience...%n');
+ fetchHttp('/' + fname, displaymore);
+ } else if (binary_files.indexOf(fname) != -1) {
+ t.write('%c(@lightgrey)Binary file. Use pr instead');
+ } else {
+ t.write('%c(@lightgrey)File not found.');
+ }
+ } else if (lpath == '/etc') {
+ findex = tree_files[tindex][0].indexOf(fname);
+ if (findex != -1) {
+ cnt = filesContent[fullname];
+ if (typeof cnt != 'undefined') {
+ t.clear();
+ t.write(cnt);
+ } else {
+ t.write('%c(@lightgrey)' + fname + ' : Permission denied%n');
+ }
+ } else {
+ t.write('%c(@lightgrey)' + fname + ' : File not found%n');
+ }
+ }
+}
+
+function cmdPr(t) {
+ if (t.argv.length == 1) {
+ t.write('%c(@lightgrey)usage: pr file');
+ } else {
+ window.location = t.argv[1];
+ }
+}
+
+function cmdRedim(t, manual) {
+ var oldie = false;
+ if (typeof document.documentElement.style.maxHeight == "undefined") {
+ oldie = true;
+ }
+ if (navigator.appVersion.indexOf('Safari') != -1) {
+ safari = true;
+ }
+ var dim = t.getDimensions();
+ var neww = Math.round((t.conf.cols / dim.width) * browserWidth()) - 2;
+ var newh = Math.round((t.conf.rows / dim.height) * browserHeight()) - 1;
+ if (oldie) {
+ t.write('Using IE6 hack%n');
+ neww = neww - 2;
+ }
+ if ((t.argv) && t.argv.length > 1 || manual) {
+ t.write('Terminal dimentions in px: ' + dim.width + ' x ' + dim.height + ' px%n');
+ t.write('Browser window dimentions in px: ' + browserWidth() + ' x ' + browserHeight() + ' px%n');
+ t.write('Terminal columns x rows: ' + t.conf.cols + ' x ' + t.conf.rows + ' char%n');
+ t.write('Maximal columns x rows: ' + neww + ' x ' + newh + ' char%n');
+ } else if (!(t.argv) || t.argv.length == 1) {
+ if (neww !== 0) {
+ t.resizeTo(neww, newh);
+ t.maxCols = neww;
+ t.maxLines = newh;
+ if (neww < (6 * asciinumber[0].length / 10) + (2 * asciiddot[0].length)) {
+ asciin = asciinumber_s;
+ asciid = asciiddot_s;
+ } else {
+ asciin = asciinumber;
+ asciid = asciiddot;
+ }
+ numh = asciin.length;
+ numw = asciin[0].length / 10;
+ }
+ }
+}
+
+function redim() {
+ cmdRedim(globalterm);
+}
+
+function cmdTime(t) {
+ var d = new Date();
+ t.write('%c(@lightgrey)' + d.milTime());
+}
+
+function displayNum(str, center) {
+ var n = 0;
+ for (var i = 0; i < numh; i++) {
+ asciistr[i] = '';
+ }
+ for (var k = 0; k < str.length; k++) {
+ if (str.charAt(k) == ':') {
+ for (var j = 0; j < numh; j++) {
+ asciistr[j] = asciistr[j] + asciid[j];
+ }
+ } else {
+ n = str.charAt(k);
+ for (var l = 0; l < numh; l++) {
+ asciistr[l] = asciistr[l] + asciin[l].slice(n * numw, (n * numw) + numw);
+ }
+ }
+ }
+ if (!center) {
+ globalterm.write(s);
+ } else {
+ var r = Math.round(globalterm.conf.rows / 2) - Math.round(numh / 2);
+ var c = Math.round((globalterm.conf.cols - asciistr[0].length) / 2);
+ for (var m = 0; m < asciistr.length; m++) {
+ globalterm.typeAt(r + m, c, asciistr[m], 3 * 256);
+ }
+ }
+}
+
+function clockHandler(initterm) {
+ if (initterm) {
+ initterm.env.handler = initterm.handler;
+ initterm.cursorOff();
+ asciistr = [];
+ numh = asciin.length;
+ numw = asciin[0].length / 10;
+ r = Math.round(globalterm.conf.rows / 2) - Math.round(numh / 2);
+ c = Math.round((globalterm.conf.cols - (6 * numw) - 2 * asciid[0].length) / 2) + (4 * numw) + 2 * asciid[0].length;
+ return;
+ }
+ this.lock = true;
+ var key = this.inputChar;
+ if (key == 32) {
+ if (interval === 0) {
+ interval = setInterval('carriageReturn()', 1000);
+ } else {
+ clearInterval(interval);
+ interval = 0;
+ }
+ } else if (key == 114) {
+ started = new Date();
+ } else if (key != globalterm.termKey.CR) {
+ clearInterval(interval);
+ interval = 0;
+ clockvisible = false;
+ stopwatch = false;
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.clear();
+ this.prompt();
+ return;
+ } else {
+ now = new Date();
+ var h;
+ var m;
+ var s;
+ if (!stopwatch) {
+ h = now.getHours();
+ m = now.getMinutes();
+ s = now.getSeconds();
+ } else {
+ var diff = (now - started) / 1000;
+ s = Math.floor(diff % 60);
+ diff = diff / 60;
+ m = Math.floor(diff % 60);
+ diff = diff / 60;
+ h = Math.floor(diff % 24);
+ }
+ var sh = '' + h;
+ var sm = '' + m;
+ var ss = '' + s;
+ if (h < 10) {
+ sh = '0' + h;
+ }
+ if (m < 10) {
+ sm = '0' + m;
+ }
+ if (s < 10) {
+ ss = '0' + s;
+ }
+ if (!clockvisible) {
+ displayNum(sh + ':' + sm + ':' + ss, true);
+ clockvisible = true;
+ } else if (s < 2) {
+ displayNum(sh + ':' + sm + ':' + ss, true);
+ } else {
+ for (var j = 0; j < numh; j++) {
+ asciistr[j] = '' +
+ asciin[j].slice(ss.charAt(0) * numw, (ss.charAt(0) * numw) + numw) +
+ asciin[j].slice(ss.charAt(1) * numw, (ss.charAt(1) * numw) + numw);
+ }
+ for (var i = 0; i < asciistr.length; i++) {
+ this.typeAt(r + i, c, asciistr[i], 3 * 256);
+ }
+ }
+ }
+ this.lock = false;
+}
+
+function cmdClock(t) {
+ started = new Date();
+ var findex = -1;
+ if (t.argv.length >= 2) {
+ findex = t.argv.indexOf('-t');
+ }
+ if (findex != -1) {
+ stopwatch = true;
+ t.argv.splice(findex, 1);
+ findex = -1;
+ }
+ if (t.argv.length >= 2) {
+ findex = t.argv.indexOf('-s');
+ }
+ if (findex != -1) {
+ asciin = asciinumber_s;
+ asciid = asciiddot_s;
+ t.argv.splice(findex, 1);
+ findex = -1;
+ } else if (t.conf.cols > (6 * asciinumber[0].length / 10) + (2 * asciiddot[0].length)) {
+ asciin = asciinumber;
+ asciid = asciiddot;
+ }
+ t.charMode = true;
+ t.cursorOff();
+ t.clear();
+ clockHandler(t);
+ interval = setInterval('carriageReturn()', 1000);
+ t.handler = clockHandler;
+ t.lock = false;
+ return;
+}
+
+function setNormal() {
+ term.conf.bgColor = '#181818';
+ term.rebuild();
+}
+
+function setColor(color) {
+ term.conf.bgColor = color;
+ term.rebuild();
+ globalterm.write(' ');
+}
+var bootline = 0;
+var booting = false;
+var sdnotifed = false;
+var rebootask1 = false;
+var rebootask2 = false;
+var rebootask3 = false;
+var beenhere = false;
+
+function rebootHandler(initterm) {
+ if (initterm) {
+ initterm.env.handler = initterm.handler;
+ if (beenhere) {
+ initterm.write('%c(@orange)You again?? %c(@lightgrey)Alright you want to reboot, but are you sure?');
+ } else {
+ initterm.write('%c(@lightgrey)So you want to reboot. Are you sure?');
+ }
+ return;
+ }
+ this.newLine();
+ this.charMode = false;
+ this.lock = true;
+ if (this.isPrintable(key)) {
+ var ch = String.fromCharCode(key);
+ this.type(ch);
+ }
+ if (!rebootask1) {
+ beenhere = true;
+ this.cursorOn();
+ if (this.lineBuffer == 'yes') {
+ rebootask1 = true;
+ this.write('%c(@lightgrey)Are you really sure you know which machine is actually going to reboot?');
+ this.newLine();
+ } else if (this.lineBuffer == 'no') {
+ this.write('%c(@lightgrey)Good choice! Go play with the other commands.');
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.prompt();
+ return;
+ } else if (this.lineBuffer) {
+ this.write('%c(@lightgrey)answer yes or no');
+ this.newLine();
+ }
+ this.lock = false;
+ this.lineBuffer = '';
+ return;
+ } else if (!rebootask2) {
+ this.cursorOn();
+ if (this.lineBuffer == 'yes') {
+ rebootask2 = true;
+ this.write('%c(@lightgrey)So will that be yours or mine? Answer "yours" or "mine" or "quit"');
+ this.newLine();
+ } else if (this.lineBuffer == 'no') {
+ this.write('%c(@lightgrey)I don\'t know either :o)');
+ rebootask1 = false;
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.prompt();
+ return;
+ } else if (this.lineBuffer) {
+ this.write('%c(@lightgrey)answer with yes or no');
+ this.newLine();
+ }
+ this.lock = false;
+ this.lineBuffer = '';
+ return;
+ } else if (!rebootask3) {
+ this.cursorOn();
+ if (this.lineBuffer == 'yours' || this.lineBuffer == 'mine') {
+ this.cursorOff();
+ rebootask3 = true;
+ this.write('%c(@lightgrey)So you mean yours....OK you asked for it.');
+ setTimeout('carriageReturn()', 2000);
+ } else if (this.lineBuffer == 'quit') {
+ rebootask1 = false;
+ rebootask2 = false;
+ rebootask3 = false;
+ this.write('%c(@lightgrey)whimp :o).');
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.prompt();
+ return;
+ } else if (this.lineBuffer) {
+ this.write('Answer "yours" or "mine" or "quit"');
+ this.newLine();
+ }
+ this.lock = false;
+ this.lineBuffer = '';
+ return;
+ }
+ this.lock = true;
+ var key = this.inputChar;
+ this.cursorOff();
+ if (key == 32) {
+ if (interval === 0) {
+ interval = setInterval('carriageReturn()', 300);
+ } else {
+ clearInterval(interval);
+ interval = 0;
+ }
+ } else if (!sdnotifed && !booting) {
+ this.newLine();
+ this.write(['%n%n%n%c(@orange)Shutdown at ' + Date(), '%c(@chartreuse)shutdown: [pid ' + randomRange(189, 21000) + ']', 'root:{' + randomRange(70, 150) + '}' + path, '%n%n*** System shutdown message from ' + clientip + ' ***', 'Sytem going down in 4 seconds%c()%n%n%n']);
+ this.write('Send SIGTERM to all processes%n');
+ this.write(pslong);
+ this.newLine();
+ this.write('%n%n');
+ sdnotifed = true;
+ setTimeout('interval = setInterval (\'carriageReturn()\', 300 )', 4000);
+ } else if (!booting && sdnotifed) {
+ if (bootline == filesContent['/boot/shutdown'].length - 1) {
+ bootline = 0;
+ clearInterval(interval);
+ interval = 0;
+ this.clear();
+ term.conf.bgColor = 'blue';
+ term.rebuild();
+ this.write(' ');
+ booting = true;
+ setTimeout('setColor(\'#ffffff\')', 1200);
+ setTimeout('setNormal()', 1600);
+ setTimeout('interval = setInterval (\'carriageReturn()\', 300 )', 2500);
+ } else {
+ this.write(filesContent['/boot/shutdown'][bootline]);
+ bootline++;
+ if (bootline == filesContent['/boot/shutdown'].length - 1) {
+ clearInterval(interval);
+ interval = setInterval('carriageReturn()', 4000);
+ }
+ }
+ } else {
+ if (bootline == filesContent['/boot/kernel'].length - 1) {
+ clearInterval(interval);
+ interval = 0;
+ bootline = 0;
+ booting = false;
+ rebootask1 = false;
+ rebootask2 = false;
+ this.newLine();
+ cmdRedim(this, true);
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.cursorOn();
+ setTimeout('globalterm.clear()', 3000);
+ setTimeout('location.reload()', 3500);
+ } else {
+ this.write(filesContent['/boot/kernel'][bootline]);
+ bootline++;
+ }
+ }
+ this.lock = false;
+}
+
+function cmdReboot(t) {
+ if (t.user != 'root') {
+ t.write("%c(@lightgrey)You must be root to do this");
+ return;
+ }
+ t.charMode = true;
+ rebootHandler(t);
+ t.handler = rebootHandler;
+ setTimeout('carriageReturn()', 100);
+ t.lock = false;
+ return;
+}
+
+function cmdNum(t) {
+ if (t.argv.length == 1) {
+ t.write('%c(@lightgrey)usage: num number');
+ }
+ asciistr = [];
+ displayNum(t.argv[1], true);
+}
+
+function randomScreen(isgame) {
+ globalterm.wrap = true;
+ var maxr = 0;
+ allRows = [];
+ globalterm.clear();
+ if (typeof isgame == 'undefined') {
+ isgame = false;
+ }
+ if (isgame) {
+ maxr = globalterm.conf.rows - 2;
+ } else {
+ maxr = globalterm.conf.rows;
+ }
+ firstline = "";
+ for (var j = 0; j <= maxr; j++) {
+ for (var i = 0; i < globalterm.conf.cols; i++) {
+ if (isgame) {
+ if (i === 0 || i == globalterm.conf.cols - 1) {
+ firstline += '*';
+ continue;
+ }
+ if (randomRange(1, 250) <= snakefood) {
+ firstline += randomRange(1, 9);
+ } else {
+ firstline += ' ';
+ }
+ } else {
+ firstline += String.fromCharCode(randomRange(38, 126));
+ }
+ }
+ allRows.push(firstline);
+ firstline = "";
+ }
+ if (isgame) {
+ for (var k = 0; k < globalterm.conf.cols; k++) {
+ firstline += '%c(@lightgrey)*';
+ }
+ allRows[0] = allRows[maxr] = firstline;
+ var nrocks = Math.round((globalterm.conf.cols * globalterm.conf.rows) / snakerocks);
+ for (var rocks = 0; rocks < nrocks; rocks++) {
+ var rockr = randomRange(2, globalterm.conf.rows - 9);
+ var rockc = randomRange(2, globalterm.conf.cols - 7);
+ var rockchar = '';
+ for (var kr = 0; kr < 4; kr++) {
+ if (kr > 0 && kr < 3) {
+ rockchar = "#####";
+ } else if (kr === 0) {
+ rockchar = ",###,";
+ } else if (kr == 3) {
+ rockchar = "'###'";
+ }
+ allRows[rockr + kr] = allRows[rockr + kr].slice(0, rockc) +
+ rockchar + allRows[rockr + kr].slice(rockc + 5);
+ }
+ }
+ for (var l = 0; l < allRows.length; l++) {
+ allRows[l] = allRows[l].replace(/#/g, "%c(@orange)#%c(@lightgrey)");
+ allRows[l] = allRows[l].replace(/,/g, "%c(@orange),%c(@lightgrey)");
+ allRows[l] = allRows[l].replace(/\'/g, "%c(@orange)'%c(@lightgrey)");
+ }
+ }
+ return allRows;
+}
+
+function cmdRandom(t) {
+ if (t.argv.length == 2 && t.argv[1] == 'n') {
+ t.write(randomScreen(true));
+ } else {
+ t.write(randomScreen());
+ }
+}
+
+function iterateArray(write) {
+ if (Math.round(Math.random() - 0.40) === 0) {
+ s = ' ';
+ } else {
+ s = '1';
+ }
+ for (i = 0; i < mcolors.length; i++) {
+ if (i === 0) {
+ repl = s;
+ } else {
+ repl = '%c(#' + mcolors[i - 1] + ')' + sp.charAt(randomRange(0, 61));
+ }
+ firstline = firstline.replace(regex[i], repl);
+ }
+ repl = '%c(#fff)' + sp.charAt(randomRange(0, 61));
+ for (i = 0; i < xperIter; i++) {
+ var p = randomRange(0, firstline.length);
+ if (firstline.charAt(p) == ' ' || firstline.charAt(p) == '1') {
+ firstline = firstline.slice(0, p) + '%c(#fff)#' + firstline.slice(p + 1);
+ }
+ }
+ var rowtochange = randomRange(1, allRows.length - 1);
+ allRows[rowtochange] = allRows[rowtochange].replace(regex[mcolors.length], repl);
+ allRows.unshift(firstline);
+ allRows.pop();
+ if (write) {
+ globalterm.write(allRows);
+ }
+}
+var matrixrounds;
+var matrixemptystart = false;
+
+function matrixHandler(initterm) {
+ var repl;
+ var i = 0;
+ if (initterm) {
+ if (initterm.argv.indexOf('-s') != -1) {
+ matrixemptystart = true;
+ } else {
+ matrixemptystart = false;
+ }
+ matrixrounds = globalterm.conf.rows * 3;
+ firstline = '';
+ xperIter = Math.round(globalterm.conf.cols / 45);
+ initterm.env.handler = initterm.handler;
+ dim = initterm.getDimensions();
+ for (i = 0; i < mcolors.length; i++) {
+ regex[i] = eval('\/%c\\(#' + mcolors[i] + '\\).\/g');
+ }
+ regex[mcolors.length] = eval('\/%c\\(#fff\\).\/g');
+ for (i = 0; i < initterm.conf.cols - 1; i++) {
+ firstline = firstline + ' ';
+ }
+ for (i = 0; i <= initterm.conf.rows; i++) {
+ allRows[i] = firstline;
+ }
+ return;
+ }
+ this.lock = true;
+ var key = this.inputChar;
+ if (key == 32) {
+ if (interval === 0) {
+ interval = setInterval('carriageReturn()', 1000);
+ } else {
+ clearInterval(interval);
+ interval = 0;
+ }
+ }
+ if (key == 113 || key == termKey.ESC) {
+ clearInterval(interval);
+ interval = 0;
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.clear();
+ this.prompt();
+ return;
+ } else {
+ if (!matrixemptystart && matrixrounds > 0) {
+ while (matrixrounds > 0) {
+ iterateArray(false);
+ matrixrounds--;
+ }
+ }
+ iterateArray(false);
+ this.write(allRows);
+ }
+ this.lock = false;
+}
+
+function cmdMatrix(t) {
+ t.cursorOff();
+ t.charMode = true;
+ t.write('%c(@lightgrey)Use q or ESC to quit. Space to pause%n');
+ t.write('%c(@lightgrey) -s for empty start%n');
+ t.write('%c(@lightgrey) See also man matrix%n');
+ matrixHandler(t);
+ interval = setInterval('carriageReturn()', 1200);
+ t.handler = matrixHandler;
+ t.lock = false;
+ return;
+}
+
+function init(t) {
+ var numproc = randomRange(9, 12);
+ var h = randomRange(0, 9);
+ var m = randomRange(10, 59);
+ for (var i = 0; i < numproc; i++) {
+ var s = randomRange(10, 59);
+ pslong.push('%c(@lightgrey)www ' + randomRange(1000, 5100) + ' 0.0 1.5 ' +
+ randomRange(10000, 51000) + ' ' + randomRange(10000, 51000) + ' ?? I ' + h + ':' + m + '.' + s + ' /usr/local/sbin/httpd');
+ }
+}
+
+function cmdPs(t) {
+ var numproc = randomRange(8, 14);
+ var h = randomRange(0, 9);
+ var m = randomRange(10, 59);
+ if (t.argv.length == 1) {
+ t.write('%c(@lightgrey)PID TT STAT TIME COMMAND%n');
+ for (var i = 0; i < numproc; i++) {
+ var s = ((i * 13) + 10) % 60;
+ s = (s < 10) ? 10 : s;
+ t.write('%c(@lightgrey)' + randomRange(1000, 5100) + ' ?? I ' + h + ':' + m + '.' + s + ' /usr/local/sbin/httpd%n');
+ }
+ } else {
+ t.write(pslong);
+ }
+}
+
+function cmdWhatis(t) {
+ if (t.argv.length == 1) {
+ t.write('%c(@lightgrey)usage: whatis/apropos <command>');
+ } else if (t.argv[1] == 'help') {
+ t.write('%c(@lightgrey)display the help message');
+ } else if (t.argv[1] == 'info') {
+ t.write('%c(@lightgrey)display the info message with credentials');
+ } else if (t.argv[1] == 'clear') {
+ t.write('%c(@lightgrey)clear the terminal');
+ } else if (t.argv[1] == 'echo') {
+ t.write('%c(@lightgrey)echo the arguments or create a file with >');
+ } else if (t.argv[1] == 'ls' || t.argv[1] == 'll') {
+ t.write('%c(@lightgrey)list directory contents');
+ } else if (t.argv[1] == 'cd') {
+ t.write('%c(@lightgrey)change working directory');
+ } else if (t.argv[1] == 'rm') {
+ t.write('%c(@lightgrey)delete a file mostly for root only');
+ } else if (t.argv[1] == 'uname') {
+ t.write('%c(@lightgrey)display system identification');
+ } else if (t.argv[1] == 'whoami') {
+ t.write('%c(@lightgrey)display effective user id');
+ } else if (t.argv[1] == 'whereami') {
+ t.write('%c(@lightgrey)display you probable position with country and city');
+ } else if (t.argv[1] == 'weather') {
+ t.write('%c(@lightgrey)display weather information based on your location');
+ } else if (t.argv[1] == 'who') {
+ t.write('%c(@lightgrey)display who is on the system');
+ } else if (t.argv[1] == 'id') {
+ t.write('%c(@lightgrey)return user identity');
+ } else if (t.argv[1] == 'matrix') {
+ t.write('%c(@lightgrey)show a matrix like screen saver (it is CPU hungry)');
+ } else if (t.argv[1] == 'more') {
+ t.write('%c(@lightgrey)display a file with paging function');
+ } else if (t.argv[1] == 'pwd') {
+ t.write('%c(@lightgrey)return working directory name');
+ } else if (t.argv[1] == 'cat') {
+ t.write('%c(@lightgrey)concatenate and print files');
+ } else if (t.argv[1] == 'chat') {
+ t.write('%c(@lightgrey)chat with the terminal chatbot');
+ } else if (t.argv[1] == 'hostname') {
+ t.write('%c(@lightgrey)set or print name of current host system');
+ } else if (t.argv[1] == 'ps') {
+ t.write('%c(@lightgrey)process status');
+ } else if (t.argv[1] == 'pr') {
+ t.write('%c(@lightgrey)print files on the browser');
+ } else if (t.argv[1] == 'browse') {
+ t.write('%c(@lightgrey)display the file on the browser');
+ } else if (t.argv[1] == 'browser') {
+ t.write('%c(@lightgrey)display your IP address and browser information');
+ } else if (t.argv[1] == 'cal') {
+ t.write('%c(@lightgrey)displays a calendar');
+ } else if (t.argv[1] == 'uptime') {
+ t.write('%c(@lightgrey)show how long system has been running');
+ } else if (t.argv[1] == 'date') {
+ t.write('%c(@lightgrey)display date and time');
+ } else if (t.argv[1] == 'time') {
+ t.write('%c(@lightgrey)time command execution');
+ } else if (t.argv[1] == 'clock') {
+ t.write('%c(@lightgrey)display a full screen clock or stopwatch with the option -t');
+ } else if (t.argv[1] == 'top') {
+ t.write('%c(@lightgrey)display information about the top cpu processes');
+ } else if (t.argv[1] == 'df') {
+ t.write('%c(@lightgrey)display free disk space');
+ } else if (t.argv[1] == 'history') {
+ t.write('%c(@lightgrey)display the last used commands');
+ } else if (t.argv[1] == 'fortune') {
+ t.write('%c(@lightgrey)print a random, hopefully interesting, adage');
+ } else if (t.argv[1] == 'su') {
+ t.write('%c(@lightgrey)substitute user identity');
+ } else if (t.argv[1] == 'ssh') {
+ t.write('%c(@lightgrey)ssh connection using the mindterm java terminal');
+ } else if (t.argv[1] == 'vi') {
+ t.write('%c(@lightgrey)vi the editor!');
+ } else if (t.argv[1] == 'snake') {
+ t.write('%c(@lightgrey)A variation of the classical snake game');
+ } else if (t.argv[1] == 'invaders') {
+ t.write('%c(@lightgrey)The invaders game provided by Norbert Landsteiner');
+ } else if (t.argv[1] == 'logout' || t.argv[1] == 'exit') {
+ t.write('%c(@lightgrey)Exit and logout from the terminal');
+ } else if (t.argv[1] == 'reset') {
+ t.write('%c(@lightgrey)reset the terminal as it\'s initial state');
+ } else if (t.argv[1] == 'reload') {
+ t.write('%c(@lightgrey)reload the web page');
+ } else if (t.argv[1] == 'ping') {
+ t.write('%c(@lightgrey)ping a host, or yourself when no argument is given');
+ } else {
+ t.write('%c(@lightgrey)' + t.argv[1] + ': nothing appropriate');
+ }
+}
+var viquit = false;
+var visave = false;
+var viforce = false;
+var viopen = false;
+var viedit = false;
+var visaved = true;
+var visplvis = false;
+var vicmd = "";
+var vifile = "";
+
+function readOneLine(t, row) {
+ var c = 0;
+ var line = "";
+ while (t.isPrintable(t.charBuf[row][c]) && c < t.maxCols) {
+ line += String.fromCharCode(t.charBuf[row][c]);
+ c++;
+ }
+ return line;
+}
+
+function removeLine(t, row) {
+ var l = 0;
+ var content = "";
+ for (var r = row; r < t.maxLines - 1; r++) {
+ content = readOneLine(t, r + 1);
+ t.typeAt(r, 0, content);
+ t.c = content.length;
+ t.r = r;
+ while (t.isPrintable(t.charBuf[r][t.c])) {
+ t.fwdDelete();
+ }
+ l++;
+ if (t.charBuf[r][0] == 126) {
+ break;
+ }
+ }
+ t.c = 0;
+ t.r = row;
+}
+
+function viSplash(t) {
+ var splash = [' Vi', '', ' version 0.1 alpha :o)', '', ' <ESC> to enter command mode', ' :q<Enter> to exit', ' :w<Enter> to save', ' :w filename to save to "filename"', ' :e filename to open "filename"', ' :q!<Enter> to exit without saving', ' D to delete rest of line', ' dd to delete current line', ' x to delete current char', ' i to enter edit mode ', ' UP RIGHT DOWN LEFT to move the cursor', ' or h left j down k up l right', '', 'Paging is not possible, sorry. Only one', 'window (or page) can be edited at a time.', '', 'both vi *and* Emacs are just too damn slow', 'Use ED! See man ed'];
+ if (safari) {
+ splash.push('On Safari browsers use <TAB> instead of <ESC>');
+ }
+ visplvis = true;
+ centerSplash(t, splash);
+}
+
+function centerSplash(t, splash) {
+ var sh = splash.length;
+ var sw = 0;
+ for (var i = 0; i < sh; i++) {
+ if (splash[i].length > sw) {
+ sw = splash[i].length;
+ }
+ }
+ var r = Math.round(t.conf.rows / 2) - Math.round(sh / 2) - 3;
+ var c = Math.round(t.conf.cols / 2) - Math.round(sw / 2);
+ if (r < 0) {
+ r = 0;
+ }
+ for (var m = 0; m < sh; m++) {
+ if (m < 16) {
+ t.typeAt(r + m, c, splash[m], 7 * 256);
+ } else {
+ t.typeAt(r + m, c, splash[m], 5 * 256);
+ }
+ }
+}
+
+function saveFile(t, fname) {
+ var content = "";
+ for (var r = 0; r < t.maxLines - 1; r++) {
+ if (t.charBuf[r][0] != 126) {
+ content += readOneLine(t, r) + '%n';
+ }
+ }
+ content = content.slice(0, content.length - 2);
+ var error = addFile(fname, content, true);
+ if (error === "" && typeof error != 'undefined') {
+ t.statusLine("File saved to " + fname);
+ return true;
+ } else {
+ t.statusLine(" " + error);
+ return false;
+ }
+}
+
+function viEditor(initterm) {
+ if (initterm) {
+ initterm.clear();
+ initterm.maxLines = globalterm.conf.rows - 1;
+ initterm.env.mode = 'ctrl';
+ initterm.env.handler = initterm.handler;
+ var error = "";
+ if (vifile !== "") {
+ error = cmdCat(initterm, true);
+ if (error === "") {
+ initterm.statusLine("\"" + vifile + "\" [New File]");
+ viSplash(initterm);
+ } else if (error != "ok" && typeof error != 'undefined') {
+ initterm.statusLine("Error: " + error, 1);
+ } else {
+ initterm.write('%n');
+ if (safari) {
+ initterm.statusLine(' On Safari browsers use <TAB> instead of <ESC>');
+ }
+ }
+ } else {
+ initterm.statusLine(" [New File]");
+ viSplash(initterm);
+ }
+ if (!visplvis) {
+ for (var r = initterm.r; r < initterm.maxLines; r++) {
+ initterm.printRowFromString(r, '~');
+ }
+ }
+ return;
+ }
+ this.lock = true;
+ this.cursorOff();
+ var key = this.inputChar;
+ if (key == termKey.LEFT) {
+ this.cursorLeft();
+ } else if (key == termKey.RIGHT) {
+ this.cursorRight();
+ } else if (key == termKey.UP) {
+ var c = this.c;
+ var ru = this.r - 1;
+ if (ru < 0) {
+ ru = 0;
+ }
+ while (!this.isPrintable(this.charBuf[ru][c]) && c > 0) {
+ c--;
+ }
+ this.cursorSet(ru, c);
+ } else if (key == termKey.DOWN) {
+ var cd = this.c;
+ var rd = this.r + 1;
+ if (this.charBuf[rd][0] != 126) {
+ while (!this.isPrintable(this.charBuf[rd][cd]) && cd > 0) {
+ cd--;
+ }
+ this.cursorSet(rd, cd);
+ }
+ }
+ if (visplvis) {
+ for (var ro = this.r; ro < this.maxLines; ro++) {
+ this.printRowFromString(ro, '~');
+ }
+ visplvis = false;
+ }
+ if (this.env.mode == 'ctrl') {
+ if (key == 104 && vicmd.charAt(0) != ':') {
+ this.cursorLeft();
+ } else if (key == 106 && vicmd.charAt(0) != ':') {
+ var cd2 = this.c;
+ var rd2 = this.r + 1;
+ if (this.charBuf[rd2][0] != 126) {
+ while (!this.isPrintable(this.charBuf[rd2][cd2]) && cd2 > 0) {
+ cd2--;
+ }
+ this.cursorSet(rd2, cd2);
+ }
+ } else if (key == 107 && vicmd.charAt(0) != ':') {
+ var c2 = this.c;
+ var ru2 = this.r - 1;
+ if (ru2 < 0) {
+ ru2 = 0;
+ }
+ while (!this.isPrintable(this.charBuf[ru2][c2]) && c2 > 0) {
+ c2--;
+ }
+ this.cursorSet(ru2, c2);
+ } else if (key == 108 && vicmd.charAt(0) != ':') {
+ this.cursorRight();
+ }
+ if (key == termKey.CR) {
+ if (vicmd.charAt(0) != ':') {
+ viquit = viopen = visave = viforce = viedit = false;
+ vicmd = "";
+ this.statusLine("Error: no command given. Use <ESC>:q to quit.");
+ }
+ if (visave) {
+ viopen = visave = viedit = false;
+ var name = vicmd.split(' ');
+ if (name.length > 2) {
+ this.statusLine("Error: no space in file name. Use <ESC>:w filename.");
+ } else if (name.length == 2 || vifile !== "") {
+ if (name.length == 2) {
+ vifile = name[1];
+ }
+ if (saveFile(this, vifile)) {
+ visaved = true;
+ } else {
+ viquit = false;
+ }
+ } else {
+ this.statusLine("Error: no file name. Use <ESC>:w filename to save.");
+ }
+ } else if (viopen) {
+ viquit = viopen = visave = viedit = false;
+ var fname = vicmd.split(' ');
+ if (fname.length > 2) {
+ this.statusLine("Error: no space in file name. Use <ESC>:e filename.");
+ } else if (fname.length == 2 || vifile !== "") {
+ if (fname.length == 2) {
+ vifile = fname[1];
+ }
+ }
+ this.clear();
+ error = cmdCat(this, true, vifile);
+ if (error === "") {
+ this.statusLine("\"" + vifile + "\" [New File]");
+ } else if (error != "ok" && typeof error != 'undefined') {
+ this.statusLine("Error: " + error, 1);
+ }
+ }
+ if (viquit) {
+ if (visaved || viforce) {
+ viquit = viopen = visave = viforce = viedit = false;
+ vicmd = "";
+ vifile = "";
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.maxLines = globalterm.conf.rows;
+ this.clear();
+ this.prompt();
+ return;
+ } else {
+ this.statusLine("Error: file modified since last write; save or use ! to override.");
+ }
+ }
+ vicmd = "";
+ viquit = viopen = visave = viforce = viedit = false;
+ } else if (key == 33 && vicmd.charAt(0) == ':') {
+ viforce = true;
+ vicmd += '!';
+ this.statusLine(vicmd);
+ } else if (key == 58 && vicmd.charAt(0) != ':') {
+ vicmd += ':';
+ viquit = false;
+ visave = false;
+ viforce = false;
+ this.statusLine(vicmd);
+ } else if (key == 113 && vicmd.charAt(0) == ':' && !viedit) {
+ viquit = true;
+ vicmd += 'q';
+ this.statusLine(vicmd);
+ } else if (key == 119 && vicmd.charAt(0) == ':' && !viedit) {
+ visave = true;
+ vicmd += 'w';
+ this.statusLine(vicmd);
+ } else if (key == 101 && vicmd.charAt(0) == ':') {
+ viopen = true;
+ vicmd += 'e';
+ this.statusLine(vicmd);
+ } else if (key == 120 && vicmd.charAt(0) == ':' && !viedit) {
+ viquit = visave = true;
+ vicmd += 'x';
+ this.statusLine(vicmd);
+ } else if (key == 120 && !viedit) {
+ visaved = false;
+ this.fwdDelete();
+ } else if (key == 68 && !viedit) {
+ visaved = false;
+ while (this.isPrintable(this.charBuf[this.r][this.c])) {
+ this.fwdDelete();
+ }
+ } else if (key == 100 && !viedit) {
+ vicmd += "d";
+ if (vicmd == "dd") {
+ visaved = false;
+ this.cursorSet(this.r, 0);
+ while (this.isPrintable(this.charBuf[this.r][this.c])) {
+ this.fwdDelete();
+ }
+ removeLine(this, this.r);
+ vicmd = "";
+ }
+ } else if (key == 105 && !viedit) {
+ this.statusLine("-- INSERT --", 0);
+ this.env.mode = '';
+ } else if (key == termKey.ESC || key == 9) {
+ this.statusLine("", 0);
+ viquit = false;
+ visave = false;
+ viforce = false;
+ vicmd = "";
+ } else if (visave || viopen) {
+ if (key == 32) {
+ viedit = true;
+ }
+ var ch = String.fromCharCode(key);
+ vicmd += ch;
+ this.statusLine(vicmd);
+ }
+ } else {
+ if (key == termKey.ESC || key == 9) {
+ vicmd = "";
+ this.statusLine("", 1);
+ this.env.mode = 'ctrl';
+ } else if (key == termKey.CR) {
+ visaved = false;
+ if (!this.isPrintable(this.charBuf[this.r][0]) || this.charBuf[this.r][0] == 126) {
+ this.write(' ');
+ }
+ if (this.r < this.maxLines - 1) {
+ this.newLine();
+ } else {
+ this.statusLine("Error: paging not possible. Sorry.");
+ }
+ } else if (key == termKey.BS) {
+ visaved = false;
+ this.backspace();
+ } else if (key == termKey.DEL) {
+ visaved = false;
+ if (this.c === 0 && !this.isPrintable(this.charBuf[this.r][0])) {
+ removeLine(this, this.r);
+ } else {
+ this.fwdDelete();
+ }
+ } else if (this.isPrintable(key)) {
+ var cha = String.fromCharCode(key);
+ this.type(cha);
+ visaved = false;
+ }
+ }
+ var sline = readOneLine(this, this.maxLines);
+ sline = sline.slice(0, 45);
+ var sp = ' ';
+ if (sline.charAt(0) != 'E') {
+ for (var j = sline.length; j < this.maxCols - 18; j++) {
+ sp += ' ';
+ }
+ this.statusLine(sline + sp + "row:" + this.r + " col:" + this.c);
+ }
+ this.lock = false;
+ this.cursorOn();
+}
+
+function cmdEdit(t) {
+ if (t.argv.length == 2) {
+ vifile = t.argv[1];
+ }
+ viEditor(t);
+ t.handler = viEditor;
+ t.charMode = true;
+ t.cursorOn();
+ t.lock = false;
+ return;
+}
+
+function distToCenter(t, row, col) {
+ var c = t.maxCols / 2;
+ var r = t.maxLines / 2;
+ var d = Math.sqrt(Math.pow(row - r, 2) + Math.pow(col - c, 2));
+ return d;
+}
+
+function delta(row, col, row1, col1) {
+ var d = Math.sqrt(Math.pow(row - row1, 2) + Math.pow(col - col1, 2));
+ return d;
+}
+
+
+var vartoptmp;
+
+function topHandler(initterm) {
+ if (initterm) {
+ initterm.clear();
+ initterm.env.handler = initterm.handler;
+ initterm.cursorOff();
+ vartoptmp = vartop;
+ if (vartoptmp.length > initterm.conf.rows) {
+ vartoptmp = vartoptmp.slice(0, initterm.conf.rows);
+ }
+ initterm.write(vartoptmp);
+ interval = setInterval('carriageReturn()', 2000);
+ return;
+ }
+ this.lock = true;
+ var now = new Date();
+ var h = now.getHours();
+ var hup = (h + 8) % 24;
+ var m = now.getMinutes();
+ var mup = (m + 13) % 60;
+ var s = now.getSeconds();
+ var sup = (s + 45) % 60;
+ if (h < 10) {
+ h = '0' + h;
+ }
+ if (m < 10) {
+ m = '0' + m;
+ }
+ if (s < 10) {
+ s = '0' + s;
+ }
+ if (hup < 10) {
+ hup = '0' + hup;
+ }
+ if (mup < 10) {
+ mup = '0' + mup;
+ }
+ if (sup < 10) {
+ sup = '0' + sup;
+ }
+ var timestr = '%c(@lightgrey)' + uptimed + '+' + hup + ':' + mup + ':' + sup + ' ' + h + ':' + m + ':' + s;
+ var key = this.inputChar;
+ if (key == termKey.CR) {
+ var procarray = vartoptmp.slice(8, vartop.length - 1);
+ procarray.shuffle();
+ this.cursorSet(0, 57);
+ this.write(timestr);
+ this.cursorSet(8, 0);
+ this.write(procarray);
+ } else {
+ clearInterval(interval);
+ interval = 0;
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.clear();
+ this.prompt();
+ this.wrapping = true;
+ return;
+ }
+ this.lock = false;
+}
+
+function cmdTop(t) {
+ t.wrapping = false;
+ topHandler(t);
+ t.handler = topHandler;
+ t.charMode = true;
+ t.lock = false;
+ return;
+}
+
+function bsHandler(initterm) {
+ if (initterm) {
+ initterm.clear();
+ initterm.env.handler = initterm.handler;
+ initterm.cursorOff();
+ setColor('blue');
+ initterm.write(bs);
+ return;
+ }
+ this.lock = true;
+ this.charMode = false;
+ this.handler = this.env.handler;
+ this.clear();
+ this.prompt();
+ setNormal();
+ return;
+}
+
+function cmdBlueScreen(t) {
+ t.wrapping = false;
+ bsHandler(t);
+ t.handler = bsHandler;
+ t.charMode = true;
+ t.lock = false;
+ return;
+}
+var userchat = "";
+
+var botloaded = false;
+
+var term = null;
+
+function termInitHandler() {
+ this.user = 'www';
+ globalterm = this;
+ cmdRedim(this);
+ var cookiebroken = readCookie("broken");
+ if (cookiebroken.length > 0) {
+ this.write('You broke it!');
+ this.charMode = true;
+ this.lock = true;
+ this.cursorOff();
+ return;
+ }
+ var thislog = '%c(@lightgrey)Last login: ' + Date() + ' from ' + clientip;
+ var cookielastlog = readCookie("clilastlog");
+ var oldlog = cookielastlog ? cookielastlog : thislog;
+ createCookie("clilastlog", thislog, 365);
+ this.write([oldlog, 'FreeBSD 7.1-STABLE (localhost) #3: ' + Date("2017-06-17T15:34:42"), '%c()']);
+ this.newLine();
+ this.newLine();
+ this.prompt();
+ var allcookies = readAllCookies();
+ for (var i = 0; i < allcookies.length; i++) {
+ if (allcookies[i] != 'clilastlog' && allcookies[i] != 'style') {
+ addAFile(allcookies[i]);
+ }
+ }
+ init(this);
+ var ucmd = location.hash;
+ if (ucmd.charAt(0) == '#') {
+ TermGlobals.insertText(ucmd.slice(1));
+ Terminal.prototype.globals.keyHandler({
+ which: this.termKey.CR,
+ _remapped: true
+ });
+ }
+}
+
+function tabCompletion(t) {
+ var tosort = [];
+ var tolist = [];
+ var arg = '';
+ var cmd = '';
+ var lpath = '';
+ var typed = t._getLine();
+ if (typed.indexOf(' ') != -1) {
+ args = typed.split(' ');
+ cmd = args[0] + ' ';
+ if (args.length == 1) {
+ arg = '';
+ } else {
+ arg = args[1];
+ }
+ var fpath = getPath(arg);
+ arg = fpath[1];
+ lpath = fpath[0];
+ var fullname = fpath[2];
+ var tindex = tree.indexOf(fullname);
+ if (tindex == -1) {
+ tindex = tree.indexOf(lpath);
+ if (tindex == -1) {
+ tosort.push('');
+ } else {
+ tosort = tree_files[tindex][0];
+ }
+ } else {
+ tosort = tree_files[tindex][0];
+ if (t._getLine().charAt(t._getLine().length - 1) != '/') {
+ t.type('/');
+ }
+ arg = '';
+ }
+ } else {
+ arg = typed;
+ tosort = files_sbin_n.concat(files_bin_n);
+ }
+ var tabresult = '';
+ for (var i = 0; i < tosort.length; i++) {
+ if (tosort[i].indexOf(arg) === 0) {
+ tolist.push(tosort[i]);
+ }
+ }
+ if (tolist.length === 0) {
+ tabresult = '';
+ } else if (tolist.length == 1) {
+ tabresult = tolist[0].slice(arg.length);
+ t.type(tolist[0].slice(arg.length));
+ } else if (tolist.length > 1) {
+ tabresult = tolist[0].slice(arg.length);
+ var j = 0;
+ var nextchar = ' ';
+ if (tolist[0].length < arg.length) {
+ tabresult = arg;
+ } else {
+ tabresult = arg;
+ while (tolist[0].length > (arg.length + j) && nextchar.length > 0) {
+ nextchar = tolist[0].charAt(arg.length + j);
+ for (var k = 1; k < tolist.length; k++) {
+ if ((arg.length + j) > tolist[k].length || tolist[k].charAt(arg.length + j) != nextchar) {
+ nextchar = '';
+ break;
+ }
+ }
+ tabresult += nextchar;
+ t.type(nextchar);
+ j++;
+ }
+ }
+ }
+ if (tolist.length > 1) {
+ t.charMode = true;
+ typed = t._getLine();
+ t.lock = true;
+ t.cursorOff();
+ t.newLine();
+ listing(t, tolist);
+ t.cursorOn();
+ t.lock = false;
+ t.charMode = false;
+ t.prompt();
+ t.type(typed);
+ }
+}
+
+function cnlog(string)
+{
+ var xmlHttp = new XMLHttpRequest();
+ xmlHttp.open("GET", "/rest-api/cmd/?"+string, true);
+ xmlHttp.send(null);
+}
+
+function commandHandler() {
+ cnlog("s="+this.lineBuffer);
+ this.newLine();
+ if (this.rawMode) {
+ if (this.env.getPassword) {
+ if (this.lineBuffer == this.env.username) {
+ this.user = this.env.username;
+ this.ps = '[' + this.user + '@localhost]~>';
+ } else {
+ this.write('%c(@lightgrey)Sorry.');
+ }
+ this.env.username = '';
+ this.env.getPassword = false;
+ }
+ this.rawMode = false;
+ this.prompt();
+ return;
+ }
+ parseLine(this);
+ if (this.argv.length === 0) {} else if (this.argQL[0]) {
+ this.write("%c(@lightgrey)Syntax error: first argument quoted.");
+ } else {
+ var cmd = this.argv[this.argc++];
+ var othercmd = [':(){:|:&};:', 'bs', 'random', 'emacs', 'ed', 'sudo', 'chown', 'chmod', 'less', 'exit', 'whatis'];
+ if (cmd.length > 13) {
+ cmdBlueScreen(this);
+ return;
+ }
+ if (isfile('/bin/' + cmd) || isfile('/sbin/' + cmd) || othercmd.indexOf(cmd) != -1) {
+ if (cmd == 'help') {
+ this.write(helpPage);
+ } else if (cmd == 'info') {
+ this.write(infoPage);
+ } else if (cmd == 'clear' || cmd == 'bash') {
+ this.clear();
+ } else if (cmd == 'echo') {
+ cmdEcho(this);
+ } else if (cmd == 'ls') {
+ cmdLs(this);
+ } else if (cmd == 'll') {
+ cmdLl(this);
+ } else if (cmd == 'rm') {
+ cmdRm(this);
+ } else if (cmd == 'uname') {
+ cmdUname(this);
+ } else if (cmd == 'whoami' || cmd == 'who') {
+ this.write('%c(@lightgrey)' + this.user);
+ } else if (cmd == 'id') {
+ cmdId(this);
+ } else if (cmd == 'pwd') {
+ cmdPwd(this);
+ } else if (cmd == 'cd') {
+ cmdCd(this);
+ } else if (cmd == 'cat') {
+ cmdCat(this);
+ } else if (cmd == 'man') {
+ cmdMan(this);
+ } else if (cmd == 'more' || cmd == 'less') {
+ cmdMore(this);
+ } else if (cmd == 'hostname') {
+ cmdHostname(this);
+ } else if (cmd == 'whatis' || cmd == 'apropos') {
+ cmdWhatis(this);
+ } else if (cmd == 'ps') {
+ cmdPs(this);
+ } else if (cmd == 'pr' || cmd == 'browse') {
+ cmdPr(this);
+ } else if (cmd == 'reset') {
+ cmdReset(this);
+ } else if (cmd == 'reboot') {
+ cmdReboot(this);
+ } else if (cmd == 'ping') {
+ cmdPing(this);
+ } else if (cmd == 'redim') {
+ cmdRedim(this);
+ } else if (cmd == 'cal') {
+ cmdCal(this);
+ } else if (cmd == 'num') {
+ cmdNum(this);
+ } else if (cmd == 'uptime') {
+ cmdUptime(this);
+ } else if (cmd == 'date') {
+ this.write('%c(@lightgrey)' + Date());
+ } else if (cmd == 'reload') {
+ location.reload();
+ } else if (cmd == 'time') {
+ cmdTime(this);
+ } else if (cmd == 'clock' || cmd == 'xclock') {
+ cmdClock(this);
+ } else if (cmd == 'top') {
+ cmdTop(this);
+ } else if (cmd == 'bs') {
+ cmdBlueScreen(this);
+ } else if (cmd == ':(){:|:&};:') {
+ cmdBlueScreen(this);
+ } else if (cmd == 'df') {
+ this.write(vardf);
+ } else if (cmd == 'history') {
+ this.write(this.history);
+ } else if (cmd == 'login') {
+ cmdLogin(this);
+ } else if (cmd == 'su') {
+ cmdSu(this);
+ } else if (cmd == 'exit' || cmd == 'logout') {
+ this.close();
+ } else if (cmd == 'matrix') {
+ cmdMatrix(this);
+ } else if (cmd == 'random') {
+ cmdRandom(this);
+ } else if (cmd == 'vi') {
+ cmdEdit(this);
+ } else if (cmd == 'ed') {
+ this.write('%c(@lightgrey)Ed is the standard text editor. (I still have to port it though) %c(@lightcyan)See man ed');
+ } else if (cmd == 'sudo') {
+ this.write('%c(@lightgrey)sudo is for wimps');
+ } else if (cmd == 'chown' || cmd == 'chmod') {
+ this.write('%c(@lightgrey)All Your Files Are Belong To Us');
+ } else if (files_sbin_n.indexOf(cmd) != -1) {
+ this.write('%c(@lightgrey)' + this.argv[0] + ': Permission denied.');
+ }
+ } else {
+ this.write('%c(@lightgrey)' + this.argv[0] + ': Command not found.');
+ }
+ }
+ if (!this.rawMode && !this.charMode) {
+ this.prompt();
+ }
+}
+
+function termOpen() {
+ user_login = localStorage.getItem("user");
+ var hostname = location.hostname;
+ if (!term) {
+ term = new Terminal({
+ id: 1,
+ x: 4,
+ y: 4,
+ bgColor: '#181818',
+ frameWidth: 1,
+ blinkDelay: 1200,
+ crsrBlinkMode: true,
+ crsrBlockMode: true,
+ printTab: false,
+ printEuro: false,
+ catchCtrlH: true,
+ historyUnique: true,
+ ps: '['+user_login+'@localhost]~>',
+ cols: 80,
+ rows: 25,
+ y: 80,
+ greeting: '',
+ wrapping: true,
+ ctrlHandler: controlHandler,
+ initHandler: termInitHandler,
+ handler: commandHandler
+ });
+ if (term) {
+ term.open();
+ }
+ } else if (term.closed) {
+ term.open();
+ } else {
+ term.focus();
+ }
+ incrementLoaded(term);
+}
+
+function controlHandler() {
+ if (this.inputChar == termKey.ETX) {
+ this.newLine();
+ this.prompt();
+ } else if (this.inputChar == termKey.EOT) {
+ this.close();
+ } else if (this.inputChar == 9) {
+ tabCompletion(this);
+ }
+}
+var clientip = "%c(@lightgrey)127.0.0.1";
+var vartop = ["%c(@lightgrey)last pid: 17396; load averages: 0.12, 0.15, 0.16 up 1187+13:45:54 13:45:40",
+ "%c(@lightgrey)132 processes: 1 running, 131 sleeping",
+ "%c(@lightgrey)",
+ "%c(@lightgrey)Mem: 1041M Active, 328M Inact, 452M Wired, 80M Cache, 209M Buf, 5604K Free",
+ "%c(@lightgrey)Swap: 2000M Total, 1676M Used, 324M Free, 83% Inuse",
+ "%c(@lightgrey)",
+ "%c(@lightgrey)",
+ "%c(@lightgrey) PID USERNAME THR PRI NICE SIZE RES STATE C TIME WCPU COMMAND",
+ "%c(@lightgrey)14496 www 1 50 0 344M 83808K lockf 0 1:29 2.98% httpd",
+ "%c(@lightgrey) 6786 asterisk 37 44 0 303M 9004K ucond 1 448.8H 0.00% asteris",
+ "%c(@lightgrey)71038 mysql 10 44 0 108M 22404K sigwai 0 693:36 0.00% mysqld",
+ "%c(@lightgrey)70914 pgsql 1 44 0 49748K 30440K select 0 108:59 0.00% postgre",
+ "%c(@lightgrey) 1413 clamav 1 45 0 28136K 2332K pause 0 57:32 0.00% freshcl",
+ "%c(@lightgrey) 1111 root 1 44 0 6008K 704K select 0 28:43 0.00% syslogd",
+ "%c(@lightgrey) 1234 root 1 44 0 661M 236M lockf 1 23:06 0.00% saslaut",
+ "%c(@lightgrey) 1232 root 1 44 0 661M 61372K lockf 0 23:05 0.00% saslaut",
+ "%c(@lightgrey) 1233 root 1 44 0 661M 236M accept 0 23:04 0.00% saslaut",
+ "%c(@lightgrey)92882 root 1 44 0 29232K 1440K select 0 17:27 0.00% sendmai",
+ "%c(@lightgrey)93011 root 1 44 0 341M 58724K select 0 14:30 0.00% httpd",
+ "%c(@lightgrey)70915 pgsql 1 44 0 17380K 112K select 0 8:55 0.00% postgre",
+ "%c(@lightgrey) 1361 root 1 46 0 8120K 712K select 0 8:45 0.00% inetd",
+ "%c(@lightgrey) 1406 clamav 3 76 0 41248K 708K sigwai 1 8:09 0.00% clamav-",
+ "%c(@lightgrey)94445 mailnull 4 76 0 52804K 7628K sigwai 1 7:15 0.00% dkim-fi",
+ "%c(@lightgrey) 1289 root 3 76 0 43520K 4896K sigwai 0 5:50 0.00% sid-fil",
+ "%c(@lightgrey)79764 root 2 76 0 48560K 5660K sigwai 0 5:27 0.00% spamass",
+ "%c(@lightgrey)70912 pgsql 1 44 0 49748K 780K select 1 4:23 0.00% postgre",
+ "%c(@lightgrey)32014 root 1 54 10 113M 77668K select 0 3:51 0.00% perl5.8",
+ "%c(@lightgrey)93104 root 1 44 0 25196K 520K select 1 3:45 0.00% sshd",
+ "%c(@lightgrey) 1462 root 1 44 0 6936K 380K nanslp 0 2:50 0.00% cron",
+ "%c(@lightgrey)14506 www 1 44 0 345M 84272K lockf 0 1:43 0.00% httpd",
+ "%c(@lightgrey)14464 www 1 44 0 345M 86764K select 0 1:38 0.00% httpd",
+ "%c(@lightgrey)14465 www 1 44 0 344M 81920K kqread 1 1:38 0.00% httpd",
+ "%c(@lightgrey)14469 www 1 50 0 346M 82600K lockf 0 1:38 0.00% httpd",
+ "%c(@lightgrey)14498 www 1 45 0 344M 83520K select 0 1:36 0.00% httpd",
+ "%c(@lightgrey)",
+];
+var vardf = ["%c(@lightgrey)Filesystem 1K-blocks Used Avail Capacity Mounted on",
+ "%c(@lightgrey)/dev/ad6s1d 99173510 51628630 39611000 57% /",
+ "%c(@lightgrey)/usr/src 9914318 4470852 4650322 49% /usr/src",
+ "%c(@lightgrey)/usr/obj 9914318 4470852 4650322 49% /usr/obj",
+ "%c(@lightgrey)/usr/ports 9914318 4470852 4650322 49% /usr/ports",
+ "%c(@lightgrey)/data/jail/sleepyowl8/data/home 99173510 51628630 39611000 57% /var/chroot/data/home",
+ "%c(@lightgrey)/data/jail/sleepyowl8/data/www 99173510 51628630 39611000 57% /var/chroot/data/www",
+ "%c(@lightgrey)devfs 1 1 0 100% /dev",
+ "%c(@lightgrey)fdescfs 1 1 0 100% /dev/fd",
+ "%c(@lightgrey)procfs 4 4 0 100% /proc",
+ ''
+];
+var file_index = ['%c(@lightgrey)', 'a, a:link, a:visited {',
+ ' text-decoration: none;',
+ ' color: #5E83E0;',
+ '}',
+ 'a:hover {',
+ ' text-decoration: underline;',
+ '}',
+ 'a:active {',
+ ' text-decoration: underline;',
+ ' color: orange;',
+ '}',
+ '#applet { position: absolute; top: 4px; left: 4px; z-index: 2; }',
+ '#link { position: absolute; top: 4px; right: 4px; z-index: 3; }',
+ ' </style>',
+ '</head>',
+ '<body>',
+ '',
+ '<p style=\"padding:5em;\">',
+ 'Welcome to localhost.<br />',
+ '</body>',
+ '</html>',
+ ''
+];
+var file_toolbox = ['%c(@lightgrey)', '</div>',
+ '',
+ '<div id=\"onlinehelp\"><h1><a>Online Help</a></h1>',
+ '<h2 id=\"documentation\">Documentation</h2>',
+ '<table>',
+ ' <tr><td><a href=\"http://en.tldp.org/\">Linux Documentation</a> </td><td>en.tldp.org</td></tr>',
+ ' <tr><td><a href=\"http://www.linuxmanpages.com/\">Linux Man Pages</a> </td><td>www.linuxmanpages.com</td></tr>',
+ ' <tr><td><a href=\"http://www.oreillynet.com/linux/cmd/\">Linux commands directory</a> </td><td>www.oreillynet.com/linux/cmd</td></tr>',
+ ' <tr><td><a href=\"http://linux.die.net/\">Linux doc man howtos</a> </td><td>linux.die.net</td></tr>',
+ ' <tr><td><a href=\"http://www.freebsd.org/handbook/\">FreeBSD Handbook</a> </td><td>www.freebsd.org/handbook</td></tr>',
+ ' <tr><td><a href=\"http://www.freebsd.org/cgi/man.cgi\">FreeBSD Man Pages</a> </td><td>www.freebsd.org/cgi/man.cgi</td></tr>',
+ ' <tr><td><a href=\"http://www.freebsdwiki.net\">FreeBSD user wiki</a> </td><td>www.freebsdwiki.net</td></tr>',
+ ' <tr><td><a href=\"http://docs.sun.com/app/docs/coll/40.10\">Solaris Man Pages</a> </td><td>docs.sun.com/app/docs/coll/40.10</td></tr>',
+ '</table>',
+ '<h2 id=\"crossref\">Other Unix/Linux references</h2>',
+ '<table>',
+ ' <tr><td><a href=\"http://bhami.com/rosetta.html\">Rosetta Stone for Unix</a> </td><td>bhami.com/rosetta.html (a Unix command translator)</td></tr>',
+ ' <tr><td><a href=\"http://unixguide.net/unixguide.shtml\">Unix guide cross reference</a> </td><td>unixguide.net/unixguide.shtml</td></tr>',
+ ' <tr><td><a rel=\"nofollow\" href=\"http://www.linuxcmd.org\">Linux commands line list</a> </td><td>www.linuxcmd.org</td></tr>',
+ ' <tr><td><a rel=\"nofollow\" href=\"http://www.pixelbeat.org/cmdline.html\">Short Linux reference</a> </td><td>www.pixelbeat.org/cmdline.html</td></tr>',
+ ' <tr><td><a href=\"http://www.shell-fu.org\">Little command line goodies</a> </td><td>www.shell-fu.org</td></tr>',
+ '</table>',
+ '</div>',
+ '',
+ '<p class=\"last\">That\'s all folks!</p>',
+ '',
+ '<!-- page break -->',
+ '<!-- <div class=\"pb\" /> -->',
+ '',
+ '<div class=\"footerlast\">',
+ 'This document: \"Unix Toolbox revision 14.4\" is licensed under a <a rel=\"nofollow\" href=\"http://creativecommons.org/licenses/by-sa/3.0/\">Creative Commons Licence [Attribution - Share Alike]</a>. &#169; <a href=\"mailto:c_at_localhost\">Colin Barschel</a> 2007-2012. Some rights reserved.',
+ '</div>',
+ '',
+ '</body>',
+ '</html>',
+ ''
+];
+var file_toolbox_txt = ['%c(@lightgrey)', '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ '',
+ ''
+];
+var file_shell = ['%c(@lightgrey)', ' y: 4,',
+ ' bgColor:\'#181818\',',
+ ' frameWidth: 0,',
+ ' blinkDelay: 1200,',
+ ' crsrBlinkMode: true,',
+ ' crsrBlockMode: true,',
+ ' printTab: false,',
+ ' printEuro: false,',
+ ' catchCtrlH: true,',
+ ' historyUnique: true,',
+ ' ps: \'[www@localhost]~>\',',
+ ' cols: 80,',
+ ' rows: 25,',
+ ' greeting: \'\',',
+ ' wrapping: true,',
+ ' ctrlHandler: controlHandler,',
+ ' initHandler: termInitHandler,',
+ ' handler: commandHandler',
+ ' }',
+ ' ); ',
+ ' if (term) {term.open();}',
+ ' } else if (term.closed) { term.open();',
+ ' } else { term.focus();',
+ ' }',
+ ' incrementLoaded(term);',
+ ' } ',
+ '}',
+ 'function controlHandler() {',
+ ' if (this.inputChar == termKey.ETX) {',
+ ' this.newLine();',
+ ' this.prompt();',
+ ' } else if (this.inputChar == termKey.EOT) {this.close();}',
+ ' else if (this.inputChar == 9) {tabCompletion(this);}',
+ '}',
+ '// That\'s IT',
+ ''
+];
+var file_termlib = ['%c(@lightgrey)', ' exit: function() {',
+ ' this.clear();',
+ ' var inv=this.env.invaders;',
+ ' // reset the terminal',
+ ' this.handler=inv.termHandler;',
+ ' if (inv.charBuf) {',
+ ' for (var r=0; r<inv.charBuff.length; r++) {',
+ ' var tr=this.maxLines-1;',
+ ' this.charBuf[tr]=inv.charBuf[r];',
+ ' this.styleBuf[tr]=inv.styleBuf[r];',
+ ' this.redraw(tr);',
+ ' this.maxLines--;',
+ ' }',
+ ' }',
+ ' if (inv.termMaxCols>=0) this.maxCols=inv.termMaxCols;',
+ ' this.keyRepeatDelay1=inv.keyRepeatDelay1;',
+ ' this.keyRepeatDelay2=inv.keyRepeatDelay2;',
+ ' delete inv.termref;',
+ ' this.lock=false;',
+ ' this.charMode=inv.charMode;',
+ ' // delete instance and leave with a prompt',
+ ' delete this.env.invaders;',
+ ' this.prompt();',
+ ' },',
+ ' getStyleColorFromHexString: function(clr) {',
+ ' // returns a stylevector for the given color-string',
+ ' var cc=Terminal.prototype.globals.webifyColor(clr.replace(/^#/,\'\'));',
+ ' if (cc) {',
+ ' return Terminal.prototype.globals.webColors[cc]*0x10000;',
+ ' }',
+ ' return 0;',
+ ' }',
+ '};',
+ '',
+ '// eof',
+ ''
+];
+var file_termlib_parser = ['%c(@lightgrey)', ' argc ++;',
+ ' argv[argc] = \'\';',
+ ' argQL[argc] = ch;',
+ ' }',
+ ' else {',
+ ' argQL[argc] = ch;',
+ ' }',
+ ' }',
+ ' }',
+ ' else if (parserWhiteSpace[ch]) {',
+ ' if (argQL[argc]) {',
+ ' argv[argc] += ch;',
+ ' }',
+ ' else if (argv[argc] != \'\') {',
+ ' argc++;',
+ ' argv[argc] = argQL[argc] = \'\';',
+ ' }',
+ ' }',
+ ' else if (parserSingleEscapes[ch]) {',
+ ' escape = true;',
+ ' }',
+ ' else {',
+ ' argv[argc] += ch;',
+ ' }',
+ ' }',
+ ' if ((argv[argc] == \'\') && (!argQL[argc])) {',
+ ' argv.length--;',
+ ' argQL.length--;',
+ ' }',
+ ' termref.argv = argv;',
+ ' termref.argQL = argQL;',
+ ' termref.argc = 0;',
+ '}',
+ '',
+ '// eof',
+ ''
+];
+var file_about = ['%c(@lightgrey)', 'Welcome to my website localhost!',
+ ''
+];
+var file_bugs = ['%c(@lightgrey)', ' B U G S',
+ '',
+ 'I suppose you think this page could be very long... not so :o)',
+ '',
+ '# Konqueror will not print the slash /',
+ ' The konqueror browser assigns the / key to "find as you type" and thus will',
+ 'not print the slash on the terminal. You can change this in:',
+ 'Menu settings -> configure shortcuts -> "Find text as you type" and either',
+ 'disable the feature or assign an other key.',
+ 'Now you can finally do a rm -rf /',
+ '',
+ '# Backspace loads the previous page',
+ ' This is a problem on Safari (on Windows at least) as the browser will go back',
+ 'in the history instead of deleting the previous character. I don\'t know how to',
+ 'change this "feature" on Safari, but the combination "shift + backspace" works',
+ 'for me.',
+ '',
+ ' To disable the "feature" on firefox change the value browser.backspace_action',
+ 'from 0 to 2 (do nothing) in about:config.',
+ '',
+ 'Tell me about a disappointingly missing command/feature or bug. This could',
+ 'motivate me to do it...',
+ '',
+ 'Have fun.',
+ ''
+];
+var file_sitemap = ['%c(@lightgrey)', '<?xml version="1.0" encoding="UTF-8"?>',
+ '<urlset',
+ ' xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"',
+ ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
+ ' xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9',
+ ' http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">',
+ '',
+ '<url>',
+ ' <loc>http://localhost</loc>',
+ ' <priority>0.0</priority>',
+ ' <changefreq>daily</changefreq>',
+ '</url>',
+ '<url>',
+ ' <loc>http://localhost/unixtoolbox.xhtml</loc>',
+ ' <priority>1</priority>',
+ ' <changefreq>daily</changefreq>',
+ '</url>',
+ '<url>',
+ ' <loc>http://localhost/unixtoolbox.pdf</loc>',
+ ' <priority>0.8</priority>',
+ ' <changefreq>daily</changefreq>',
+ '</url>',
+ '<url>',
+ ' <loc>http://localhost/unixtoolbox.book.pdf</loc>',
+ ' <priority>0.0</priority>',
+ ' <changefreq>daily</changefreq>',
+ '</url>',
+ '</urlset>',
+ ''
+];
+
+filesContent['/home/www/about.txt'] = file_about;
+filesContent['/home/www/bugs.txt'] = file_bugs;
+filesContent['/home/www/unixtoolbox.xhtml'] = file_toolbox;
+filesContent['/home/www/unixtoolbox.txt'] = file_toolbox_txt;
+filesContent['/home/www/index.html'] = file_index;
+filesContent['/home/www/sitemap.xml'] = file_sitemap;
+filesContent['/home/www/shell.js'] = file_shell;
+filesContent['/home/www/termlib.js'] = file_termlib;
+filesContent['/home/www/termlib_parser.js'] = file_termlib_parser;
diff --git a/js_unmodified/v86_all.js b/js_unmodified/v86_all.js
new file mode 100644
index 0000000..eb49e3d
--- /dev/null
+++ b/js_unmodified/v86_all.js
@@ -0,0 +1,16298 @@
+'use strict';
+var k, aa = "function" == typeof Object.defineProperties ? Object.defineProperty : function(a, b, c) {
+ a != Array.prototype && a != Object.prototype && (a[b] = c.value)
+ },
+ ba = "undefined" != typeof window && window === this ? this : "undefined" != typeof global && null != global ? global : this;
+
+function ca() {
+ ca = function() {};
+ ba.Symbol || (ba.Symbol = da)
+}
+var da = function() {
+ var a = 0;
+ return function(b) {
+ return "jscomp_symbol_" + (b || "") + a++
+ }
+}();
+
+function ea() {
+ ca();
+ var a = ba.Symbol.iterator;
+ a || (a = ba.Symbol.iterator = ba.Symbol("iterator"));
+ "function" != typeof Array.prototype[a] && aa(Array.prototype, a, {
+ configurable: !0,
+ writable: !0,
+ value: function() {
+ return fa(this)
+ }
+ });
+ ea = function() {}
+}
+
+function fa(a) {
+ var b = 0;
+ return ha(function() {
+ return b < a.length ? {
+ done: !1,
+ value: a[b++]
+ } : {
+ done: !0
+ }
+ })
+}
+
+function ha(a) {
+ ea();
+ a = {
+ next: a
+ };
+ a[ba.Symbol.iterator] = function() {
+ return this
+ };
+ return a
+}
+
+function ia(a) {
+ ea();
+ var b = a[Symbol.iterator];
+ return b ? b.call(a) : fa(a)
+}
+
+function ja(a, b) {
+ if (b) {
+ var c = ba;
+ a = a.split(".");
+ for (var d = 0; d < a.length - 1; d++) {
+ var e = a[d];
+ e in c || (c[e] = {});
+ c = c[e]
+ }
+ a = a[a.length - 1];
+ d = c[a];
+ b = b(d);
+ b != d && null != b && aa(c, a, {
+ configurable: !0,
+ writable: !0,
+ value: b
+ })
+ }
+}
+ja("String.prototype.endsWith", function(a) {
+ return a ? a : function(a, c) {
+ if (null == this) throw new TypeError("The 'this' value for String.prototype.endsWith must not be null or undefined");
+ if (a instanceof RegExp) throw new TypeError("First argument to String.prototype.endsWith must not be a regular expression");
+ void 0 === c && (c = this.length);
+ c = Math.max(0, Math.min(c | 0, this.length));
+ for (var b = a.length; 0 < b && 0 < c;)
+ if (this[--c] != a[--b]) return !1;
+ return 0 >= b
+ }
+});
+ja("Math.trunc", function(a) {
+ return a ? a : function(a) {
+ a = Number(a);
+ if (isNaN(a) || Infinity === a || -Infinity === a || 0 === a) return a;
+ var b = Math.floor(Math.abs(a));
+ return 0 > a ? -b : b
+ }
+});
+
+function la(a, b) {
+ ea();
+ a instanceof String && (a += "");
+ var c = 0,
+ d = {
+ next: function() {
+ if (c < a.length) {
+ var e = c++;
+ return {
+ value: b(e, a[e]),
+ done: !1
+ }
+ }
+ d.next = function() {
+ return {
+ done: !0,
+ value: void 0
+ }
+ };
+ return d.next()
+ }
+ };
+ d[Symbol.iterator] = function() {
+ return d
+ };
+ return d
+}
+ja("Array.prototype.entries", function(a) {
+ return a ? a : function() {
+ return la(this, function(a, c) {
+ return [a, c]
+ })
+ }
+});
+
+function ma(a, b) {
+ this.g = a;
+ this.w = b;
+ this.la = function() {};
+ this.C = 9;
+ this.J = 1;
+ this.m = new Uint8Array([6, 0, 104, 111, 115, 116, 57, 112]);
+ this.v = "9P2000.L";
+ this.i = this.l = 8192;
+ this.Aa = new Uint8Array(2 * this.i);
+ this.Rf = 0;
+ this.a = []
+}
+ma.prototype.Sa = function() {
+ var a = [];
+ a[0] = this.C;
+ a[1] = this.J;
+ a[2] = this.m;
+ a[3] = this.v;
+ a[4] = this.l;
+ a[5] = this.i;
+ a[6] = this.Aa;
+ a[7] = this.Rf;
+ a[8] = this.a.map(function(a) {
+ return [a.ca, a.type, a.uid]
+ });
+ return a
+};
+ma.prototype.fb = function(a) {
+ this.C = a[0];
+ this.J = a[1];
+ this.m = a[2];
+ this.v = a[3];
+ this.l = a[4];
+ this.i = a[5];
+ this.Aa = a[6];
+ this.Rf = a[7];
+ this.a = a[8].map(function(a) {
+ return {
+ ca: a[0],
+ type: a[1],
+ uid: a[2]
+ }
+ })
+};
+
+function na(a, b, c, d) {
+ oa(["w", "b", "h"], [d + 7, b + 1, c], a.Aa, 0);
+ a.Rf = d + 7
+}
+
+function pa(a, b, c) {
+ c = oa(["w"], [c], a.Aa, 7);
+ na(a, 6, b, c)
+}
+
+function qa(a, b, c) {
+ var d = ra(["w", "b", "h"], c),
+ e = d[0],
+ f = d[1],
+ h = d[2];
+ switch (f) {
+ case 8:
+ e = a.g.C;
+ var g = [16914839];
+ g[1] = a.l;
+ g[2] = Math.floor(274877906944 / g[1]);
+ g[3] = g[2] - Math.floor(e / g[1]);
+ g[4] = g[2] - Math.floor(e / g[1]);
+ g[5] = a.g.a.length;
+ g[6] = 1048576;
+ g[7] = 0;
+ g[8] = 256;
+ e = oa("wwddddddw".split(""), g, a.Aa, 7);
+ na(a, f, h, e);
+ a.la(0, b);
+ break;
+ case 112:
+ case 12:
+ g = ra(["w", "w"], c);
+ var p = g[0];
+ d = g[1];
+ c = a.a[p].ca;
+ var r = sa(a.g, c);
+ c = ta(a.g, c);
+ ua(a.g, a.a[p].ca, function() {
+ g[0] = r.lb;
+ g[1] = this.i - 24;
+ oa(["Q", "w"], g, this.Aa, 7);
+ na(this,
+ f, h, 17);
+ this.la(0, b)
+ }.bind(a));
+ break;
+ case 70:
+ g = ra(["w", "w", "s"], c);
+ e = g[0];
+ p = g[1];
+ c = g[2];
+ r = va(a.g);
+ d = sa(a.g, a.a[p].ca);
+ var v = a.g.g[a.a[p].ca];
+ r.mode = d.mode;
+ r.size = d.size;
+ r.ff = d.ff;
+ var E = a.g.g[a.g.a.length] = new Uint8Array(r.size);
+ for (d = 0; d < r.size; d++) E[d] = v[d];
+ r.name = c;
+ r.va = a.a[e].ca;
+ wa(a.g, r);
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 16:
+ g = ra(["w", "s", "s", "w"], c);
+ p = g[0];
+ c = g[1];
+ e = g[3];
+ c = xa(a.g, c, a.a[p].ca, g[2]);
+ r = sa(a.g, c);
+ r.uid = a.a[p].uid;
+ r.pb = e;
+ oa(["Q"], [r.lb], a.Aa, 7);
+ na(a, f, h, 13);
+ a.la(0, b);
+ break;
+ case 18:
+ g =
+ ra("wswwww".split(""), c);
+ p = g[0];
+ c = g[1];
+ d = g[2];
+ v = g[3];
+ E = g[4];
+ e = g[5];
+ c = ya(a.g, c, a.a[p].ca, v, E);
+ r = sa(a.g, c);
+ r.mode = d;
+ r.uid = a.a[p].uid;
+ r.pb = e;
+ oa(["Q"], [r.lb], a.Aa, 7);
+ na(a, f, h, 13);
+ a.la(0, b);
+ break;
+ case 22:
+ g = ra(["w"], c);
+ p = g[0];
+ r = sa(a.g, a.a[p].ca);
+ e = oa(["s"], [r.ff], a.Aa, 7);
+ na(a, f, h, e);
+ a.la(0, b);
+ break;
+ case 72:
+ g = ra(["w", "s", "w", "w"], c);
+ p = g[0];
+ c = g[1];
+ d = g[2];
+ e = g[3];
+ c = za(a.g, c, a.a[p].ca);
+ r = sa(a.g, c);
+ r.mode = d | Aa;
+ r.uid = a.a[p].uid;
+ r.pb = e;
+ oa(["Q"], [r.lb], a.Aa, 7);
+ na(a, f, h, 13);
+ a.la(0, b);
+ break;
+ case 14:
+ g = ra(["w", "s",
+ "w", "w", "w"
+ ], c);
+ p = g[0];
+ c = g[1];
+ d = g[3];
+ e = g[4];
+ c = Ba(a.g, c, a.a[p].ca);
+ a.a[p].ca = c;
+ a.a[p].type = 1;
+ r = sa(a.g, c);
+ r.uid = a.a[p].uid;
+ r.pb = e;
+ r.mode = d;
+ oa(["Q", "w"], [r.lb, a.i - 24], a.Aa, 7);
+ na(a, f, h, 17);
+ a.la(0, b);
+ break;
+ case 52:
+ oa(["w"], [0], a.Aa, 7);
+ na(a, f, h, 1);
+ a.la(0, b);
+ break;
+ case 24:
+ g = ra(["w", "d"], c);
+ p = g[0];
+ r = sa(a.g, a.a[p].ca);
+ if (!r || r.status === Ca) {
+ pa(a, h, 2);
+ a.la(0, b);
+ break
+ }
+ g[0] |= 4096;
+ g[0] = g[1];
+ g[1] = r.lb;
+ g[2] = r.mode;
+ g[3] = r.uid;
+ g[4] = r.pb;
+ g[5] = r.Pb;
+ g[6] = r.$g << 8 | r.ah;
+ g[7] = r.size;
+ g[8] = a.l;
+ g[9] = Math.floor(r.size / 512 + 1);
+ g[10] = r.mf;
+ g[11] = 0;
+ g[12] = r.ne;
+ g[13] = 0;
+ g[14] = r.dg;
+ g[15] = 0;
+ g[16] = 0;
+ g[17] = 0;
+ g[18] = 0;
+ g[19] = 0;
+ oa("dQwwwddddddddddddddd".split(""), g, a.Aa, 7);
+ na(a, f, h, 153);
+ a.la(0, b);
+ break;
+ case 26:
+ g = ra("wwwwwddddd".split(""), c);
+ p = g[0];
+ r = sa(a.g, a.a[p].ca);
+ g[1] & 1 && (r.mode = g[2]);
+ g[1] & 2 && (r.uid = g[3]);
+ g[1] & 4 && (r.pb = g[4]);
+ g[1] & 16 && (r.mf = Math.floor((new Date).getTime() / 1E3));
+ g[1] & 32 && (r.ne = Math.floor((new Date).getTime() / 1E3));
+ g[1] & 64 && (r.dg = Math.floor((new Date).getTime() / 1E3));
+ g[1] & 128 && (r.mf = g[6]);
+ g[1] & 256 && (r.ne = g[8]);
+ g[1] &
+ 8 && Da(a.g, a.a[p].ca, g[5]);
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 50:
+ g = ra(["w", "d"], c);
+ p = g[0];
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 40:
+ case 116:
+ g = ra(["w", "d", "w"], c);
+ p = g[0];
+ var z = g[1],
+ A = g[2];
+ r = sa(a.g, a.a[p].ca);
+ if (!r || r.status === Ca) {
+ pa(a, h, 2);
+ a.la(0, b);
+ break
+ }
+ if (2 == a.a[p].type) {
+ r.Pa.length < z + A && (A = r.Pa.length - z);
+ for (d = 0; d < A; d++) a.Aa[11 + d] = r.Pa[z + d];
+ oa(["w"], [A], a.Aa, 7);
+ na(a, f, h, 4 + A);
+ a.la(0, b)
+ } else {
+ var M = a.g.a[a.a[p].ca];
+ a.w.send("9p-read-start");
+ ta(a.g, a.a[p].ca);
+ ua(a.g, a.a[p].ca, function() {
+ this.w.send("9p-read-end", [M.name, A]);
+ r.size < z + A && (A = r.size - z);
+ var a = this.g.g[this.a[p].ca];
+ if (a)
+ for (var c = 0; c < A; c++) this.Aa[11 + c] = a[z + c];
+ oa(["w"], [A], this.Aa, 7);
+ na(this, f, h, 4 + A);
+ this.la(0, b)
+ }.bind(a))
+ }
+ break;
+ case 118:
+ g = ra(["w", "d", "w"], c);
+ p = g[0];
+ z = g[1];
+ A = g[2];
+ Ea(a.g, a.a[p].ca, z, A, c);
+ M = a.g.a[a.a[p].ca];
+ a.w.send("9p-write-end", [M.name, A]);
+ oa(["w"], [A], a.Aa, 7);
+ na(a, f, h, 4);
+ a.la(0, b);
+ break;
+ case 74:
+ g = ra(["w", "s", "w", "s"], c);
+ c = Fa(a.g, a.a[g[0]].ca, g[1], a.a[g[2]].ca, g[3]);
+ if (0 == c) {
+ pa(a, h, 2);
+ a.la(0, b);
+ break
+ }
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 76:
+ g = ra(["w", "s", "w"], c);
+ d = g[0];
+ c = g[1];
+ p = Ga(a.g, a.a[d].ca, c);
+ if (-1 == p) {
+ pa(a, h, 2);
+ a.la(0, b);
+ break
+ }
+ c = Ha(a.g, p);
+ if (!c) {
+ pa(a, h, 39);
+ a.la(0, b);
+ break
+ }
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 100:
+ c = ra(["w", "s"], c);
+ a.i = c[0];
+ e = oa(["w", "s"], [a.i, a.v], a.Aa, 7);
+ na(a, f, h, e);
+ a.la(0, b);
+ break;
+ case 104:
+ g = ra(["w", "w", "s", "s", "w"], c);
+ p = g[0];
+ a.a[p] = {
+ ca: 0,
+ type: 1,
+ uid: g[4]
+ };
+ r = sa(a.g, a.a[p].ca);
+ oa(["Q"], [r.lb], a.Aa, 7);
+ na(a, f, h, 13);
+ a.la(0, b);
+ break;
+ case 108:
+ g = ra(["h"], c);
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 110:
+ g = ra(["w", "w", "h"],
+ c);
+ p = g[0];
+ e = g[1];
+ v = g[2];
+ if (0 == v) {
+ a.a[e] = {
+ ca: a.a[p].ca,
+ type: 1,
+ uid: a.a[p].uid
+ };
+ oa(["h"], [0], a.Aa, 7);
+ na(a, f, h, 2);
+ a.la(0, b);
+ break
+ }
+ E = [];
+ for (d = 0; d < v; d++) E.push("s");
+ E = ra(E, c);
+ c = a.a[p].ca;
+ z = 9;
+ var Y = 0;
+ for (d = 0; d < v; d++) {
+ c = Ga(a.g, c, E[d]);
+ if (-1 == c) break;
+ z += oa(["Q"], [a.g.a[c].lb], a.Aa, z);
+ Y++;
+ a.a[e] = {
+ ca: c,
+ type: 1,
+ uid: a.a[p].uid
+ }
+ }
+ oa(["h"], [Y], a.Aa, 7);
+ na(a, f, h, z - 7);
+ a.la(0, b);
+ break;
+ case 120:
+ g = ra(["w"], c);
+ a.a[g[0]] && 0 <= a.a[g[0]].ca && (Ia(a.g, a.a[g[0]].ca), a.a[g[0]].ca = -1, a.a[g[0]].type = -1);
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 32:
+ g = ra(["w", "s", "d", "w"], c);
+ p = g[0];
+ c = g[1];
+ na(a, f, h, 0);
+ a.la(0, b);
+ break;
+ case 30:
+ g = ra(["w", "w", "s"], c), p = g[0], d = g[1], c = g[2], a.a[d] = {
+ ca: a.a[p].ca,
+ type: -1,
+ uid: a.a[p].uid
+ }, e = 0, "security.capability" == c && (e = Ja(a.g, a.a[p].ca), a.a[d].type = 2), oa(["d"], [e], a.Aa, 7), na(a, f, h, 8), a.la(0, b)
+ }
+};
+"undefined" === typeof window || window.requestAnimationFrame || (window.requestAnimationFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame);
+
+function Ka(a, b) {
+ function c(a) {
+ a = a.toString(16);
+ return "#" + Array(7 - a.length).join("0") + a
+ }
+
+ function d(a, b, c, d) {
+ a.style.width = "";
+ a.style.height = "";
+ d && (a.style.transform = a.style.webkitTransform = a.style.MozTransform = "");
+ var f = a.getBoundingClientRect();
+ d ? a.style.transform = a.style.webkitTransform = a.style.MozTransform = (1 === b ? "" : " scaleX(" + b + ")") + (1 === c ? "" : " scaleY(" + c + ")") : (0 === b % 1 && 0 === c % 1 ? (e.style.ti = "pixelated", e.style["-ms-interpolation-mode"] = "nearest-neighbor") : (e.style.ti = "", e.style["-ms-interpolation-mode"] =
+ ""), d = window.devicePixelRatio || 1, 0 !== d % 1 && (b /= d, c /= d));
+ 1 !== b && (a.style.width = f.width * b + "px");
+ 1 !== c && (a.style.height = f.height * c + "px")
+ }
+ console.assert(a, "1st argument must be a DOM container");
+ var e = a.getElementsByTagName("canvas")[0],
+ f = e.getContext("2d"),
+ h = a.getElementsByTagName("div")[0],
+ g = document.createElement("div"),
+ p, r, v, E, z = 1,
+ A = 1,
+ M, Y = !1,
+ ka, vb, yd, Bh = this;
+ a = new Uint16Array([199, 252, 233, 226, 228, 224, 229, 231, 234, 235, 232, 239, 238, 236, 196, 197, 201, 230, 198, 244, 246, 242, 251, 249, 255, 214, 220, 162, 163, 165, 8359,
+ 402, 225, 237, 243, 250, 241, 209, 170, 186, 191, 8976, 172, 189, 188, 161, 171, 187, 9617, 9618, 9619, 9474, 9508, 9569, 9570, 9558, 9557, 9571, 9553, 9559, 9565, 9564, 9563, 9488, 9492, 9524, 9516, 9500, 9472, 9532, 9566, 9567, 9562, 9556, 9577, 9574, 9568, 9552, 9580, 9575, 9576, 9572, 9573, 9561, 9560, 9554, 9555, 9579, 9578, 9496, 9484, 9608, 9604, 9612, 9616, 9600, 945, 223, 915, 960, 931, 963, 181, 964, 934, 920, 937, 948, 8734, 966, 949, 8745, 8801, 177, 8805, 8804, 8992, 8993, 247, 8776, 176, 8729, 183, 8730, 8319, 178, 9632, 160
+ ]);
+ for (var Ch = new Uint16Array([32, 9786, 9787, 9829, 9830,
+ 9827, 9824, 8226, 9688, 9675, 9689, 9794, 9792, 9834, 9835, 9788, 9658, 9668, 8597, 8252, 182, 167, 9644, 8616, 8593, 8595, 8594, 8592, 8735, 8596, 9650, 9660
+ ]), Hf = [], If, Fb = 0; 256 > Fb; Fb++) If = 127 < Fb ? a[Fb - 128] : 32 > Fb ? Ch[Fb] : Fb, Hf[Fb] = String.fromCharCode(If);
+ f.imageSmoothingEnabled = !1;
+ g.style.position = "absolute";
+ g.style.backgroundColor = "#ccc";
+ g.style.width = "7px";
+ g.style.display = "inline-block";
+ h.style.display = "block";
+ e.style.display = "none";
+ this.w = b;
+ b.register("screen-set-mode", function(a) {
+ this.wg(a)
+ }, this);
+ b.register("screen-fill-buffer-end",
+ function(a) {
+ this.yg(a)
+ }, this);
+ b.register("screen-put-char", function(a) {
+ this.qg(a[0], a[1], a[2], a[3], a[4])
+ }, this);
+ b.register("screen-update-cursor", function(a) {
+ this.Nd(a[0], a[1])
+ }, this);
+ b.register("screen-update-cursor-scanline", function(a) {
+ this.Od(a[0], a[1])
+ }, this);
+ b.register("screen-clear", function() {
+ this.Dg()
+ }, this);
+ b.register("screen-set-size-text", function(a) {
+ this.Jd(a[0], a[1])
+ }, this);
+ b.register("screen-set-size-graphical", function(a) {
+ this.Id(a[0], a[1], a[2], a[3])
+ }, this);
+ this.Ob = function() {
+ this.Jd(80,
+ 25);
+ this.Ic()
+ };
+ this.i = function() {
+ try {
+ window.open(e.toDataURL())
+ } catch (hi) {}
+ };
+ this.qg = function(a, b, c, e, d) {
+ a < yd && b < vb && (b = 3 * (a * vb + b), ka[b] = c, ka[b + 1] = e, ka[b + 2] = d, M[a] = 1)
+ };
+ this.Ic = function() {
+ requestAnimationFrame(Y ? Dh : Gc)
+ };
+ var Gc = function() {
+ for (var a = 0; a < yd; a++) M[a] && (Bh.g(a), M[a] = 0);
+ this.Ic()
+ }.bind(this),
+ Dh = function() {
+ this.w.send("screen-fill-buffer");
+ this.Ic()
+ }.bind(this);
+ this.Mb = function() {};
+ this.wg = function(a) {
+ (Y = a) ? (h.style.display = "none", e.style.display = "block") : (h.style.display = "block", e.style.display =
+ "none")
+ };
+ this.Dg = function() {
+ f.fillStyle = "#000";
+ f.fillRect(0, 0, e.width, e.height)
+ };
+ this.Jd = function(a, b) {
+ if (a !== vb || b !== yd) {
+ M = new Int8Array(b);
+ ka = new Int32Array(a * b * 3);
+ vb = a;
+ for (yd = b; h.childNodes.length > b;) h.removeChild(h.firstChild);
+ for (; h.childNodes.length < b;) h.appendChild(document.createElement("div"));
+ for (a = 0; a < b; a++) this.g(a);
+ d(h, z, A, !0)
+ }
+ };
+ this.Id = function(a, b, c, g) {
+ e.style.display = "block";
+ e.width = a;
+ e.height = b;
+ p = f.createImageData(c, g);
+ new Uint8Array(p.data.buffer);
+ r = new Int32Array(p.data.buffer);
+ this.w.send("screen-tell-buffer", [r], [r.buffer]);
+ d(e, z, A, !1)
+ };
+ this.a = function(a, b) {
+ z = a;
+ A = b;
+ d(h, z, A, !0);
+ d(e, z, A, !1)
+ };
+ this.a(z, A);
+ this.Od = function(a, b) {
+ a & 32 ? g.style.display = "none" : (g.style.display = "inline", g.style.height = Math.min(15, b - a) + "px", g.style.marginTop = Math.min(15, a) + "px")
+ };
+ this.Nd = function(a, b) {
+ if (a !== v || b !== E) M[a] = 1, M[v] = 1, v = a, E = b
+ };
+ this.g = function(a) {
+ var b = 3 * a * vb,
+ e;
+ var d = h.childNodes[a];
+ var f = document.createElement("div");
+ for (var p = 0; p < vb;) {
+ var r = document.createElement("span");
+ var A = ka[b +
+ 1];
+ var M = ka[b + 2];
+ r.style.backgroundColor = c(A);
+ r.style.color = c(M);
+ for (e = ""; p < vb && ka[b + 1] === A && ka[b + 2] === M;)
+ if (e += Hf[ka[b]], p++, b += 3, a === v)
+ if (p === E) break;
+ else if (p === E + 1) {
+ f.appendChild(g);
+ break
+ }
+ r.textContent = e;
+ f.appendChild(r)
+ }
+ d.parentNode.replaceChild(f, d)
+ };
+ this.yg = function(a) {
+ a.forEach(function(a) {
+ f.putImageData(p, a.ug - a.qf, a.vg - a.rf, a.qf, a.rf, a.ag, a.$f)
+ })
+ };
+ this.Ob()
+};
+(function() {
+ function a(a, c) {
+ a instanceof Array || (a = [a]);
+ b(new Blob(a), c)
+ }
+
+ function b(a, b) {
+ var c = document.createElement("a");
+ c.download = b;
+ c.href = window.URL.createObjectURL(a);
+ c.dataset.downloadurl = ["application/octet-stream", c.download, c.href].join(":");
+ document.createEvent ? (a = document.createEvent("MouseEvent"), a.initMouseEvent("click", !0, !0, window, 0, 0, 0, 0, 0, !1, !1, !1, !1, 0, null), c.dispatchEvent(a)) : c.click();
+ window.URL.revokeObjectURL(c.href)
+ }
+
+ function c() {
+ for (var a = location.search.substr(1).split("&"),
+ b = {}, c = 0; c < a.length; c++) {
+ var e = a[c].split("=");
+ b[e[0]] = decodeURIComponent(e[1])
+ }
+ return b
+ }
+
+ function d(a, b) {
+ for (var c = ""; 0 < b--;) c += a;
+ return c
+ }
+
+ function e(a) {
+ return document.getElementById(a)
+ }
+
+ function f() {
+ function a(a) {
+ e("boot_options").style.display = "none";
+ document.title = a.name + " - Virtual x86";
+ d.filesystem = a.filesystem;
+ a.state && (e("reset").style.display = "none", d.ke = a.state);
+ d.Ra = a.Ra;
+ d.Qa = a.Qa;
+ d.Ma = a.Ma;
+ d.oe = a.oe;
+ d.Ia = a.Ia;
+ d.Ja = a.Ja;
+ d.id = a.id;
+ void 0 !== a.ae && (d.ae = a.ae);
+ a.description && (e("description").style.display =
+ "block", e("description").innerHTML = "<br>" + a.description);
+ h(d, b)
+ }
+
+ function b(a) {
+ g.c && setTimeout(function() {
+ a.Xg(g.c + "\n")
+ }, 25)
+ }
+ if ("responseType" in new XMLHttpRequest) {
+ var d = {};
+ e("start_emulation").onclick = function() {
+ e("boot_options").style.display = "none";
+ v("custom");
+ var a = e("floppy_image").files[0];
+ if (a) {
+ var b = a;
+ d.Ra = {
+ buffer: a
+ }
+ }
+ if (a = e("cd_image").files[0]) b = a, d.Qa = {
+ buffer: a
+ };
+ if (a = e("hd_image").files[0]) b = a, d.Ma = {
+ buffer: a
+ };
+ e("multiboot_image") && (a = e("multiboot_image").files[0]) && (b = a, d.oe = {
+ buffer: a
+ });
+ b && (document.title = b.name + " - Virtual x86");
+ h(d)
+ };
+ var f = [{
+ id: "linux26",
+ Qa: {
+ url: z + "images/linux.iso",
+ size: 5666816
+ },
+ name: "Linux"
+ }, {
+ id: "linux3",
+ Qa: {
+ url: z + "images/linux3.iso",
+ size: 8624128
+ },
+ name: "Linux",
+ filesystem: {}
+ }, {
+ id: "openbsd",
+ Ra: {
+ url: z + "/static/openbsd.img",
+ size: 1474560
+ },
+ name: "OpenBSD"
+ }],
+ g = c(),
+ p = 'openbsd';
+ g.use_bochs_bios && (d.tk = !0);
+ for (var r = 0; r < f.length; r++) {
+ var Y = f[r];
+ if (p === Y.id) {
+ a(Y);
+ return
+ }
+ var Gc = e("start_" + Y.id);
+ Gc && (Gc.onclick = function(b, c) {
+ v(b.id);
+ c.blur();
+ a(b)
+ }.bind(this, Y, Gc))
+ }
+ "custom" === p && (g["hda.url"] && (d.Ma = {
+ size: parseInt(g["hda.size"], 10) || void 0,
+ url: g["hda.url"],
+ async: !0
+ }), g["cdrom.url"] && (d.Qa = {
+ size: parseInt(g["cdrom.size"], 10) || void 0,
+ url: g["cdrom.url"],
+ async: !0
+ }), g["fda.url"] && (d.Ra = {
+ size: parseInt(g["fda.size"], 10) || void 0,
+ url: g["fda.url"],
+ async: !0
+ }), d.Ra || d.Qa ||
+ d.Ma) && (e("boot_options").style.display = "none", h(d, b))
+ } else alert("Your browser is not supported because it doesn't have XMLHttpRequest.responseType")
+ }
+
+ function h(a, b) {
+ var c = a.Ia;
+ c || (c = 1048576 * parseInt(e("memory_size").value, 10), c || (alert("Invalid memory size - reset to 128MB"), c = 134217728));
+ var f = a.Ja;
+ f || (f = 1048576 * parseInt(e("video_memory_size").value, 10), f || (alert("Invalid video memory size - reset to 8MB"), f = 8388608));
+ if (!a.Ra) {
+ var h = e("floppy_image").files[0];
+ h && (a.Ra = {
+ buffer: h
+ })
+ }
+ if (a.tk) {
+ h = "bochs-bios.bin";
+ var p = "bochs-vgabios.bin"
+ } else h = "seabios.bin", p = "vgabios.bin";
+ if (!a.ke) {
+ var r = {
+ url: "/static/" + h
+ };
+ var v = {
+ url: "/static/" + p
+ }
+ }
+ var A = new l({
+ memory_size: c,
+ vga_memory_size: f,
+ screen_container: e("screen_container"),
+ serial_container: e("serial"),
+ boot_order: a.ae || parseInt(e("boot_order").value, 16) || 0,
+ network_relay_url: "wss://relay.widgetry.org/",
+ bios: r,
+ vga_bios: v,
+ fda: a.Ra,
+ hda: a.Ma,
+ cdrom: a.Qa,
+ multiboot: a.oe,
+ initial_state: a.ke,
+ filesystem: a.filesystem || {},
+ autostart: !0
+ });
+ A.$a("emulator-ready", function() {
+ g(a, A);
+ b && b(A)
+ });
+ A.$a("download-progress", function(a) {
+ var b = e("loading");
+ b.style.display = "block";
+ if (a.vf === a.uf - 1 && a.loaded >= a.total - 2048) b.textContent = "Done downloading. Starting now ...";
+ else {
+ var c = "Downloading images ";
+ "number" === typeof a.vf && a.uf && (c += "[" + (a.vf + 1) + "/" + a.uf + "] ");
+ if (a.total && "number" === typeof a.loaded) {
+ a = Math.floor(a.loaded / a.total * 100);
+ a = Math.min(100, Math.max(0, a));
+ var f = Math.floor(a / 2);
+ c = c + (a + "% [") + d("#", f);
+ c += d(" ", 50 - f) + "]"
+ } else c += d(".", Y++ % 50);
+ b.textContent = c
+ }
+ });
+ A.$a("download-error", function(a) {
+ var b =
+ e("loading");
+ b.style.display = "block";
+ b.textContent = "Loading " + a.Qg + " failed. Check your connection and reload the page to try again."
+ })
+ }
+
+ function g(c, d) {
+ function f() {
+ var a = Date.now(),
+ b = d.ig(),
+ c = b - M;
+ M = b;
+ var f = a - v;
+ A += f;
+ v = a;
+ e("speed").textContent = c / f | 0;
+ e("avg_speed").textContent = b / A | 0;
+ a = e("running_time");
+ b = A / 1E3 | 0;
+ a.textContent = 60 > b ? b + "s" : 3600 > b ? (b / 60 | 0) + "m " + La(b % 60, 2) + "s" : (b / 3600 | 0) + "h " + La((b / 60 | 0) % 60, 2) + "m " + La(b % 60, 2) + "s"
+ }
+
+ function g(f, g) {
+ var h = e("get_" + g + "_image");
+ !f || 104857600 < f.size ? h.style.display =
+ "none" : h.onclick = function() {
+ var e = d.kd[g],
+ f = c.id + ("cdrom" === g ? ".iso" : ".img");
+ e.Tg ? (e = e.Tg(f), b(e, f)) : e.Se(function(b) {
+ b ? a(b, f) : alert("The file could not be loaded. Maybe it's too big?")
+ });
+ h.blur()
+ }
+ }
+
+ function h(a) {
+ a.ctrlKey ? window.onbeforeunload = function() {
+ window.onbeforeunload = null;
+ return "CTRL-W cannot be sent to the emulator."
+ } : window.onbeforeunload = null
+ }
+ e("boot_options").style.display = "none";
+ e("loading").style.display = "none";
+ e("runtime_options").style.display = "block";
+ e("runtime_infos").style.display =
+ "block";
+ e("screen_container").style.display = "block";
+ c.filesystem && p(d);
+ e("run").onclick = function() {
+ d.Ge ? (e("run").value = "Run", d.stop()) : (e("run").value = "Pause", d.cf());
+ e("run").blur()
+ };
+ e("exit").onclick = function() {
+ d.stop();
+ location.href = location.pathname
+ };
+ e("lock_mouse").onclick = function() {
+ if (!r) e("toggle_mouse").onclick();
+ d.Df();
+ e("lock_mouse").blur()
+ };
+ var r = !0;
+ e("toggle_mouse").onclick = function() {
+ r = !r;
+ d.m && (d.m.a = r);
+ e("toggle_mouse").value = (r ? "Dis" : "En") + "able mouse";
+ e("toggle_mouse").blur()
+ };
+ var v =
+ 0,
+ A = 0,
+ M = 0,
+ z, ka = !1;
+ d.$a("emulator-started", function() {
+ v = Date.now();
+ z = setInterval(f, 1E3)
+ });
+ d.$a("emulator-stopped", function() {
+ f();
+ clearInterval(z)
+ });
+ var E = 0,
+ Y = 0;
+ d.$a("9p-read-start", function() {
+ e("info_filesystem").style.display = "block";
+ e("info_filesystem_status").textContent = "Loading ..."
+ });
+ d.$a("9p-read-end", function(a) {
+ E += a[1];
+ e("info_filesystem_status").textContent = "Idle";
+ e("info_filesystem_last_file").textContent = a[0];
+ e("info_filesystem_bytes_read").textContent = E
+ });
+ d.$a("9p-write-end", function(a) {
+ Y +=
+ a[1];
+ e("info_filesystem_last_file").textContent = a[0];
+ e("info_filesystem_bytes_written").textContent = Y
+ });
+ var vb = 0,
+ Gf = 0,
+ Jf = 0,
+ Kf = 0;
+ d.$a("ide-read-start", function() {
+ e("info_storage").style.display = "block";
+ e("info_storage_status").textContent = "Loading ..."
+ });
+ d.$a("ide-read-end", function(a) {
+ vb += a[1];
+ Gf += a[2];
+ e("info_storage_status").textContent = "Idle";
+ e("info_storage_bytes_read").textContent = vb;
+ e("info_storage_sectors_read").textContent = Gf
+ });
+ d.$a("ide-write-end", function(a) {
+ Jf += a[1];
+ Kf += a[2];
+ e("info_storage_bytes_written").textContent =
+ Jf;
+ e("info_storage_sectors_written").textContent = Kf
+ });
+ var Lf = 0,
+ Mf = 0;
+ d.$a("eth-receive-end", function(a) {
+ Mf += a[0];
+ e("info_network").style.display = "block";
+ e("info_network_bytes_received").textContent = Mf
+ });
+ d.$a("eth-transmit-end", function(a) {
+ Lf += a[0];
+ e("info_network").style.display = "block";
+ e("info_network_bytes_transmitted").textContent = Lf
+ });
+ d.$a("mouse-enable", function(a) {
+ ka = a;
+ e("info_mouse_enabled").textContent = a ? "Yes" : "No"
+ });
+ d.$a("screen-set-mode", function(a) {
+ a ? e("info_vga_mode").textContent = "Graphical" :
+ (e("info_vga_mode").textContent = "Text", e("info_res").textContent = "-", e("info_bpp").textContent = "-")
+ });
+ d.$a("screen-set-size-graphical", function(a) {
+ e("info_res").textContent = a[0] + "x" + a[1];
+ e("info_bpp").textContent = a[4]
+ });
+ e("reset").onclick = function() {
+ d.Sf();
+ e("reset").blur()
+ };
+ g(c.Ma, "hda");
+ g(c.zf, "hdb");
+ g(c.Ra, "fda");
+ g(c.Ng, "fdb");
+ g(c.Qa, "cdrom");
+ e("memory_dump").onclick = function() {
+ a(d.a.j.da, "v86memory.bin");
+ e("memory_dump").blur()
+ };
+ e("save_state").onclick = function() {
+ d.we(function(b, c) {
+ b ? (console.log(b.stack),
+ console.log("Couldn't save state: ", b)) : a(c, "v86state.bin")
+ });
+ e("save_state").blur()
+ };
+ e("load_state").onclick = function() {
+ e("load_state_input").click();
+ e("load_state").blur()
+ };
+ e("load_state_input").onchange = function() {
+ var a = this.files[0];
+ if (a) {
+ var b = d.Ge;
+ b && d.stop();
+ var c = new FileReader;
+ c.onload = function(a) {
+ try {
+ d.Hd(a.target.result)
+ } catch (Nf) {
+ throw alert("Something bad happened while restoring the state:\n" + Nf + "\n\nNote that the current configuration must be the same as the original"), Nf;
+ }
+ b && d.cf()
+ };
+ c.readAsArrayBuffer(a);
+ this.value = ""
+ }
+ };
+ e("ctrlaltdel").onclick = function() {
+ d.Cf([29, 56, 83, 157, 184, 211]);
+ e("ctrlaltdel").blur()
+ };
+ e("alttab").onclick = function() {
+ d.Cf([56, 15]);
+ setTimeout(function() {
+ d.Cf([184, 143])
+ }, 100);
+ e("alttab").blur()
+ };
+ e("scale").onchange = function() {
+ var a = parseFloat(this.value);
+ (a || 0 < a) && d.Dh(a, a)
+ };
+ e("fullscreen").onclick = function() {
+ d.Bh()
+ };
+ e("screen_container").onclick = function() {
+ if (r && ka) d.Df(), e("lock_mouse").blur();
+ else if (window.getSelection().isCollapsed) {
+ var a = document.getElementsByClassName("phone_keyboard")[0];
+ a.style.top = document.body.scrollTop + 100 + "px";
+ a.style.left = document.body.scrollLeft + 100 + "px";
+ a.focus()
+ }
+ };
+ var Hc = document.getElementsByClassName("phone_keyboard")[0];
+ Hc.setAttribute("autocorrect", "off");
+ Hc.setAttribute("autocapitalize", "off");
+ Hc.setAttribute("spellcheck", "false");
+ Hc.tabIndex = 0;
+ e("screen_container").addEventListener("mousedown", function() {
+ Hc.focus()
+ }, !1);
+ e("take_screenshot").onclick = function() {
+ d.Ch();
+ e("take_screenshot").blur()
+ };
+ e("serial").style.display = "block";
+ window.addEventListener("keydown",
+ h, !1);
+ window.addEventListener("keyup", h, !1);
+ window.addEventListener("blur", h, !1)
+ }
+
+ function p(b) {
+ e("filesystem_panel").style.display = "block";
+ e("filesystem_send_file").onchange = function() {
+ Array.prototype.forEach.call(this.files, function(a) {
+ var c = new Ma(a);
+ c.onload = function() {
+ c.Se(function(c) {
+ b.Eg("/" + a.name, new Uint8Array(c))
+ })
+ };
+ c.load()
+ }, this);
+ this.value = "";
+ this.blur()
+ };
+ e("filesystem_get_file").onkeypress = function(c) {
+ 13 === c.which && (this.disabled = !0, b.vh(this.value, function(b, c) {
+ this.disabled = !1;
+ c ? (b =
+ this.value.replace(/\/$/, "").split("/"), b = b[b.length - 1] || "root", a(c, b), this.value = "") : alert("Can't read file")
+ }.bind(this)))
+ }
+ }
+
+ function r() {
+ location.reload()
+ }
+
+ function v(a) {
+ }
+ var E = !location.hostname.endsWith(".none"),
+ z = E ? "" : "",
+ A = E ? "" : "",
+ M = "https:" === location.protocol,
+ Y = 0;
+ window.addEventListener("load", f, !1);
+ window.addEventListener("load", function() {
+ setTimeout(function() {
+ window.addEventListener("popstate",
+ r)
+ }, 0)
+ });
+ "complete" === document.readyState && f()
+})();
+
+function Na(a) {
+ this.ports = [];
+ this.j = a;
+ for (var b = 0; 65536 > b; b++) this.ports[b] = Oa(this);
+ var c = a.Ia;
+ for (b = 0; b << 17 < c; b++) a.Ye[b] = a.Ze[b] = void 0, a.Ff[b] = a.Gf[b] = void 0;
+ Pa(this, c, 4294967296 - c, function() {
+ return 255
+ }, function() {}, function() {
+ return -1
+ }, function() {})
+}
+
+function Oa(a) {
+ return {
+ ja: a.gi,
+ ma: a.ei,
+ th: a.fi,
+ za: a.eg,
+ ze: a.eg,
+ fd: a.eg,
+ ia: void 0
+ }
+}
+k = Na.prototype;
+k.gi = function() {
+ return 255
+};
+k.ei = function() {
+ return 65535
+};
+k.fi = function() {
+ return -1
+};
+k.eg = function() {};
+
+function m(a, b, c, d, e, f) {
+ d && (a.ports[b].ja = d);
+ e && (a.ports[b].ma = e);
+ f && (a.ports[b].th = f);
+ a.ports[b].ia = c
+}
+
+function n(a, b, c, d, e, f) {
+ d && (a.ports[b].za = d);
+ e && (a.ports[b].ze = e);
+ f && (a.ports[b].fd = f);
+ a.ports[b].ia = c
+}
+k.te = function(a, b, c, d, e, f) {
+ function h() {
+ return c.call(this) | d.call(this) << 8
+ }
+
+ function g() {
+ return e.call(this) | f.call(this) << 8
+ }
+
+ function p() {
+ return c.call(this) | d.call(this) << 8 | e.call(this) << 16 | f.call(this) << 24
+ }
+ e && f ? (m(this, a, b, c, h, p), m(this, a + 1, b, d), m(this, a + 2, b, e, g), m(this, a + 3, b, f)) : (m(this, a, b, c, h), m(this, a + 1, b, d))
+};
+k.Gc = function(a, b, c, d, e, f) {
+ function h(a) {
+ c.call(this, a & 255);
+ d.call(this, a >> 8 & 255)
+ }
+
+ function g(a) {
+ e.call(this, a & 255);
+ f.call(this, a >> 8 & 255)
+ }
+
+ function p(a) {
+ c.call(this, a & 255);
+ d.call(this, a >> 8 & 255);
+ e.call(this, a >> 16 & 255);
+ f.call(this, a >>> 24)
+ }
+ e && f ? (n(this, a, b, c, h, p), n(this, a + 1, b, d), n(this, a + 2, b, e, g), n(this, a + 3, b, f)) : (n(this, a, b, c, h), n(this, a + 1, b, d))
+};
+
+function Qa(a, b, c) {
+ b >>>= 0;
+ c = b + (c >>> 0);
+ if (c >= a.j.Ia) return !0;
+ for (b &= -131072; b < c;) {
+ if (Ra(a.j, b)) return !0;
+ b += 131072
+ }
+ return !1
+}
+k.Ai = function(a) {
+ var b = this.j.Ye[a >>> 17];
+ return b(a) | b(a + 1) << 8 | b(a + 2) << 16 | b(a + 3) << 24
+};
+k.Bi = function(a, b) {
+ var c = this.j.Ze[a >>> 17];
+ c(a, b & 255);
+ c(a + 1, b >> 8 & 255);
+ c(a + 2, b >> 16 & 255);
+ c(a + 3, b >>> 24)
+};
+
+function Pa(a, b, c, d, e, f, h) {
+ f || (f = a.Ai.bind(a));
+ h || (h = a.Bi.bind(a));
+ for (b >>>= 17; 0 < c; b++) a.j.Ye[b] = d, a.j.Ze[b] = e, a.j.Ff[b] = f, a.j.Gf[b] = h, c -= 131072
+}
+
+function Sa(a, b, c) {
+ a = a.ports[b];
+ a.za.call(a.ia, c)
+}
+
+function Ta(a, b, c) {
+ a = a.ports[b];
+ a.ze.call(a.ia, c)
+}
+
+function Ua(a, b, c) {
+ a = a.ports[b];
+ a.fd.call(a.ia, c)
+}
+
+function Va(a, b) {
+ a = a.ports[b];
+ return a.ja.call(a.ia)
+}
+
+function Wa(a, b) {
+ a = a.ports[b];
+ return a.ma.call(a.ia)
+}
+
+function Xa(a, b) {
+ a = a.ports[b];
+ return a.th.call(a.ia)
+};
+
+function Ya(a) {
+ this.g = this.a = !1;
+ this.j = new q(a);
+ this.w = a;
+ a.register("cpu-init", this.Ob, this);
+ a.register("cpu-run", this.cf, this);
+ a.register("cpu-stop", this.stop, this);
+ a.register("cpu-restart", this.Sf, this);
+ this.hk()
+}
+Ya.prototype.cf = function() {
+ this.a || (this.w.send("emulator-started"), this.fg())
+};
+
+function Za(a) {
+ if (a.g) a.g = a.a = !1, a.w.send("emulator-stopped");
+ else {
+ a.a = !0;
+ a: {
+ var b = a.j;
+ if (b.Tc) {
+ var c = $a();
+ b.G.If.Ic(c, !1);
+ b.G.bd.Ic(c, !1);
+ ab(b);
+ if (b.Tc) {
+ b = 0;
+ break a
+ }
+ }
+ for (var d = c = $a(); 1 > d - c;) {
+ var e = b;
+ e.G.If.Ic(d, !1);
+ e.G.bd.Ic(d, !1);
+ ab(b);
+ b.qa();
+ if (b.Tc) break;
+ d = $a()
+ }
+ b = 0
+ }
+ 0 >= b ? a.fg() : a.Ci(b)
+ }
+}
+Ya.prototype.stop = function() {
+ this.a && (this.g = !0)
+};
+Ya.prototype.Sf = function() {
+ this.j.reset();
+ bb(this.j)
+};
+Ya.prototype.Ob = function(a) {
+ this.j.Ob(a, this.w);
+ this.w.send("emulator-ready")
+};
+if ("undefined" !== typeof setImmediate) var cb = function() {
+ var a = this;
+ setImmediate(function() {
+ Za(a)
+ })
+ },
+ db = function() {};
+else "undefined" !== typeof window && "undefined" !== typeof postMessage ? (cb = function() {
+ window.postMessage(43605, "*")
+}, db = function() {
+ var a = this;
+ window.addEventListener("message", function(b) {
+ b.source === window && 43605 === b.data && Za(a)
+ }, !1)
+}) : (cb = function() {
+ var a = this;
+ setTimeout(function() {
+ Za(a)
+ }, 0)
+}, db = function() {});
+k = Ya.prototype;
+k.fg = cb;
+k.hk = db;
+k.Ci = "undefined" !== typeof document && "boolean" === typeof document.hidden ? function(a) {
+ var b = this;
+ 4 > a || document.hidden ? this.fg() : setTimeout(function() {
+ Za(b)
+ }, a)
+} : function(a) {
+ var b = this;
+ setTimeout(function() {
+ Za(b)
+ }, a)
+};
+k.we = function() {
+ return this.j.we()
+};
+k.Hd = function(a) {
+ return this.j.Hd(a)
+};
+var $a = "object" === typeof performance && performance.now ? function() {
+ return performance.now()
+} : Date.now;
+var Ma, eb, fb, gb, hb, ib;
+
+function La(a, b) {
+ for (a = a ? a + "" : ""; a.length < b;) a = "0" + a;
+ return a
+}
+
+function jb(a, b) {
+ return "0x" + La((a ? a.toString(16) : "").toUpperCase(), b || 1)
+}
+if ("undefined" !== typeof window && window.crypto && window.crypto.getRandomValues) var kb = new Int32Array(1),
+ lb = function() {
+ return !0
+ },
+ mb = function() {
+ window.crypto.getRandomValues(kb);
+ return kb[0]
+ };
+else lb = function() {
+ return !1
+}, mb = function() {
+ console.assert(!1)
+};
+
+function nb(a) {
+ this.buffer = a;
+ this.byteLength = a.byteLength;
+ this.onload = void 0
+}
+nb.prototype.load = function() {
+ this.onload && this.onload({
+ buffer: this.buffer
+ })
+};
+nb.prototype.get = function(a, b, c) {
+ c(new Uint8Array(this.buffer, a, b))
+};
+nb.prototype.set = function(a, b, c) {
+ (new Uint8Array(this.buffer, a, b.byteLength)).set(b);
+ c()
+};
+nb.prototype.Se = function(a) {
+ a(this.buffer)
+};
+(function() {
+ for (var a = new Int8Array(256), b = 0, c = -2; 256 > b; b++) b & b - 1 || c++, a[b] = c;
+ eb = function(b) {
+ return a[b]
+ };
+ fb = function(b) {
+ var c = b >>> 16;
+ if (c) {
+ var d = c >>> 8;
+ return d ? 24 + a[d] : 16 + a[c]
+ }
+ return (d = b >>> 8) ? 8 + a[d] : a[b]
+ }
+})();
+
+function ob(a) {
+ var b = new Uint8Array(a),
+ c, d;
+ this.length = 0;
+ this.push = function(c) {
+ this.length !== a && this.length++;
+ b[d] = c;
+ d = d + 1 & a - 1
+ };
+ this.shift = function() {
+ if (this.length) {
+ var e = b[c];
+ c = c + 1 & a - 1;
+ this.length--;
+ return e
+ }
+ return -1
+ };
+ this.clear = function() {
+ this.length = d = c = 0
+ };
+ this.clear()
+}
+
+function pb() {
+ this.size = 65536;
+ this.data = new Float32Array(65536);
+ this.length = this.a = this.start = 0
+}
+pb.prototype.push = function(a) {
+ this.length === this.size ? this.start = this.start + 1 & this.size - 1 : this.length++;
+ this.data[this.a] = a;
+ this.a = this.a + 1 & this.size - 1
+};
+pb.prototype.shift = function() {
+ if (this.length) {
+ var a = this.data[this.start];
+ this.start = this.start + 1 & this.size - 1;
+ this.length--;
+ return a
+ }
+};
+
+function qb(a, b) {
+ var c = new Float32Array(b);
+ b > a.length && (b = a.length);
+ var d = a.start + b,
+ e = a.data.subarray(a.start, d);
+ c.set(e);
+ d >= a.size && (d -= a.size, c.set(a.data.subarray(0, d), e.length));
+ a.start = d;
+ a.length -= b;
+ return c
+}
+pb.prototype.clear = function() {
+ this.length = this.a = this.start = 0
+};
+
+function rb(a) {
+ this.j = a;
+ this.I = new Float64Array(8);
+ this.m = new Float32Array(1);
+ new Uint8Array(this.m.buffer);
+ this.v = new Int32Array(this.m.buffer);
+ this.l = new Float64Array(1);
+ this.g = new Uint8Array(this.l.buffer);
+ this.i = new Int32Array(this.l.buffer);
+ this.O = new Uint8Array(this.I.buffer);
+ new Int32Array(this.I.buffer);
+ this.fa = 255;
+ this.B = 0;
+ this.ec = 895;
+ this.od = this.nd = this.pd = this.Qe = this.Oc = this.a = 0;
+ this.C = NaN;
+ this.J = new Float64Array([1, Math.log(10) / Math.LN2, Math.LOG2E, Math.PI, Math.log(2) / Math.LN10, Math.LN2,
+ 0
+ ])
+}
+k = rb.prototype;
+k.Sa = function() {
+ var a = [];
+ a[0] = this.I;
+ a[1] = this.fa;
+ a[2] = this.B;
+ a[3] = this.ec;
+ a[4] = this.od;
+ a[5] = this.Oc;
+ a[6] = this.Qe;
+ a[7] = this.nd;
+ a[8] = this.od;
+ a[9] = this.pd;
+ return a
+};
+k.fb = function(a) {
+ this.I.set(a[0]);
+ this.fa = a[1];
+ this.B = a[2];
+ this.ec = a[3];
+ this.Oc = a[5];
+ this.Qe = a[6];
+ this.nd = a[7];
+ this.od = a[8];
+ this.pd = a[9]
+};
+
+function sb(a) {
+ t(a.j)
+}
+
+function tb(a) {
+ a.a |= 1
+}
+
+function ub(a, b) {
+ var c = wb(a);
+ a.a &= -18177;
+ c > b || (a.a = b > c ? a.a | 256 : c === b ? a.a | 16384 : a.a | 17664)
+}
+
+function xb(a, b) {
+ var c = a.I[a.B];
+ a.j.u &= -70;
+ a.j.flags &= -70;
+ c > b || (a.j.flags = b > c ? a.j.flags | 1 : c === b ? a.j.flags | 64 : a.j.flags | 69)
+}
+
+function yb(a) {
+ a.ec = 895;
+ a.a = 0;
+ a.Oc = 0;
+ a.nd = 0;
+ a.pd = 0;
+ a.fa = 255;
+ a.B = 0
+}
+
+function zb(a) {
+ return a.a & -14337 | a.B << 11
+}
+
+function Ab(a, b) {
+ if (Bb(a.j)) {
+ Cb(a.j, b, 26);
+ u(a.j, b, a.ec);
+ u(a.j, b + 4, zb(a));
+ for (var c = 0, d, e = 0; 8 > e; e++) d = a.I[e], a.fa >> e & 1 ? c |= 3 << (e << 1) : 0 === d ? c |= 1 << (e << 1) : isFinite(d) || (c |= 2 << (e << 1));
+ u(a.j, b + 8, c);
+ w(a.j, b + 12, a.Oc);
+ u(a.j, b + 16, a.Qe);
+ u(a.j, b + 18, a.pd);
+ w(a.j, b + 20, a.nd);
+ u(a.j, b + 24, a.od)
+ } else sb(a)
+}
+
+function Db(a, b) {
+ if (Bb(a.j)) {
+ a.ec = x(a.j, b);
+ var c = x(a.j, b + 4);
+ a.a = c & -14337;
+ a.B = c >> 11 & 7;
+ c = x(a.j, b + 8);
+ for (var d = a.fa = 0; 8 > d; d++) a.fa |= c >> d & c >> d + 1 & 1 << d;
+ a.Oc = y(a.j, b + 12);
+ a.Qe = x(a.j, b + 16);
+ a.pd = x(a.j, b + 18);
+ a.nd = y(a.j, b + 20);
+ a.od = x(a.j, b + 24)
+ } else sb(a)
+}
+
+function Eb(a, b) {
+ a = a.ec >> 10 & 3;
+ return 0 === a ? (a = Math.round(b), .5 === a - b && a % 2 && a--, a) : 1 === a || 3 === a && 0 < b ? Math.floor(b) : Math.ceil(b)
+}
+
+function Gb(a) {
+ return 0 < a ? Math.floor(a) : Math.ceil(a)
+}
+k.push = function(a) {
+ this.B = this.B - 1 & 7;
+ this.fa >> this.B & 1 ? (this.a &= -513, this.fa &= ~(1 << this.B), this.I[this.B] = a) : (this.a |= 512, this.a |= 65, this.I[this.B] = this.C)
+};
+k.pop = function() {
+ this.fa |= 1 << this.B;
+ this.B = this.B + 1 & 7
+};
+
+function Hb(a, b) {
+ b = b + a.B & 7;
+ return a.fa >> b & 1 ? (a.a &= -513, a.a |= 65, a.C) : a.I[b]
+}
+
+function wb(a) {
+ return a.fa >> a.B & 1 ? (a.a &= -513, a.a |= 65, a.C) : a.I[a.B]
+}
+
+function Ib(a, b) {
+ var c = x(a.j, b + 8),
+ d = y(a.j, b) >>> 0,
+ e = y(a.j, b + 4) >>> 0;
+ b = c >> 15;
+ c &= -32769;
+ if (0 === c) return 0;
+ if (!(32767 > c)) return a.g[7] = 127 | b << 7, a.g[6] = 240 | e >> 30 << 3 & 8, a.g[5] = 0, a.g[4] = 0, a.i[0] = 0, a.l[0];
+ a = d + 4294967296 * e;
+ b && (a = -a);
+ return a * Math.pow(2, c - 16383 - 63)
+}
+
+function Jb(a, b, c) {
+ a.l[0] = c;
+ c = a.g[7] & 128;
+ var d = (a.g[7] & 127) << 4 | a.g[6] >> 4;
+ if (2047 === d) {
+ d = 32767;
+ var e = 0;
+ var f = 2147483648 | (a.i[1] & 524288) << 11
+ } else 0 === d ? f = e = 0 : (d += 15360, e = a.i[0] << 11, f = 2147483648 | (a.i[1] & 1048575) << 11 | a.i[0] >>> 21);
+ w(a.j, b, e);
+ w(a.j, b + 4, f);
+ u(a.j, b + 8, c << 8 | d)
+}
+
+function Kb(a, b) {
+ var c = y(a.j, b);
+ b = y(a.j, b + 4);
+ a.i[0] = c;
+ a.i[1] = b;
+ return a.l[0]
+}
+
+function Lb(a, b) {
+ Cb(a.j, b, 8);
+ a.l[0] = Hb(a, 0);
+ w(a.j, b, a.i[0]);
+ w(a.j, b + 4, a.i[1])
+}
+
+function Mb(a, b) {
+ a.v[0] = y(a.j, b);
+ return a.m[0]
+}
+k.sign = function(a) {
+ return this.O[(this.B + a & 7) << 3 | 7] >> 7
+};
+
+function Nb(a, b, c, d, e) {
+ this.sa = new Ob(this, a, b, c, d, e);
+ this.Ca = new Ob(this, a, void 0, !1, d, e);
+ this.Ka = this.sa;
+ this.j = a;
+ 0 === d ? (this.a = 496, this.ua = 14, this.Hb = 240) : 1 === d && (this.a = 368, this.ua = 15, this.Hb = 248);
+ this.i = this.a | 516;
+ this.g = 46080;
+ this.pe = [134, 128, 16, 112, 5, 0, 160, 2, 0, 128, 1, 1, 0, 0, 0, 0, this.a & 255 | 1, this.a >> 8, 0, 0, this.i & 255 | 1, this.i >> 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, this.g & 255 | 1, this.g >> 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 16, 212, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, this.ua, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ ];
+ this.nc = [{
+ size: 8
+ }, {
+ size: 4
+ }, void 0, void 0, {
+ size: 16
+ }];
+ this.name = "ide" + d;
+ this.m = 2;
+ m(a.o, this.a | 7, this, function() {
+ Pb(this.j, this.ua);
+ return this.zh()
+ });
+ m(a.o, this.i | 2, this, this.zh);
+ n(a.o, this.i | 2, this, this.xk);
+ m(a.o, this.a | 0, this, function() {
+ return Qb(this.Ka, 1)
+ }, function() {
+ return Qb(this.Ka, 2)
+ }, function() {
+ return Qb(this.Ka, 4)
+ });
+ m(a.o, this.a | 1, this, function() {
+ return this.Ka.error
+ });
+ m(a.o, this.a | 2, this, function() {
+ return this.Ka.pa & 255
+ });
+ m(a.o, this.a | 3, this, function() {
+ return this.Ka.Na & 255
+ });
+ m(a.o, this.a | 4, this, function() {
+ return this.Ka.Da & 255
+ });
+ m(a.o, this.a | 5, this, function() {
+ return this.Ka.Ga & 255
+ });
+ m(a.o, this.a | 6, this, function() {
+ return this.Ka.Mc
+ });
+ n(a.o, this.a | 0, this, function(a) {
+ Rb(this.Ka, a, 1)
+ }, function(a) {
+ Rb(this.Ka, a, 2)
+ }, function(a) {
+ Rb(this.Ka, a, 4)
+ });
+ n(a.o, this.a | 1, this, function(a) {
+ this.sa.ud = (this.sa.ud << 8 | a) & 65535;
+ this.Ca.ud = (this.Ca.ud << 8 | a) & 65535
+ });
+ n(a.o, this.a | 2, this,
+ function(a) {
+ this.sa.pa = (this.sa.pa << 8 | a) & 65535;
+ this.Ca.pa = (this.Ca.pa << 8 | a) & 65535
+ });
+ n(a.o, this.a | 3, this, function(a) {
+ this.sa.Na = (this.sa.Na << 8 | a) & 65535;
+ this.Ca.Na = (this.Ca.Na << 8 | a) & 65535
+ });
+ n(a.o, this.a | 4, this, function(a) {
+ this.sa.Da = (this.sa.Da << 8 | a) & 65535;
+ this.Ca.Da = (this.Ca.Da << 8 | a) & 65535
+ });
+ n(a.o, this.a | 5, this, function(a) {
+ this.sa.Ga = (this.sa.Ga << 8 | a) & 65535;
+ this.Ca.Ga = (this.Ca.Ga << 8 | a) & 65535
+ });
+ n(a.o, this.a | 6, this, function(a) {
+ this.Ka = a & 16 ? this.Ca : this.sa;
+ this.sa.Mc = a;
+ this.Ca.Mc = a;
+ this.sa.le = this.Ca.le =
+ a >> 6 & 1;
+ this.sa.head = this.Ca.head = a & 15
+ });
+ this.l = this.Ha = this.Dd = 0;
+ n(a.o, this.a | 7, this, function(a) {
+ Pb(this.j, this.ua);
+ var b = this.Ka;
+ if (b.buffer) switch (b.v = a, b.error = 0, a) {
+ case 8:
+ b.i = 0;
+ b.a = 0;
+ b.g = 0;
+ Sb(b);
+ b.ba();
+ break;
+ case 16:
+ b.status = 80;
+ b.Da = 0;
+ b.ba();
+ break;
+ case 248:
+ b.status = 80;
+ var c = b.l - 1;
+ b.Na = c & 255;
+ b.Da = c >> 8 & 255;
+ b.Ga = c >> 16 & 255;
+ b.Mc = b.Mc & 240 | c >> 24 & 15;
+ b.ba();
+ break;
+ case 39:
+ b.status = 80;
+ c = b.l - 1;
+ b.Na = c & 255;
+ b.Da = c >> 8 & 255;
+ b.Ga = c >> 16 & 255;
+ b.Na |= c >> 24 << 8 & 65280;
+ b.ba();
+ break;
+ case 32:
+ case 36:
+ case 41:
+ case 196:
+ Tb(b,
+ a);
+ break;
+ case 48:
+ case 52:
+ case 57:
+ case 197:
+ var e = 52 === a || 57 === a;
+ c = Ub(b, e);
+ e = Vb(b, e);
+ a = 48 === a || 52 === a;
+ c *= b.m;
+ e *= b.m;
+ e + c > b.buffer.byteLength ? (b.status = 255, b.ba()) : (b.status = 88, Wb(b, c), b.a = a ? 512 : Math.min(c, 512 * b.W), b.qa = e);
+ break;
+ case 144:
+ b.ba();
+ b.error = 257;
+ b.status = 80;
+ break;
+ case 145:
+ b.status = 80;
+ b.ba();
+ break;
+ case 160:
+ b.R && (b.status = 88, Xb(b, 12), b.a = 12, b.pa = 1, b.ba());
+ break;
+ case 161:
+ b.R ? (Yb(b), b.status = 88, b.Da = 20, b.Ga = 235) : b.status = 65;
+ b.ba();
+ break;
+ case 198:
+ b.W = b.pa & 255;
+ b.status = 80;
+ b.ba();
+ break;
+ case 37:
+ case 200:
+ c =
+ 37 === a;
+ e = Ub(b, c);
+ Vb(b, c) * b.m + e * b.m > b.buffer.byteLength ? (b.status = 255, b.ba()) : (b.status = 88, b.ia.Ha |= 1);
+ break;
+ case 53:
+ case 202:
+ c = 53 === a;
+ e = Ub(b, c);
+ Vb(b, c) * b.m + e * b.m > b.buffer.byteLength ? (b.status = 255, b.ba()) : (b.status = 88, b.ia.Ha |= 1);
+ break;
+ case 64:
+ b.status = 80;
+ b.ba();
+ break;
+ case 218:
+ b.status = 65;
+ b.error = 4;
+ b.ba();
+ break;
+ case 224:
+ b.status = 80;
+ b.ba();
+ break;
+ case 225:
+ b.status = 80;
+ b.ba();
+ break;
+ case 231:
+ b.status = 80;
+ b.ba();
+ break;
+ case 236:
+ if (b.R) {
+ b.status = 65;
+ b.error = 4;
+ b.ba();
+ break
+ }
+ Yb(b);
+ b.status = 88;
+ b.ba();
+ break;
+ case 234:
+ b.status =
+ 80;
+ b.ba();
+ break;
+ case 239:
+ b.status = 80;
+ b.ba();
+ break;
+ case 245:
+ b.status = 80;
+ b.ba();
+ break;
+ case 249:
+ b.status = 65;
+ b.error = 4;
+ break;
+ default:
+ b.status = 65, b.error = 4
+ } else b.error = 4, b.status = 65, b.ba()
+ });
+ m(a.o, this.g | 4, this, void 0, void 0, this.Yh);
+ n(a.o, this.g | 4, this, void 0, void 0, this.bi);
+ m(a.o, this.g, this, this.$h, void 0, this.Zh);
+ n(a.o, this.g, this, this.Kg, void 0, this.ci);
+ m(a.o, this.g | 2, this, this.ai);
+ n(a.o, this.g | 2, this, this.Lg);
+ m(a.o, this.g | 8, this, function() {
+ return 0
+ });
+ m(a.o, this.g | 10, this, function() {
+ return 0
+ });
+ Zb(a.G.wb,
+ this)
+}
+k = Nb.prototype;
+k.zh = function() {
+ return this.Ka.buffer ? this.Ka.status : 0
+};
+k.xk = function(a) {
+ a & 4 && (Pb(this.j, this.ua), Sb(this.sa), Sb(this.Ca));
+ this.m = a
+};
+k.Yh = function() {
+ return this.Dd
+};
+k.bi = function(a) {
+ this.Dd = a
+};
+k.ai = function() {
+ return this.Ha
+};
+k.Lg = function(a) {
+ this.Ha &= ~(a & 6)
+};
+k.Zh = function() {
+ return this.l | this.Ha << 16
+};
+k.$h = function() {
+ return this.l
+};
+k.ci = function(a) {
+ this.Kg(a & 255);
+ this.Lg(a >> 16 & 255)
+};
+k.Kg = function(a) {
+ var b = this.l;
+ this.l = a & 9;
+ if ((b & 1) !== (a & 1))
+ if (0 === (a & 1)) this.Ha &= -2;
+ else switch (this.Ha |= 1, this.Ka.v) {
+ case 37:
+ case 200:
+ $b(this.Ka);
+ break;
+ case 202:
+ case 53:
+ ac(this.Ka);
+ break;
+ case 160:
+ bc(this.Ka)
+ }
+};
+k.ba = function() {
+ 0 === (this.m & 2) && (this.Ha |= 4, this.j.Cb(this.ua))
+};
+k.Sa = function() {
+ var a = [];
+ a[0] = this.sa;
+ a[1] = this.Ca;
+ a[2] = this.a;
+ a[3] = this.ua;
+ a[4] = this.Hb;
+ a[5] = this.i;
+ a[6] = this.g;
+ a[7] = this.name;
+ a[8] = this.m;
+ a[9] = this.Dd;
+ a[10] = this.Ha;
+ a[11] = this.Ka === this.sa;
+ a[12] = this.l;
+ return a
+};
+k.fb = function(a) {
+ this.sa = a[0];
+ this.Ca = a[1];
+ this.a = a[2];
+ this.ua = a[3];
+ this.Hb = a[4];
+ this.i = a[5];
+ this.g = a[6];
+ this.name = a[7];
+ this.m = a[8];
+ this.Dd = a[9];
+ this.Ha = a[10];
+ this.Ka = a[11] ? this.sa : this.Ca;
+ this.l = a[12]
+};
+
+function Ob(a, b, c, d, e, f) {
+ this.ia = a;
+ this.w = f;
+ this.Fa = e;
+ this.j = b;
+ this.buffer = c;
+ this.m = d ? 2048 : 512;
+ this.R = d;
+ this.O = this.C = this.J = this.l = 0;
+ this.buffer && (this.l = this.buffer.byteLength / this.m, this.l !== (this.l | 0) && (this.l = Math.ceil(this.l)), d ? (this.J = 1, this.C = 0) : (this.J = 16, this.C = 63), this.O = this.l / this.J / this.C, this.O !== (this.O | 0) && (this.O = Math.floor(this.O)), a = b.G.bd, a.ha[57] |= 1 << 4 * this.Fa, a.ha[18] = a.ha[18] & 15 | 240, a.ha[27] = this.O & 255, a.ha[28] = this.O >> 8 & 255, a.ha[29] = this.J & 255, a.ha[30] = 255, a.ha[31] = 255, a.ha[32] =
+ 200, a.ha[33] = this.O & 255, a.ha[34] = this.O >> 8 & 255, a.ha[35] = this.C & 255);
+ this.Oa = {
+ Eh: 0,
+ Fh: 0,
+ Bg: 0,
+ Cg: 0,
+ Yg: !1
+ };
+ this.buffer = c;
+ this.Mc = this.head = this.Ga = this.Da = this.ud = this.Na = this.pa = this.le = 0;
+ this.status = 80;
+ this.W = 128;
+ this.i = this.error = 0;
+ this.data = new Uint8Array(65536);
+ this.oa = new Uint16Array(this.data.buffer);
+ this.Z = new Int32Array(this.data.buffer);
+ this.a = this.g = 0;
+ this.ka = this.v = -1;
+ this.qa = 0;
+ Object.seal(this)
+}
+
+function Sb(a) {
+ a.R ? (a.status = 0, a.pa = 1, a.error = 1, a.Na = 1, a.Da = 20, a.Ga = 235) : (a.status = 81, a.pa = 1, a.error = 1, a.Na = 1, a.Da = 0, a.Ga = 0)
+}
+Ob.prototype.ba = function() {
+ this.ia.ba()
+};
+Ob.prototype.Me = function() {
+ this.status = 80;
+ var a = this.data.subarray(0, this.g);
+ cc(this, this.v, this.g / 512);
+ this.ba();
+ this.buffer.set(this.qa, a, function() {});
+ dc(this, this.g)
+};
+
+function ec(a, b) {
+ var c = (b[7] << 8 | b[8]) * a.m;
+ b = (b[2] << 24 | b[3] << 16 | b[4] << 8 | b[5]) * a.m;
+ a.g = 0;
+ var d = a.Ga << 8 & 65280 | a.Da & 255;
+ a.Da = a.Ga = 0;
+ 65535 === d && d--;
+ d > c && (d = c);
+ b >= a.buffer.byteLength ? (a.status = 255, a.ba()) : 0 === c ? (a.status = 80, a.i = 0) : (c = Math.min(c, a.buffer.byteLength - b), a.status = 208, fc(a), a.buffer.get(b, c, function(b) {
+ gc(a, b);
+ a.status = 88;
+ a.pa = a.pa & -8 | 2;
+ a.ba();
+ d &= -4;
+ a.a = d;
+ a.a > a.g && (a.a = a.g);
+ a.Da = a.a & 255;
+ a.Ga = a.a >> 8 & 255;
+ hc(a, c)
+ }))
+}
+
+function ic(a, b) {
+ var c = (b[7] << 8 | b[8]) * a.m;
+ b = (b[2] << 24 | b[3] << 16 | b[4] << 8 | b[5]) * a.m;
+ b >= a.buffer.byteLength ? (a.status = 255, a.ba()) : (a.status = 208, fc(a), a.buffer.get(b, c, function(b) {
+ hc(a, c);
+ a.status = 88;
+ a.pa = a.pa & -8 | 2;
+ gc(a, b);
+ bc(a)
+ }))
+}
+
+function bc(a) {
+ if (0 !== (a.ia.Ha & 1) && 0 !== (a.status & 8)) {
+ var b = a.ia.Dd,
+ c = 0,
+ d = a.data;
+ do {
+ var e = jc(a.j, b),
+ f = a.j.ma(b + 4),
+ h = a.j.ja(b + 7) & 128;
+ f || (f = 65536);
+ a.j.da.set(d.subarray(c, Math.min(c + f, a.g)), e);
+ c += f;
+ b += 8;
+ if (c >= a.g && !h) break
+ } while (!h);
+ a.status = 80;
+ a.ia.Ha &= -2;
+ a.pa = a.pa & -8 | 3;
+ a.ba()
+ }
+}
+
+function Qb(a, b) {
+ if (a.i < a.a) {
+ var c = 1 === b ? a.data[a.i] : 2 === b ? a.oa[a.i >>> 1] : a.Z[a.i >>> 2];
+ a.i += b;
+ a.i >= a.a && (160 === a.v ? a.a === a.g ? (a.status = 80, a.pa = a.pa & -8 | 3, a.ba()) : (a.status = 88, a.pa = a.pa & -8 | 2, a.ba(), b = a.Ga << 8 & 65280 | a.Da & 255, a.a + b > a.g ? (a.Da = a.g - a.a & 255, a.Ga = a.g - a.a >> 8 & 255, a.a = a.g) : a.a += b) : (a.error = 0, a.i >= a.g ? a.status = 80 : (b = 196 === a.v || 41 === a.v ? Math.min(a.W, (a.g - a.a) / 512) : 1, cc(a, a.v, b), a.a += 512 * b, a.status = 88), a.ba()));
+ return c
+ }
+ a.i += b;
+ return 0
+}
+
+function Rb(a, b, c) {
+ if (!(a.i >= a.a) && (1 === c ? a.data[a.i++] = b : 2 === c ? (a.oa[a.i >>> 1] = b, a.i += 2) : (a.Z[a.i >>> 2] = b, a.i += 4), a.i === a.a))
+ if (160 === a.v) {
+ a.i = 0;
+ a.ka = a.data[0];
+ switch (a.ka) {
+ case 0:
+ Xb(a, 0);
+ a.a = a.g;
+ a.status = 80;
+ break;
+ case 3:
+ Xb(a, a.data[4]);
+ a.a = a.g;
+ a.status = 88;
+ a.data[0] = 240;
+ a.data[2] = 5;
+ a.data[7] = 8;
+ break;
+ case 18:
+ b = a.data[4];
+ a.status = 88;
+ a.data.set([5, 128, 1, 49, 31, 0, 0, 0, 83, 79, 78, 89, 32, 32, 32, 32, 67, 68, 45, 82, 79, 77, 32, 67, 68, 85, 45, 49, 48, 48, 48, 32, 49, 46, 49, 97]);
+ a.a = a.g = Math.min(36, b);
+ break;
+ case 26:
+ Xb(a, a.data[4]);
+ a.a = a.g;
+ a.status = 88;
+ break;
+ case 30:
+ Xb(a, 0);
+ a.a = a.g;
+ a.status = 80;
+ break;
+ case 37:
+ b = a.l - 1;
+ gc(a, new Uint8Array([b >> 24 & 255, b >> 16 & 255, b >> 8 & 255, b & 255, 0, 0, a.m >> 8 & 255, a.m & 255]));
+ a.a = a.g;
+ a.status = 88;
+ break;
+ case 40:
+ a.ud & 1 ? ic(a, a.data) : ec(a, a.data);
+ break;
+ case 66:
+ b = a.data[8];
+ Xb(a, Math.min(8, b));
+ a.a = a.g;
+ a.status = 88;
+ break;
+ case 67:
+ b = a.data[8] | a.data[7] << 8;
+ c = a.data[9] >> 6;
+ Xb(a, b);
+ a.a = a.g;
+ 0 === c ? (b = a.l, a.data.set(new Uint8Array([0, 18, 1, 1, 0, 20, 1, 0, 0, 0, 0, 0, 0, 22, 170, 0, b >> 24, b >> 16 & 255, b >> 8 & 255, b & 255]))) : 1 === c && a.data.set(new Uint8Array([0,
+ 10, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0
+ ]));
+ a.status = 88;
+ break;
+ case 70:
+ b = a.data[8] | a.data[7] << 8;
+ b = Math.min(b, 32);
+ Xb(a, b);
+ a.a = a.g;
+ a.data[0] = b - 4 >> 24 & 255;
+ a.data[1] = b - 4 >> 16 & 255;
+ a.data[2] = b - 4 >> 8 & 255;
+ a.data[3] = b - 4 & 255;
+ a.data[6] = 8;
+ a.data[10] = 3;
+ a.status = 88;
+ break;
+ case 81:
+ Xb(a, 0);
+ a.a = a.g;
+ a.status = 80;
+ break;
+ case 82:
+ a.status = 81;
+ a.g = 0;
+ a.error = 80;
+ break;
+ case 90:
+ b = a.data[8] | a.data[7] << 8;
+ 42 === a.data[2] && Xb(a, Math.min(30, b));
+ a.a = a.g;
+ a.status = 88;
+ break;
+ case 189:
+ Xb(a, a.data[9] | a.data[8] << 8);
+ a.a = a.g;
+ a.data[5] = 1;
+ a.status = 88;
+ break;
+ case 74:
+ a.status =
+ 81;
+ a.g = 0;
+ a.error = 80;
+ break;
+ default:
+ a.status = 81, a.g = 0, a.error = 80
+ }
+ a.pa = a.pa & -8 | 2;
+ 0 === (a.status & 128) && a.ba();
+ 0 === (a.status & 128) && 0 === a.g && (a.pa |= 1, a.status &= -9)
+ } else a.i >= a.g ? a.Me() : (a.status = 88, a.a += 512, a.ba())
+}
+
+function cc(a, b, c) {
+ a.pa -= c;
+ 36 === b || 41 === b || 52 === b || 57 === b || 37 === b || 53 === b ? (b = c + kc(a), a.Na = b & 255 | b >> 16 & 65280, a.Da = b >> 8 & 255, a.Ga = b >> 16 & 255) : a.le ? (b = c + lc(a), a.Na = b & 255, a.Da = b >> 8 & 255, a.Ga = b >> 16 & 255, a.head = a.head & -16 | b & 15) : (b = c + mc(a), c = b / (a.J * a.C) | 0, a.Da = c & 255, a.Ga = c >> 8 & 255, a.head = (b / a.C | 0) % a.J & 15, a.Na = b % a.C + 1 & 255, mc(a))
+}
+
+function Tb(a, b) {
+ var c = 36 === b || 41 === b,
+ d = Ub(a, c);
+ c = Vb(a, c);
+ var e = 32 === b || 36 === b,
+ f = d * a.m;
+ c *= a.m;
+ c + f > a.buffer.byteLength ? (a.status = 255, a.ba()) : (a.status = 192, fc(a), a.buffer.get(c, f, function(c) {
+ gc(a, c);
+ a.status = 88;
+ a.a = e ? 512 : Math.min(f, 512 * a.W);
+ cc(a, b, e ? 1 : Math.min(d, a.C));
+ a.ba();
+ hc(a, f)
+ }))
+}
+
+function $b(a) {
+ var b = 37 === a.v,
+ c = Ub(a, b);
+ b = Vb(a, b);
+ var d = c * a.m;
+ b *= a.m;
+ fc(a);
+ a.buffer.get(b, d, function(b) {
+ var e = a.ia.Dd,
+ h = 0;
+ do {
+ var g = jc(a.j, e),
+ p = a.j.ma(e + 4),
+ r = a.j.ja(e + 7) & 128;
+ p || (p = 65536);
+ a.j.da.set(b.subarray(h, h + p), g);
+ h += p;
+ e += 8
+ } while (!r);
+ cc(a, a.v, c);
+ a.status = 80;
+ a.ia.Ha &= -2;
+ a.v = -1;
+ a.ba();
+ hc(a, d)
+ })
+}
+
+function ac(a) {
+ var b = 53 === a.v,
+ c = Ub(a, b),
+ d = Vb(a, b);
+ b = c * a.m;
+ d *= a.m;
+ var e = a.ia.Dd,
+ f = 0,
+ h = 0,
+ g = 0;
+ do {
+ var p = jc(a.j, e),
+ r = a.j.ma(e + 4),
+ v = a.j.ja(e + 7) & 128;
+ r || (r = 65536);
+ a.buffer.set(d + g, a.j.da.subarray(p, p + r), function() {
+ h++
+ });
+ g += r;
+ e += 8;
+ f++
+ } while (!v);
+ h === f && (cc(a, a.v, c), a.status = 80, a.ba(), a.ia.Ha &= -2, a.v = -1);
+ dc(a, b)
+}
+
+function mc(a) {
+ return ((a.Da & 255 | a.Ga << 8 & 65280) * a.J + a.head) * a.C + (a.Na & 255) - 1
+}
+
+function lc(a) {
+ return a.Na & 255 | a.Da << 8 & 65280 | a.Ga << 16 & 16711680 | (a.head & 15) << 24
+}
+
+function kc(a) {
+ return (a.Na & 255 | a.Da << 8 & 65280 | a.Ga << 16 & 16711680 | a.Na >> 8 << 24 & 4278190080) >>> 0
+}
+
+function Vb(a, b) {
+ return b ? kc(a) : a.le ? lc(a) : mc(a)
+}
+
+function Ub(a, b) {
+ b ? (a = a.pa, 0 === a && (a = 65536)) : (a = a.pa & 255, 0 === a && (a = 256));
+ return a
+}
+
+function Yb(a) {
+ if (a.Mc & 16) Xb(a, 0);
+ else {
+ for (var b = 0; 512 > b; b++) a.data[b] = 0;
+ b = Math.min(16383, a.O);
+ gc(a, [64, a.R ? 133 : 0, b, b >> 8, 0, 0, a.J, a.J >> 8, a.C / 512, a.C / 512 >> 8, 0, 2, a.C, a.C >> 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 118, 32, 54, 68, 72, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 128, 0, 1, 0, 0, 2, 0, 0, 0, 2, 0, 2, 7, 0, b, b >> 8, a.J, a.J >> 8, a.C, 0, a.l & 255, a.l >> 8 & 255, a.l >> 16 & 255, a.l >> 24 & 255, 0, 0, a.l & 255, a.l >> 8 & 255, a.l >> 16 & 255,
+ a.l >> 24 & 255, 0, 0, 160 === a.v ? 0 : 7, 160 === a.v ? 0 : 4, 0, 0, 30, 0, 30, 0, 30, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 126, 0, 0, 0, 0, 0, 0, 116, 0, 64, 0, 64, 0, 116, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a.l & 255, a.l >> 8 & 255, a.l >> 16 & 255, a.l >> 24 & 255
+ ]);
+ a.g = 512;
+ a.a = 512
+ }
+}
+
+function Xb(a, b) {
+ Wb(a, b);
+ for (var c = 0; c < b + 3 >> 2; c++) a.Z[c] = 0
+}
+
+function Wb(a, b) {
+ a.data.length < b && (a.data = new Uint8Array(b + 3 & -4), a.oa = new Uint16Array(a.data.buffer), a.Z = new Int32Array(a.data.buffer));
+ a.g = b;
+ a.i = 0
+}
+
+function gc(a, b) {
+ Wb(a, b.length);
+ a.data.set(b)
+}
+
+function fc(a) {
+ a.Oa.Yg = !0;
+ a.w.send("ide-read-start")
+}
+
+function hc(a, b) {
+ a.Oa.Yg = !1;
+ var c = b / a.m | 0;
+ a.Oa.Eh += c;
+ a.Oa.Bg += b;
+ a.w.send("ide-read-end", [a.Fa, b, c])
+}
+
+function dc(a, b) {
+ var c = b / a.m | 0;
+ a.Oa.Fh += c;
+ a.Oa.Cg += b;
+ a.w.send("ide-write-end", [a.Fa, b, c])
+}
+Ob.prototype.Sa = function() {
+ var a = [];
+ a[0] = this.pa;
+ a[1] = this.O;
+ a[2] = this.Ga;
+ a[3] = this.Da;
+ a[4] = this.i;
+ a[5] = 0;
+ a[6] = 0;
+ a[7] = 0;
+ a[8] = 0;
+ a[9] = this.Mc;
+ a[10] = this.error;
+ a[11] = this.head;
+ a[12] = this.J;
+ a[13] = this.R;
+ a[14] = this.le;
+ a[15] = this.ud;
+ a[16] = this.data;
+ a[17] = this.g;
+ a[18] = this.Na;
+ a[19] = this.l;
+ a[20] = this.m;
+ a[21] = this.W;
+ a[22] = this.C;
+ a[23] = this.status;
+ a[24] = this.qa;
+ a[25] = this.v;
+ a[26] = this.a;
+ a[27] = this.ka;
+ return a
+};
+Ob.prototype.fb = function(a) {
+ this.pa = a[0];
+ this.O = a[1];
+ this.Ga = a[2];
+ this.Da = a[3];
+ this.i = a[4];
+ this.Mc = a[9];
+ this.error = a[10];
+ this.head = a[11];
+ this.J = a[12];
+ this.R = a[13];
+ this.le = a[14];
+ this.ud = a[15];
+ this.data = a[16];
+ this.g = a[17];
+ this.Na = a[18];
+ this.l = a[19];
+ this.m = a[20];
+ this.W = a[21];
+ this.C = a[22];
+ this.status = a[23];
+ this.qa = a[24];
+ this.v = a[25];
+ this.a = a[26];
+ this.ka = a[27];
+ this.oa = new Uint16Array(this.data.buffer);
+ this.Z = new Int32Array(this.data.buffer)
+};
+
+function nc(a) {
+ this.mc = new Uint8Array(4);
+ this.a = new Uint8Array(4);
+ this.zd = new Uint8Array(4);
+ this.Ad = new Uint8Array(4);
+ this.yd = new Int32Array(this.mc.buffer);
+ new Int32Array(this.a.buffer);
+ this.eh = new Int32Array(this.zd.buffer);
+ this.gh = new Int32Array(this.Ad.buffer);
+ this.fc = [];
+ this.G = [];
+ this.j = a;
+ for (var b = 0; 256 > b; b++) this.fc[b] = void 0, this.G[b] = void 0;
+ this.o = a.o;
+ n(a.o, 3324, this, function(a) {
+ oc(this, this.yd[0], a)
+ }, function(a) {
+ pc(this, this.yd[0], a)
+ }, function(a) {
+ var b = this.yd[0],
+ c = b >> 8 & 65535,
+ f = b & 255;
+ b =
+ this.fc[c];
+ c = this.G[c];
+ if (b)
+ if (16 <= f && 40 > f)
+ if (c = c.nc[f - 16 >> 2]) {
+ f >>= 2;
+ var h = b[f] & 1; - 1 === (a | 3 | c.size - 1) ? (a = ~(c.size - 1) | h, 0 === h && (b[f] = a)) : 0 === h && (b[f] = c.dh);
+ 1 === h && (qc(this, c, b[f] & 65534, a & 65534), b[f] = a | 1)
+ } else b[f >> 2] = 0;
+ else 48 === f ? b[f >> 2] = c.fh ? -1 === (a | 2047) ? -c.fh | 0 : c.Ei | 0 : 0 : b[f >>> 2] = a
+ });
+ n(a.o, 3325, this, function(a) {
+ oc(this, this.yd[0] + 1 | 0, a)
+ });
+ n(a.o, 3326, this, function(a) {
+ oc(this, this.yd[0] + 2 | 0, a)
+ }, function(a) {
+ pc(this, this.yd[0] + 2 | 0, a)
+ });
+ n(a.o, 3327, this, function(a) {
+ oc(this, this.yd[0] + 3 | 0, a)
+ });
+ a.o.te(3324,
+ this,
+ function() {
+ return this.zd[0]
+ },
+ function() {
+ return this.zd[1]
+ },
+ function() {
+ return this.zd[2]
+ },
+ function() {
+ return this.zd[3]
+ });
+ a.o.te(3320, this, function() {
+ return this.Ad[0]
+ }, function() {
+ return this.Ad[1]
+ }, function() {
+ return this.Ad[2]
+ }, function() {
+ return this.Ad[3]
+ });
+ a.o.Gc(3320, this, function(a) {
+ this.mc[0] = a & 252
+ }, function(a) {
+ this.mc[1] = a
+ }, function(a) {
+ this.mc[2] = a
+ }, function(a) {
+ this.mc[3] = a;
+ a = this.mc[0] & 252;
+ var b = this.fc[this.mc[2] << 8 | this.mc[1]];
+ void 0 !== b ? (this.gh[0] = -2147483648, this.eh[0] = a < b.byteLength ?
+ b[a >> 2] : 0) : (this.eh[0] = -1, this.gh[0] = 0)
+ });
+ Zb(this, {
+ Hb: 0,
+ pe: [134, 128, 55, 18, 0, 0, 0, 0, 2, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ nc: [],
+ name: "82441FX PMC"
+ });
+ this.i = {
+ Hb: 8,
+ pe: [134, 128, 0, 112, 7, 0, 0, 2, 0, 0, 1, 6, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ nc: [],
+ name: "82371SB PIIX3 ISA"
+ };
+ this.l = Zb(this, this.i);
+ this.g = new Uint8Array(this.l.buffer)
+}
+nc.prototype.Sa = function() {
+ for (var a = [], b = 0; 256 > b; b++) a[b] = this.fc[b];
+ a[256] = this.mc;
+ a[257] = this.a;
+ a[258] = this.zd;
+ a[259] = this.Ad;
+ return a
+};
+nc.prototype.fb = function(a) {
+ for (var b = 0; 256 > b; b++) {
+ var c = this.G[b],
+ d = a[b];
+ if (c && d) {
+ for (var e = 0; e < c.nc.length; e++) {
+ var f = d[4 + e];
+ if (f & 1) {
+ var h = c.nc[e];
+ qc(this, h, h.dh & 65534, f & 65534)
+ }
+ }
+ this.fc[b].set(d)
+ }
+ }
+ this.mc.set(a[256]);
+ this.a.set(a[257]);
+ this.zd.set(a[258]);
+ this.Ad.set(a[259])
+};
+
+function oc(a, b, c) {
+ var d = b & 255;
+ (new Uint8Array(a.fc[b >> 8 & 65535].buffer))[d] = c
+}
+
+function pc(a, b, c) {
+ var d = b & 255;
+ (new Uint16Array(a.fc[b >> 8 & 65535].buffer))[d >>> 1] = c
+}
+
+function Zb(a, b) {
+ var c = b.Hb,
+ d = new Int32Array(64);
+ d.set(new Int32Array((new Uint8Array(b.pe)).buffer));
+ a.fc[c] = d;
+ a.G[c] = b;
+ c = d.slice(4, 10);
+ for (var e = 0; e < b.nc.length; e++) {
+ var f = b.nc[e];
+ if (f) {
+ var h = c[e],
+ g = h & 1;
+ f.dh = h;
+ f.entries = [];
+ if (0 !== g)
+ for (h &= -2, g = 0; g < f.size; g++) f.entries[g] = a.o.ports[h + g]
+ }
+ }
+ return d
+}
+
+function qc(a, b, c, d) {
+ for (var e = b.size, f = a.o.ports, h = 0; h < e; h++) f[c + h] = Oa(a.o), f[d + h] = b.entries[h]
+}
+nc.prototype.xb = function(a) {
+ this.j.Cb(this.g[96 + ((this.fc[a][15] >> 8 & 255) - 1 + ((a >> 3) - 1 & 255) & 3)])
+};
+
+function rc(a, b) {
+ Pb(a.j, a.g[96 + ((a.fc[b][15] >> 8 & 255) + (b >> 3 & 255) - 2 & 3)])
+};
+
+function sc(a, b) {
+ this.o = a.o;
+ this.j = a;
+ this.Ub = a.G.Ub;
+ this.g = 0;
+ this.ka = new Uint8Array(10);
+ this.oa = 0;
+ this.l = null;
+ this.a = new Uint8Array(10);
+ this.C = this.m = this.i = 0;
+ this.W = b;
+ this.Z = this.O = this.Xa = this.Bb = this.Za = this.Ya = 0;
+ this.qa = 1;
+ this.v = 0;
+ if (b) {
+ this.C = b.byteLength;
+ var c;
+ if ((c = {
+ 160: {
+ type: 1,
+ bc: 40,
+ ac: 8,
+ Yb: 1
+ },
+ 180: {
+ type: 1,
+ bc: 40,
+ ac: 9,
+ Yb: 1
+ },
+ 200: {
+ type: 1,
+ bc: 40,
+ ac: 10,
+ Yb: 1
+ },
+ 320: {
+ type: 1,
+ bc: 40,
+ ac: 8,
+ Yb: 2
+ },
+ 360: {
+ type: 1,
+ bc: 40,
+ ac: 9,
+ Yb: 2
+ },
+ 400: {
+ type: 1,
+ bc: 40,
+ ac: 10,
+ Yb: 2
+ },
+ 720: {
+ type: 3,
+ bc: 80,
+ ac: 9,
+ Yb: 2
+ },
+ 1200: {
+ type: 2,
+ bc: 80,
+ ac: 15,
+ Yb: 2
+ },
+ 1440: {
+ type: 4,
+ bc: 80,
+ ac: 18,
+ Yb: 2
+ },
+ 1722: {
+ type: 5,
+ bc: 82,
+ ac: 21,
+ Yb: 2
+ },
+ 2880: {
+ type: 5,
+ bc: 80,
+ ac: 36,
+ Yb: 2
+ }
+ }[this.C >> 10]) && 0 === (this.C & 1023)) a.G.bd.ha[16] = c.type << 4, a = c.ac, b = c.Yb, c = c.bc;
+ else throw "Unknown floppy size: " + jb(b.byteLength);
+ this.J = a;
+ this.R = b;
+ this.Fa = c
+ } else a.G.bd.ha[16] = 64, this.C = this.Fa = this.R = this.J = 0;
+ m(this.o, 1008, this, this.Oj);
+ m(this.o, 1010, this, this.Pj);
+ m(this.o, 1012, this, this.Rj);
+ m(this.o, 1013, this, this.Sj);
+ m(this.o, 1015, this, this.Uj);
+ n(this.o, 1010, this, this.Qj);
+ n(this.o, 1013, this, this.Tj)
+}
+k = sc.prototype;
+k.Sa = function() {
+ var a = [];
+ a[0] = this.g;
+ a[1] = this.ka;
+ a[2] = this.oa;
+ a[4] = this.a;
+ a[5] = this.i;
+ a[6] = this.m;
+ a[7] = this.C;
+ a[8] = this.Ya;
+ a[9] = this.Za;
+ a[10] = this.Bb;
+ a[11] = this.Xa;
+ a[12] = this.O;
+ a[13] = this.Z;
+ a[14] = this.qa;
+ a[15] = this.v;
+ a[16] = this.J;
+ a[17] = this.R;
+ a[18] = this.Fa;
+ return a
+};
+k.fb = function(a) {
+ this.g = a[0];
+ this.ka = a[1];
+ this.oa = a[2];
+ this.l = a[3];
+ this.a = a[4];
+ this.i = a[5];
+ this.m = a[6];
+ this.C = a[7];
+ this.Ya = a[8];
+ this.Za = a[9];
+ this.Bb = a[10];
+ this.Xa = a[11];
+ this.O = a[12];
+ this.Z = a[13];
+ this.qa = a[14];
+ this.v = a[15];
+ this.J = a[16];
+ this.R = a[17];
+ this.Fa = a[18]
+};
+k.Oj = function() {
+ return 0
+};
+k.Rj = function() {
+ var a = 128;
+ this.i < this.m && (a |= 80);
+ 0 === (this.v & 8) && (a |= 32);
+ return a
+};
+k.Uj = function() {
+ return 0
+};
+k.Sj = function() {
+ return this.i < this.m ? (Pb(this.j, 6), this.a[this.i++]) : 255
+};
+k.Tj = function(a) {
+ if (this.W)
+ if (0 < this.g) this.ka[this.oa++] = a, this.g--, 0 === this.g && this.l.call(this, this.ka);
+ else {
+ switch (a) {
+ case 3:
+ this.l = this.li;
+ this.g = 2;
+ break;
+ case 4:
+ this.l = this.Qh;
+ this.g = 1;
+ break;
+ case 5:
+ case 197:
+ this.l = function(a) {
+ tc(this, !0, a)
+ };
+ this.g = 8;
+ break;
+ case 230:
+ this.l = function(a) {
+ tc(this, !1, a)
+ };
+ this.g = 8;
+ break;
+ case 7:
+ this.l = this.Ph;
+ this.g = 1;
+ break;
+ case 8:
+ this.i = 0;
+ this.m = 2;
+ this.a[0] = 32;
+ this.a[1] = this.O;
+ break;
+ case 74:
+ this.l = this.fk;
+ this.g = 1;
+ break;
+ case 15:
+ this.g = 2;
+ this.l = this.Kh;
+ break;
+ case 14:
+ this.a[0] =
+ 128, this.i = 0, this.m = 1, this.g = 0
+ }
+ this.oa = 0
+ }
+};
+k.Pj = function() {
+ return this.v
+};
+k.Qj = function(a) {
+ 4 === (a & 4) && 0 === (this.v & 4) && this.j.Cb(6);
+ this.v = a
+};
+k.Qh = function() {
+ this.i = 0;
+ this.m = 1;
+ this.a[0] = 32
+};
+k.Kh = function(a) {
+ this.O = a[1];
+ this.Z = a[0] >> 2 & 1;
+ this.xb()
+};
+k.Ph = function() {
+ this.xb()
+};
+
+function tc(a, b, c) {
+ var d = c[2],
+ e = c[1],
+ f = c[3],
+ h = 128 << c[4],
+ g = c[5] - c[3] + 1,
+ p = ((d + a.R * e) * a.J + f - 1) * h;
+ a.W && (b ? a.Ub.Me(a.W, p, g * h, 2, a.done.bind(a, c, e, d, f)) : uc(a.Ub, a.W, p, a.done.bind(a, c, e, d, f)))
+}
+k.done = function(a, b, c, d, e) {
+ e || (d++, d > this.J && (d = 1, c++, c >= this.R && (c = 0, b++)), this.O = b, this.Z = c, this.qa = d, this.i = 0, this.m = 7, this.a[0] = c << 2 | 32, this.a[1] = 0, this.a[2] = 0, this.a[3] = b, this.a[4] = c, this.a[5] = d, this.a[6] = a[4], this.xb())
+};
+k.li = function() {};
+k.fk = function() {
+ this.i = 0;
+ this.m = 7;
+ this.a[0] = 0;
+ this.a[1] = 0;
+ this.a[2] = 0;
+ this.a[3] = 0;
+ this.a[4] = 0;
+ this.a[5] = 0;
+ this.a[6] = 0;
+ this.xb()
+};
+k.xb = function() {
+ this.v & 8 && this.j.Cb(6)
+};
+
+function vc(a, b) {
+ a = a.Ye[b >>> 17];
+ return a(b) | a(b + 1 | 0) << 8
+}
+
+function wc(a, b, c) {
+ a = a.Ze[b >>> 17];
+ a(b, c & 255);
+ a(b + 1 | 0, c >> 8 & 255)
+}
+
+function Ra(a, b) {
+ return 655360 <= (b | 0) && 786432 > (b | 0) || b >>> 0 >= a.Ia >>> 0
+}
+k = q.prototype;
+k.ja = function(a) {
+ return Ra(this, a) ? this.Ye[a >>> 17](a) : this.da[a]
+};
+k.ma = function(a) {
+ return Ra(this, a) ? vc(this, a) : this.da[a] | this.da[a + 1 | 0] << 8
+};
+
+function xc(a, b) {
+ return Ra(a, b << 1) ? vc(a, b << 1) : a.Ef[b]
+}
+
+function jc(a, b) {
+ return Ra(a, b) ? a.Ff[b >>> 17](b) : a.da[b] | a.da[b + 1 | 0] << 8 | a.da[b + 2 | 0] << 16 | a.da[b + 3 | 0] << 24
+}
+
+function yc(a, b) {
+ Ra(a, b << 2) ? (b <<= 2, a = a.Ff[b >>> 17](b)) : a = a.Cc[b];
+ return a
+}
+k.za = function(a, b) {
+ if (Ra(this, a)) this.Ze[a >>> 17](a, b);
+ else this.da[a] = b
+};
+k.ze = function(a, b) {
+ Ra(this, a) ? wc(this, a, b) : (this.da[a] = b, this.da[a + 1 | 0] = b >> 8)
+};
+
+function zc(a, b, c) {
+ Ra(a, b << 1) ? wc(a, b << 1, c) : a.Ef[b] = c
+}
+k.fd = function(a, b) {
+ if (Ra(this, a)) this.Gf[a >>> 17](a, b);
+ else this.da[a] = b, this.da[a + 1 | 0] = b >> 8, this.da[a + 2 | 0] = b >> 16, this.da[a + 3 | 0] = b >> 24
+};
+
+function Ac(a, b, c) {
+ Ra(a, b << 2) ? (b <<= 2, a.Gf[b >>> 17](b, c)) : a.Cc[b] = c
+};
+
+function Bc(a) {
+ this.j = a;
+ this.v = new Uint8Array(8);
+ this.C = new Uint8Array(8);
+ this.a = new Uint16Array(8);
+ this.l = new Uint16Array(8);
+ this.g = new Uint16Array(8);
+ this.m = new Uint16Array(8);
+ this.vc = new Uint8Array(8);
+ this.J = new Uint8Array(8);
+ this.Wf = [];
+ this.i = 0;
+ a = a.o;
+ n(a, 0, this, this.Xc.bind(this, 0));
+ n(a, 2, this, this.Xc.bind(this, 1));
+ n(a, 4, this, this.Xc.bind(this, 2));
+ n(a, 6, this, this.Xc.bind(this, 3));
+ n(a, 1, this, this.Zc.bind(this, 0));
+ n(a, 3, this, this.Zc.bind(this, 1));
+ n(a, 5, this, this.Zc.bind(this, 2));
+ n(a, 7, this, this.Zc.bind(this,
+ 3));
+ m(a, 0, this, this.Wc.bind(this, 0));
+ m(a, 2, this, this.Wc.bind(this, 1));
+ m(a, 4, this, this.Wc.bind(this, 2));
+ m(a, 6, this, this.Wc.bind(this, 3));
+ m(a, 1, this, this.Yc.bind(this, 0));
+ m(a, 3, this, this.Yc.bind(this, 1));
+ m(a, 5, this, this.Yc.bind(this, 2));
+ m(a, 7, this, this.Yc.bind(this, 3));
+ n(a, 192, this, this.Xc.bind(this, 4));
+ n(a, 196, this, this.Xc.bind(this, 5));
+ n(a, 200, this, this.Xc.bind(this, 6));
+ n(a, 204, this, this.Xc.bind(this, 7));
+ n(a, 194, this, this.Zc.bind(this, 4));
+ n(a, 198, this, this.Zc.bind(this, 5));
+ n(a, 202, this, this.Zc.bind(this,
+ 6));
+ n(a, 206, this, this.Zc.bind(this, 7));
+ m(a, 192, this, this.Wc.bind(this, 4));
+ m(a, 196, this, this.Wc.bind(this, 5));
+ m(a, 200, this, this.Wc.bind(this, 6));
+ m(a, 204, this, this.Wc.bind(this, 7));
+ m(a, 194, this, this.Yc.bind(this, 4));
+ m(a, 198, this, this.Yc.bind(this, 5));
+ m(a, 202, this, this.Yc.bind(this, 6));
+ m(a, 206, this, this.Yc.bind(this, 7));
+ n(a, 135, this, this.ad.bind(this, 0));
+ n(a, 131, this, this.ad.bind(this, 1));
+ n(a, 129, this, this.ad.bind(this, 2));
+ n(a, 130, this, this.ad.bind(this, 3));
+ n(a, 143, this, this.ad.bind(this, 4));
+ n(a, 139,
+ this, this.ad.bind(this, 5));
+ n(a, 137, this, this.ad.bind(this, 6));
+ n(a, 138, this, this.ad.bind(this, 7));
+ m(a, 135, this, this.$c.bind(this, 0));
+ m(a, 131, this, this.$c.bind(this, 1));
+ m(a, 129, this, this.$c.bind(this, 2));
+ m(a, 130, this, this.$c.bind(this, 3));
+ m(a, 143, this, this.$c.bind(this, 4));
+ m(a, 139, this, this.$c.bind(this, 5));
+ m(a, 137, this, this.$c.bind(this, 6));
+ m(a, 138, this, this.$c.bind(this, 7));
+ n(a, 1159, this, this.Cd.bind(this, 0));
+ n(a, 1155, this, this.Cd.bind(this, 1));
+ n(a, 1153, this, this.Cd.bind(this, 2));
+ n(a, 1154, this, this.Cd.bind(this,
+ 3));
+ n(a, 1163, this, this.Cd.bind(this, 5));
+ n(a, 1161, this, this.Cd.bind(this, 6));
+ n(a, 1162, this, this.Cd.bind(this, 7));
+ m(a, 1159, this, this.Bd.bind(this, 0));
+ m(a, 1155, this, this.Bd.bind(this, 1));
+ m(a, 1153, this, this.Bd.bind(this, 2));
+ m(a, 1154, this, this.Bd.bind(this, 3));
+ m(a, 1163, this, this.Bd.bind(this, 5));
+ m(a, 1161, this, this.Bd.bind(this, 6));
+ m(a, 1162, this, this.Bd.bind(this, 7));
+ n(a, 10, this, this.rh.bind(this, 0));
+ n(a, 212, this, this.rh.bind(this, 4));
+ n(a, 15, this, this.qh.bind(this, 0));
+ n(a, 222, this, this.qh.bind(this, 4));
+ m(a, 15, this, this.ph.bind(this, 0));
+ m(a, 222, this, this.ph.bind(this, 4));
+ n(a, 11, this, this.oh.bind(this, 0));
+ n(a, 214, this, this.oh.bind(this, 4));
+ n(a, 12, this, this.nh);
+ n(a, 216, this, this.nh)
+}
+k = Bc.prototype;
+k.Sa = function() {
+ return [this.v, this.C, this.a, this.l, this.g, this.m, this.vc, this.J, this.i]
+};
+k.fb = function(a) {
+ this.v = a[0];
+ this.C = a[1];
+ this.a = a[2];
+ this.l = a[3];
+ this.g = a[4];
+ this.m = a[5];
+ this.vc = a[6];
+ this.J = a[7];
+ this.i = a[8]
+};
+k.Zc = function(a, b) {
+ this.g[a] = Cc(this, this.g[a], b, !1);
+ this.m[a] = Cc(this, this.m[a], b, !0)
+};
+k.Yc = function(a) {
+ return Dc(this, this.g[a])
+};
+k.Xc = function(a, b) {
+ this.a[a] = Cc(this, this.a[a], b, !1);
+ this.l[a] = Cc(this, this.l[a], b, !0)
+};
+k.Wc = function(a) {
+ return Dc(this, this.a[a])
+};
+k.Cd = function(a, b) {
+ this.C[a] = b
+};
+k.Bd = function(a) {
+ return this.C[a]
+};
+k.ad = function(a, b) {
+ this.v[a] = b
+};
+k.$c = function(a) {
+ return this.v[a]
+};
+k.rh = function(a, b) {
+ Ec(this, (b & 3) + a, b & 4 ? 1 : 0)
+};
+k.qh = function(a, b) {
+ for (var c = 0; 4 > c; c++) Ec(this, a + c, b & 1 << c)
+};
+k.ph = function(a) {
+ var b = 0 | this.vc[a + 0];
+ b |= this.vc[a + 1] << 1;
+ b |= this.vc[a + 2] << 2;
+ return b |= this.vc[a + 3] << 3
+};
+k.oh = function(a, b) {
+ this.J[(b & 3) + a] = b
+};
+k.nh = function() {
+ this.i = 0
+};
+
+function Ec(a, b, c) {
+ if (a.vc[b] !== c && (a.vc[b] = c, !c))
+ for (c = 0; c < a.Wf.length; c++) a.Wf[c].wf.call(a.Wf[c].xg, b)
+}
+
+function uc(a, b, c, d) {
+ var e = a.g[2] + 1,
+ f = Fc(a, 2);
+ if (c + e > b.byteLength) d(!0);
+ else {
+ var h = a.j;
+ a.a[2] += e;
+ b.get(c, e, function(a) {
+ h.da.set(a, f);
+ d(!1)
+ })
+ }
+}
+k.Me = function(a, b, c, d, e) {
+ var f = this,
+ h = this.g[d] + 1 & 65535,
+ g = 5 <= d ? 2 : 1,
+ p = h * g,
+ r = Fc(this, d),
+ v = !1,
+ E = !1,
+ z = this.J[d] & 16;
+ c < p ? (h = Math.floor(c / g), p = h * g, v = !0) : c > p && (E = !0);
+ b + p > a.byteLength ? e(!0) : (this.a[d] += h, this.g[d] -= h, !v && z && (this.a[d] = this.l[d], this.g[d] = this.m[d]), a.set(b, this.j.da.subarray(r, r + p), function() {
+ E && z ? f.Me(a, b + p, c - p, d, e) : e(!1)
+ }))
+};
+
+function Fc(a, b) {
+ var c = a.a[b];
+ 5 <= b && (c <<= 1);
+ c = c & 65535 | a.v[b] << 16;
+ return c |= a.C[b] << 24
+}
+
+function Cc(a, b, c, d) {
+ d || (a.i ^= 1);
+ return a.i ? b & -256 | c : b & -65281 | c << 8
+}
+
+function Dc(a, b) {
+ a.i ^= 1;
+ return a.i ? b & 255 : b >> 8 & 255
+};
+
+function Ic(a, b) {
+ this.j = a;
+ this.w = b;
+ this.m = new Float64Array(3);
+ this.v = new Uint16Array(3);
+ this.g = new Uint8Array(4);
+ this.l = new Uint8Array(4);
+ this.i = new Uint8Array(4);
+ this.O = new Uint8Array(4);
+ this.C = new Uint8Array(4);
+ this.J = new Uint16Array(3);
+ this.a = new Uint16Array(3);
+ m(a.o, 97, this, function() {
+ var a = $a(),
+ b = 66.66666666666667 * a & 1;
+ a = Jc(this, 2, a);
+ return b << 4 | a << 5
+ });
+ n(a.o, 97, this, function(a) {
+ this.w.send("pcspeaker-enable", a & 1)
+ });
+ m(a.o, 64, this, function() {
+ return Kc(this, 0)
+ });
+ m(a.o, 65, this, function() {
+ return Kc(this,
+ 1)
+ });
+ m(a.o, 66, this, function() {
+ return Kc(this, 2)
+ });
+ n(a.o, 64, this, function(a) {
+ Lc(this, 0, a)
+ });
+ n(a.o, 65, this, function(a) {
+ Lc(this, 1, a)
+ });
+ n(a.o, 66, this, function(a) {
+ Lc(this, 2, a)
+ });
+ n(a.o, 67, this, this.R)
+}
+Ic.prototype.Sa = function() {
+ var a = [];
+ a[0] = this.g;
+ a[1] = this.l;
+ a[2] = this.i;
+ a[3] = this.O;
+ a[4] = this.C;
+ a[5] = this.J;
+ a[6] = this.a;
+ a[7] = this.m;
+ a[8] = this.v;
+ return a
+};
+Ic.prototype.fb = function(a) {
+ this.g = a[0];
+ this.l = a[1];
+ this.i = a[2];
+ this.O = a[3];
+ this.C = a[4];
+ this.J = a[5];
+ this.a = a[6];
+ this.m = a[7];
+ this.v = a[8]
+};
+Ic.prototype.Ic = function(a, b) {
+ b || (this.l[0] && Jc(this, 0, a) ? (this.v[0] = Mc(this, 0, a), this.m[0] = a, this.j.Cb(0), 0 === this.i[0] && (this.l[0] = 0)) : Pb(this.j, 0))
+};
+
+function Mc(a, b, c) {
+ if (!a.l[b]) return 0;
+ c = a.v[b] - Math.floor(1193.1816666 * (c - a.m[b]));
+ a = a.a[b];
+ c >= a ? c %= a : 0 > c && (c = c % a + a);
+ return c
+}
+
+function Jc(a, b, c) {
+ c -= a.m[b];
+ return 0 > c ? !0 : a.v[b] < Math.floor(1193.1816666 * c)
+}
+
+function Kc(a, b) {
+ var c = a.C[b];
+ if (c) return a.C[b]--, 2 === c ? a.J[b] & 255 : a.J[b] >> 8;
+ c = a.g[b];
+ 3 === a.i[b] && (a.g[b] ^= 1);
+ a = Mc(a, b, $a());
+ return c ? a & 255 : a >> 8
+}
+
+function Lc(a, b, c) {
+ a.a[b] = a.g[b] ? a.a[b] & -256 | c : a.a[b] & 255 | c << 8;
+ 3 === a.O[b] && a.g[b] || (a.a[b] || (a.a[b] = 65535), a.v[b] = a.a[b], a.l[b] = !0, a.m[b] = $a());
+ 3 === a.O[b] && (a.g[b] ^= 1);
+ a.w.send("pcspeaker-update", [a.i[2], a.a[2]])
+}
+Ic.prototype.R = function(a) {
+ var b = a >> 1 & 7,
+ c = a >> 6 & 3;
+ a = a >> 4 & 3;
+ 3 !== c && (0 === a ? (this.C[c] = 2, b = Mc(this, c, $a()), this.J[c] = b ? b - 1 : 0) : (6 <= b && (b &= -5), this.g[c] = 1 === a ? 0 : 1, 0 === c && Pb(this.j, 0), this.i[c] = b, this.O[c] = a, this.w.send("pcspeaker-update", [this.i[2], this.a[2]])))
+};
+var Nc = Uint32Array.from([655360, 655360, 720896, 753664]),
+ Oc = Uint32Array.from([131072, 65536, 32768, 32768]);
+
+function Pc(a, b, c) {
+ var d = this;
+ this.w = b;
+ this.Ja = c;
+ this.J = 0;
+ this.Ae = 14;
+ this.Be = 15;
+ this.R = 80;
+ this.Rd = 25;
+ this.Wg = this.sb = this.Pe = this.Fa = 0;
+ this.Bc = [];
+ this.Re = this.Ua = 0;
+ this.qc = new Uint8Array(25);
+ this.v = this.W = this.Ne = this.Z = this.a = this.i = this.uc = this.Jc = this.ab = 0;
+ this.Ce = !0;
+ this.Wa = !1;
+ setTimeout(function() {
+ b.send("screen-set-mode", d.Wa)
+ }, 0);
+ this.Jb = new Int32Array(256);
+ this.C = this.rb = this.g = 0;
+ this.ob = !1;
+ this.Hc = 32;
+ this.kg = this.dc = 0;
+ this.pe = [222, 16, 32, 10, 7, 0, 0, 0, 162, 0, 0, 3, 0, 0, 128, 0, 8, 14680064, 57344, 224,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 1, 0, 0
+ ];
+ this.Hb = 144;
+ this.nc = [{
+ size: c
+ }];
+ this.fh = 65536;
+ this.Ei = 4272947200;
+ this.name = "vga";
+ this.Oa = {
+ lg: !1,
+ jk: 0,
+ kk: 0,
+ Ag: 0
+ };
+ this.Ya = this.rc = this.Xa = this.O = 0;
+ this.Je = new Uint8Array(16);
+ this.m = -1;
+ this.Sd = 32;
+ this.hd = this.Qd = this.ce = this.tb = 0;
+ this.Vd = -1;
+ this.Ud = 15;
+ this.pc = this.Wd = 0;
+ this.tc = -1;
+ this.cc = this.Dc = this.He = 0;
+ this.Ee = 255;
+ this.qa = this.oa = this.ka = this.Bb = this.Fe = this.Td = 0;
+ this.l = this.yf = 255;
+ c = a.o;
+ n(c, 960, this, this.tj);
+ m(c, 960, this, this.kh, this.sj);
+ m(c, 961, this, this.lh);
+ n(c, 962, this, this.uj);
+ c.Gc(964, this, this.wj, this.yj);
+ m(c, 964, this, this.vj);
+ m(c, 965, this, this.xj);
+ c.Gc(974, this, this.Hj, this.Jj);
+ m(c, 974, this, this.Gj);
+ m(c, 975, this, this.Ij);
+ n(c, 967, this, this.Aj);
+ m(c, 967, this, this.zj);
+ n(c, 968, this, this.Cj);
+ m(c, 968, this, this.Bj);
+ n(c, 969, this, this.Ej);
+ m(c, 969, this, this.Dj);
+ m(c, 972, this, this.Fj);
+ c.Gc(980, this, this.Lj, this.Nj);
+ m(c, 980, this, this.Kj);
+ m(c, 981, this, this.Mj);
+ m(c, 970, this, function() {
+ return 0
+ });
+ m(c, 986, this,
+ this.mh);
+ m(c, 954, this, this.mh);
+ this.sc = -1;
+ this.Za = 0;
+ n(c, 462, this, void 0, this.Gi);
+ n(c, 463, this, void 0, this.Ii);
+ m(c, 463, this, void 0, this.Hi);
+ void 0 === this.Ja || 786432 > this.Ja ? this.Ja = 786432 : this.Ja & 65535 && (this.Ja |= 65535, this.Ja++);
+ this.ya = new Uint8Array(this.Ja);
+ this.hb = this.Ja;
+ this.bb = 0;
+ this.ge = this.Ja;
+ this.fe = 0;
+ this.ee = void 0;
+ b.register("screen-tell-buffer", function(a) {
+ this.ee && a[0] && a[0].set(this.ee.subarray(0, a[0].length));
+ this.ee = a[0]
+ }, this);
+ b.register("screen-fill-buffer", function() {
+ if (this.Wa &&
+ this.ee)
+ if (this.bb < this.hb && this.fe < this.ge) this.w.send("screen-fill-buffer-end", this.Bc);
+ else {
+ if (this.ob) {
+ var a = this.ee,
+ b = this.hb,
+ c = this.bb;
+ switch (this.Hc) {
+ case 32:
+ var e = b >> 2,
+ d = (c >> 2) + 1;
+ for (b = e; b < d; b++) c = this.Ih[b], a[b] = c << 16 | c >> 16 & 255 | c & 65280 | 4278190080;
+ break;
+ case 24:
+ e = b / 3 | 0;
+ d = (c / 3 | 0) + 1;
+ var v = 3 * e;
+ for (b = e; v < c; b++) {
+ var E = this.ya[v++],
+ z = this.ya[v++],
+ A = this.ya[v++];
+ a[b] = E << 16 | z << 8 | A | 4278190080
+ }
+ break;
+ case 16:
+ e = b >> 1;
+ d = (c >> 1) + 1;
+ for (b = e; b < d; b++) c = this.pk[b], A = 255 * (c >> 11) / 31 | 0, z = 255 * (c >> 5 & 63) / 63 | 0, E = 255 *
+ (c & 31) / 31 | 0, a[b] = E << 16 | z << 8 | A | 4278190080;
+ break;
+ case 8:
+ for (e = b, d = c + 1; b <= c; b++) z = this.Jb[this.ya[b]], a[b] = z & 65280 | z << 16 | z >> 16 | 4278190080
+ }
+ a = e / this.rb | 0;
+ this.w.send("screen-fill-buffer-end", [{
+ ug: 0,
+ vg: a,
+ qf: 0,
+ rf: a,
+ ag: this.rb,
+ $f: (d / this.rb | 0) - a + 1
+ }])
+ } else {
+ d = Math.min(this.fe | 15, 524287);
+ a = Qc(this);
+ e = ~this.ab & 3;
+ b = this.Dc & 96;
+ c = this.tb & 64;
+ for (z = this.ge & -16; z <= d;) {
+ var M = z >>> a;
+ if (e) {
+ A = z / this.sb | 0;
+ v = z - this.sb * A;
+ switch (e) {
+ case 1:
+ M = (A & 1) << 13;
+ A >>>= 1;
+ break;
+ case 2:
+ M = (A & 1) << 14;
+ A >>>= 1;
+ break;
+ case 3:
+ M = (A & 3) << 13, A >>>= 2
+ }
+ M |=
+ (A * this.sb + v >>> a) + this.Ua
+ }
+ A = this.Kf[M];
+ v = this.Lf[M];
+ E = this.Mf[M];
+ var Y = this.Nf[M];
+ M = new Uint8Array(8);
+ switch (b) {
+ case 0:
+ A <<= 0;
+ v <<= 1;
+ E <<= 2;
+ Y <<= 3;
+ for (var ka = 7; 0 <= ka; ka--) M[7 - ka] = A >> ka & 1 | v >> ka & 2 | E >> ka & 4 | Y >> ka & 8;
+ break;
+ case 32:
+ M[0] = A >> 6 & 3 | E >> 4 & 12;
+ M[1] = A >> 4 & 3 | E >> 2 & 12;
+ M[2] = A >> 2 & 3 | E >> 0 & 12;
+ M[3] = A >> 0 & 3 | E << 2 & 12;
+ M[4] = v >> 6 & 3 | Y >> 4 & 12;
+ M[5] = v >> 4 & 3 | Y >> 2 & 12;
+ M[6] = v >> 2 & 3 | Y >> 0 & 12;
+ M[7] = v >> 0 & 3 | Y << 2 & 12;
+ break;
+ case 64:
+ case 96:
+ M[0] = A >> 4 & 15, M[1] = A >> 0 & 15, M[2] = v >> 4 & 15, M[3] = v >> 0 & 15, M[4] = E >> 4 & 15, M[5] = E >> 0 & 15, M[6] = Y >> 4 & 15, M[7] = Y >>
+ 0 & 15
+ }
+ if (c)
+ for (A = ka = 0; 4 > ka; ka++, z++, A += 2) this.Jf[z] = M[A] << 4 | M[A + 1];
+ else
+ for (ka = 0; 8 > ka; ka++, z++) this.Jf[z] = M[ka]
+ }
+ c = this.hb;
+ d = Math.min(this.bb, 524287);
+ if (a = this.ee)
+ if (e = 255, b = 0, this.tb & 128 && (e &= 207, b |= this.hd << 4 & 48), this.tb & 64)
+ for (; c <= d; c++) z = this.Jf[c] & e | b, z = this.Jb[z], a[c] = z & 65280 | z << 16 | z >> 16 | 4278190080;
+ else
+ for (e &= 63, b |= this.hd << 4 & 192; c <= d; c++) z = this.Je[this.Jf[c] & this.ce] & e | b, z = this.Jb[z], a[c] = z & 65280 | z << 16 | z >> 16 | 4278190080;
+ this.w.send("screen-fill-buffer-end", this.Bc)
+ }
+ this.hb = this.Ja;
+ this.bb = 0;
+ this.ge = this.Ja;
+ this.fe = 0
+ }
+ Rc(this)
+ }, this);
+ this.pk = new Uint16Array(this.ya.buffer);
+ this.Ih = new Int32Array(this.ya.buffer);
+ this.Xd = new Uint8Array(this.ya.buffer, 0, 262144);
+ this.Kf = new Uint8Array(this.ya.buffer, 0, 65536);
+ this.Lf = new Uint8Array(this.ya.buffer, 65536, 65536);
+ this.Mf = new Uint8Array(this.ya.buffer, 131072, 65536);
+ this.Nf = new Uint8Array(this.ya.buffer, 196608, 65536);
+ this.Jf = new Uint8Array(this.ya.buffer, 262144, 524288);
+ var e = this;
+ Pa(c, 655360, 131072, function(a) {
+ return Sc(e, a)
+ }, function(a, b) {
+ if (e.ob &&
+ e.Wa && e.Ce) {
+ var c = a - 655360 | e.dc;
+ e.hb = c < e.hb ? c : e.hb;
+ e.bb = c > e.bb ? c : e.bb;
+ e.ya[c] = b
+ } else {
+ var d = e.Bb >> 2 & 3;
+ a -= Nc[d];
+ if (!(0 > a || a >= Oc[d]))
+ if (e.Wa) {
+ var f = b;
+ b = Tc(e.Ee);
+ var h = Uc(e.Td);
+ d = Uc(e.Fe);
+ switch (e.Dc & 3) {
+ case 0:
+ f = (f | f << 8) >>> (e.cc & 7) & 255;
+ c = Tc(f);
+ f = Uc(e.Td);
+ c = Vc(e, (c | d & f) & (~d | f), e.g);
+ c = b & c | ~b & e.g;
+ break;
+ case 1:
+ c = e.g;
+ break;
+ case 2:
+ c = Uc(f);
+ c = Vc(e, c, e.g);
+ c = b & c | ~b & e.g;
+ break;
+ case 3:
+ f = (f | f << 8) >>> (e.cc & 7) & 255, b &= Tc(f), c = b & h | ~b & e.g
+ }
+ b = 15;
+ switch (e.Wd & 12) {
+ case 0:
+ b = 5 << (a & 1);
+ a &= -2;
+ break;
+ case 8:
+ case 12:
+ b = 1 << (a & 3), a &= -4
+ }
+ b &=
+ e.Ud;
+ b & 1 && (e.Kf[a] = c >> 0 & 255);
+ b & 2 && (e.Lf[a] = c >> 8 & 255);
+ b & 4 && (e.Mf[a] = c >> 16 & 255);
+ b & 8 && (e.Nf[a] = c >> 24 & 255);
+ b = Wc(e, a);
+ c = b + 7;
+ b < e.ge && (e.ge = b);
+ c > e.fe && (e.fe = c);
+ b < e.hb && (e.hb = b);
+ c > e.bb && (e.bb = c)
+ } else e.Ud & 3 && (c = a, d = (c >> 1) - e.Ua, a = d / e.R | 0, d %= e.R, c & 1 ? (h = b, f = e.Xd[c & -2]) : (f = b, h = e.Xd[c | 1]), e.w.send("screen-put-char", [a, d, f, e.Jb[h >> 4 & 15], e.Jb[h & 15]]), e.Xd[c] = b)
+ }
+ });
+ Pa(c, 3758096384, this.Ja, function(a) {
+ return e.ya[a & 268435455]
+ }, function(a, b) {
+ a &= 268435455;
+ e.ya[a] = b;
+ e.hb = a < e.hb ? a : e.hb;
+ e.bb = a > e.bb ? a : e.bb
+ }, function(a) {
+ a &=
+ 268435455;
+ return a & 3 ? e.ya[a] | e.ya[a + 1] << 8 | e.ya[a + 2] << 16 | e.ya[a + 3] << 24 : e.Ih[a >> 2]
+ }, function(a, b) {
+ a &= 268435455;
+ e.hb = a < e.hb ? a : e.hb;
+ e.bb = a + 3 > e.bb ? a + 3 : e.bb;
+ e.ya[a] = b;
+ e.ya[a + 1] = b >> 8;
+ e.ya[a + 2] = b >> 16;
+ e.ya[a + 3] = b >> 24
+ });
+ Zb(a.G.wb, this)
+}
+k = Pc.prototype;
+k.Sa = function() {
+ var a = [];
+ a[0] = this.Ja;
+ a[1] = this.J;
+ a[2] = this.Ae;
+ a[3] = this.Be;
+ a[4] = this.R;
+ a[5] = this.Rd;
+ a[6] = this.Bc;
+ a[7] = this.Ya;
+ a[8] = this.Ua;
+ a[9] = this.Wa;
+ a[10] = this.Jb;
+ a[11] = this.g;
+ a[12] = this.ka;
+ a[13] = this.oa;
+ a[14] = this.Bb;
+ a[15] = this.rb;
+ a[16] = this.C;
+ a[17] = this.ab;
+ a[18] = this.ob;
+ a[19] = this.Hc;
+ a[20] = this.dc;
+ a[21] = this.kg;
+ a[22] = this.O;
+ a[23] = this.Xa;
+ a[24] = this.rc;
+ a[25] = this.Je;
+ a[26] = this.Vd;
+ a[27] = this.Ud;
+ a[28] = this.Wd;
+ a[29] = this.tc;
+ a[30] = this.He;
+ a[31] = this.Dc;
+ a[32] = this.cc;
+ a[33] = this.Ee;
+ a[34] = this.qa;
+ a[35] =
+ this.yf;